context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Pandoras Box Automation - {{ lang }} v{{ version }} @{{ time }} <support@coolux.de> */ using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace PandorasBox { /// <summary> /// The main class used to communicate with Pandoras Box /// </summary> public class PBAuto { private Connector c; public PBAuto(Connector connector) { c = connector; } public static PBAuto ConnectTcp(string ip, int domain = 0) { return new PBAuto(new TCP(ip, domain)); } public struct PBAutoResult { public bool ok { get { return error == 0; } } public short code; public int error; } {% for c in commands %} {% if c.recv|count > 0 %}public struct {{ c.name|camelize }}Result { public bool ok { get { return error == 0; } } public short code; public int error;{% for r in c.recv %} public {{types[r.type_id].name|no_suffix }}{% if types[r.type_id].name|is_buffer %}[]{%endif%} {{ r.name|camelize_small }};{% endfor %} } {% endif %}public {% if c.recv|count > 0 %}{{ c.name|camelize }}Result{%else%}PBAutoResult{%endif%} {{ c.name|camelize }}({% for a in c.send %}{% if not loop.first %}, {% endif %}{{ types[a.type_id].name|no_suffix }}{% if types[a.type_id].name|is_buffer %}[]{%endif%} {{ a.name|camelize_small }}{% endfor %}) { var b = new ByteUtil(); b.writeShort({{ c.code }});{% for a in c.send %} b.write{{ types[a.type_id].name|camelize }}({{ a.name|camelize_small }});{% endfor %} {% if c.recv|count > 0 %}b = c.Send(b, true); var r = new {{ c.name|camelize }}Result(); r.code = b.readShort(); if(r.code < 0) { r.error = b.readInt(); } else if(r.code != {{ c.code }}) { r.code = -1; r.error = 7; // WrongMessageReturned return r; } else { r.error = 0;{% for r in c.recv %} r.{{ r.name|camelize_small }} = b.read{{ types[r.type_id].name|camelize }}();{% endfor %} } return r;{% else %}b = c.Send(b, false);return new PBAutoResult(){ code = {{c.code}},error = 0 };{% endif %} }{% endfor %} } /// <summary> /// Contains extension methods for conversion between native format and byte arrays /// </summary> public static class PBUtil { public static byte PBAutoChecksum(this byte[] message) { if (message.Length < 17) throw new ArgumentException("Byte array is not a PBAuto header! Length != 17"); var checksum = 0; for(int i=4;i<16;i++) { checksum += message[i]; } return (byte)(checksum % 255); } public static long GetInt64(this byte[] bytes, int offset = 0) { byte[] value_bytes = new byte[8]; Array.Copy(bytes, offset, value_bytes, 0, 8); if (BitConverter.IsLittleEndian) { Array.Reverse(value_bytes); } return BitConverter.ToInt64(value_bytes, 0); } public static int GetInt32(this byte[] bytes, int offset = 0) { byte[] value_bytes = new byte[4]; Array.Copy(bytes, offset, value_bytes, 0, 4); if (BitConverter.IsLittleEndian) { Array.Reverse(value_bytes); } return BitConverter.ToInt32(value_bytes, 0); } public static short GetInt16(this byte[] bytes, int offset = 0) { byte[] value_bytes = new byte[2]; Array.Copy(bytes, offset, value_bytes, 0, 2); if (BitConverter.IsLittleEndian) { Array.Reverse(value_bytes); } return BitConverter.ToInt16(value_bytes, 0); } public static byte[] GetBytesNetworkOrder(this Int64 value) { var bytes = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return bytes; } public static byte[] GetBytesNetworkOrder(this int value) { var bytes = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return bytes; } public static byte[] GetBytesNetworkOrder(this short value) { var bytes = BitConverter.GetBytes(value); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); } return bytes; } } /// <summary> /// Utility class for byte conversion /// </summary> public class ByteUtil { // Holds the bytes private List<byte> list_bytes; private byte[] read_bytes; // Position for reading private int position = 0; // Constructors public ByteUtil() { list_bytes = new List<byte>(); } public ByteUtil(byte[] data) { read_bytes = data; } public void CopyTo(byte[] bytes, int offset) { list_bytes.CopyTo(bytes, offset); } public int Length { get { return list_bytes.Count; } } // Writing public void writeBool(bool value) { list_bytes.Add((byte)(value ? 1 : 0)); } public void writeByte(byte value) { list_bytes.Add(value); } public void writeShort(short value) { list_bytes.AddRange(value.GetBytesNetworkOrder() ); } public void writeInt(int value) { list_bytes.AddRange(value.GetBytesNetworkOrder()); } public void writeInt64(long value) { list_bytes.AddRange(value.GetBytesNetworkOrder()); } public void writeDouble(double value) { list_bytes.AddRange(BitConverter.GetBytes(value)); } public void writeStringNarrow(string value) { writeShort((short)value.Length); list_bytes.AddRange(Encoding.UTF8.GetBytes(value)); } public void writeStringWide(string value) { writeShort((short)value.Length); list_bytes.AddRange(Encoding.BigEndianUnicode.GetBytes(value)); } public void writeByteBuffer(byte[] value) { writeInt(value.Length); list_bytes.AddRange(value); } public void writeIntBuffer(int[] value) { foreach (var i in value) { list_bytes.AddRange(i.GetBytesNetworkOrder()); } } // Reading private byte[] _readBlock(int length) { var ret = new byte[length]; Array.Copy(read_bytes, position, ret, 0, length);position += length;return ret; } public bool readBool() { var result = read_bytes[position];position++;return result == 1; } public byte readByte() { var result = read_bytes[position];position++;return result; } public short readShort() { return _readBlock(2).GetInt16(); } public int readInt() { return _readBlock(4).GetInt32(); } public long readInt64() { return _readBlock(8).GetInt64(); } public double readDouble() { return BitConverter.ToDouble(_readBlock(8), 0); } public string readStringNarrow() { int length = readShort(); return Encoding.UTF8.GetString(_readBlock(length)); } public string readStringWide() { int length = readShort(); return Encoding.BigEndianUnicode.GetString(_readBlock(length * 2)); } public byte[] readByteBuffer() { int length = readInt(); return _readBlock(length); } public int[] readIntBuffer() { int length = (read_bytes.Length - position) / 4; int[] result = new int[length]; for (int i = 0;i < length; i++) { result[i] = _readBlock(4).GetInt32(); }; return result; } } /// <summary> /// Interface that allows PBAuto to transmit messages /// </summary> public interface Connector { ByteUtil Send(ByteUtil data, bool has_reponse); } /// <summary> /// Implements the Connector interface using TCP as the underlying protocol /// </summary> public class TCP : Connector { private string ip; private int domain; private TcpClient client; private object sendLock = new object(); private const int PORT = 6211; public TCP(string ip, int domain = 0) { this.ip = ip; this.domain = domain; client = new TcpClient(); client.NoDelay = true; client.Connect(System.Net.IPAddress.Parse(ip), PORT); } public ByteUtil Send(ByteUtil data, bool has_response) { byte[] header = new byte[17] { (byte)'P', (byte)'B', (byte)'A', (byte)'U', //# header consists of magic "PBAU" sequence 1, //# + protocol version (byte, currently 1) 0, 0, 0, 0, //# + domain id (integer) 0, 0, //# + message size (short) 0, 0, 0, 0, //# + connection id (int, user definable, defaults to 0) 0, //# + protocol flag (byte, 0 for TCP) 0, //# + checksum }; // write domain id to header domain.GetBytesNetworkOrder().CopyTo(header, 5); // write message length ((short)data.Length).GetBytesNetworkOrder().CopyTo(header, 9); // calculate checksum and write header[16] = header.PBAutoChecksum(); var message = new byte[17 + data.Length]; header.CopyTo(message, 0); data.CopyTo(message, 17); lock(sendLock) { var stream = client.GetStream(); stream.Write(message, 0, message.Length); stream.Flush(); if( !has_response ) { return null; } int bytesread = 0; while(bytesread < 17) { bytesread += stream.Read(header, bytesread, 17 - bytesread); } if(header[0] != 0x50 || header[1] != 0x42 || header[2] != 0x41 || header[3] != 0x55 || header.PBAutoChecksum() != header[16]) { // Not a PB Header or checksum fail return new ByteUtil(new byte[]{ 255, 255, 0, 0, 0, 7}); } int message_length = header.GetInt16(9); message = new byte[message_length]; bytesread = 0; while (bytesread < message_length) { bytesread += stream.Read(message, bytesread, message_length - bytesread); } } return new ByteUtil(message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Cognition.Shared.Changes; using Cognition.Shared.Documents; using Cognition.Shared.Permissions; using Cognition.Shared.Users; using Cognition.Web.ViewModels; namespace Cognition.Web.Controllers { public class DocumentController : Controller { private readonly IDocumentTypeResolver documentTypeResolver; private readonly IDocumentService documentService; private readonly IUserAuthenticationService userAuthenticationService; private readonly IDocumentUpdateNotifier documentUpdateNotifier; private readonly IPermissionService permissionService; public DocumentController(IDocumentTypeResolver documentTypeResolver, IDocumentService documentService, IUserAuthenticationService userAuthenticationService, IDocumentUpdateNotifier documentUpdateNotifier, IPermissionService permissionService) { this.documentTypeResolver = documentTypeResolver; this.documentService = documentService; this.userAuthenticationService = userAuthenticationService; this.documentUpdateNotifier = documentUpdateNotifier; this.permissionService = permissionService; } private bool CurrentUserCanViewDocument(Document document) { switch (document.Visibility) { case Document.VisibilityStatus.Internal: return permissionService.CurrentUserCanViewInternal(); case Document.VisibilityStatus.Public: return permissionService.CurrentUserCanViewPublic(); default: throw new Exception("Unknown Document visibility status."); } } private bool CurrentUserCanEdit() { return permissionService.CurrentUserCanEdit(); } public async Task<ActionResult> Index(string id, string type) { var result = await documentService.GetDocumentAsType(id, documentTypeResolver.GetDocumentType(type)); var availableVersionResult = await documentService.CountAvailableVersions(id); if (!CurrentUserCanViewDocument(result.Document)) return new HttpUnauthorizedResult(); var viewModel = new DocumentViewViewModel { Document = result.Document, PreviousVersionCount = availableVersionResult.Amount, CanEdit = CurrentUserCanEdit() }; return View(viewModel); } public async Task<ActionResult> IndexPartial(string id, string type) { var indexResult = await Index(id, type); return PartialView("_Index", ((ViewResult)indexResult).Model); } public ActionResult Create(string type) { var newDocument = GetNewDocument(type); if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); return View(newDocument); } private dynamic GetNewDocument(string type) { var documentType = documentTypeResolver.GetDocumentType(type); return Activator.CreateInstance(documentType); } [ValidateAntiForgeryToken] [HttpPost] public async Task<ActionResult> Create(FormCollection formCollection) { var newDocument = GetNewDocument(formCollection["Type"]); if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); if (TryUpdateModel(newDocument)) { ((Document) newDocument).CreatedByUserId = userAuthenticationService.GetCurrentUserEmail(); var result = await documentService.CreateNewDocument(newDocument); if (result.Success) { await documentUpdateNotifier.DocumentUpdated(new DocumentCreatedNotification(newDocument, userAuthenticationService.GetUserByEmail(userAuthenticationService.GetCurrentUserEmail()))); return RedirectToAction("Index", new { id = result.NewId, type = newDocument.Type }); } } return View(newDocument); } public async Task<ActionResult> Edit(string id, string type) { if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); var result = await documentService.GetDocumentAsType(id, documentTypeResolver.GetDocumentType(type)); return View(result.Document); } [ValidateAntiForgeryToken] [HttpPost] public async Task<ActionResult> Edit(FormCollection formCollection) { if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); var modelType = documentTypeResolver.GetDocumentType(formCollection["Type"]); var existingDocumentGetResult = await documentService.GetDocumentAsType(formCollection["Id"], modelType); dynamic existingDocument = existingDocumentGetResult.Document; if (TryUpdateModel(existingDocument)) { ((Document) existingDocument).LastUpdatedByUserId = userAuthenticationService.GetCurrentUserEmail(); var result = await documentService.UpdateDocument(formCollection["Id"], existingDocument); if (result.Success) { await documentUpdateNotifier.DocumentUpdated(new DocumentUpdateNotification(existingDocument, GetCurrentUser())); return RedirectToAction("Index", new { id = formCollection["Id"], type = formCollection["Type"] }); } } return View(existingDocument); } private User GetCurrentUser() { return userAuthenticationService.GetUserByEmail(userAuthenticationService.GetCurrentUserEmail()); } public async Task<ActionResult> List(string type, int pageSize = 20, int pageIndex = 0) { var result = await documentService.GetDocumentList(documentTypeResolver.GetDocumentType(type), type, pageSize, pageIndex); if (result.Success) { var viewModel = new DocumentListViewModel { Documents = result.Documents.ToList(), PageIndex = result.PageIndex, PageSize = result.PageSize, TotalDocuments = result.TotalDocuments, TypeName = type, TypeFullName = documentTypeResolver.GetDocumentTypeFullName(type) }; return View(viewModel); } throw new Exception(result.ErrorReason); } public async Task<ActionResult> Version(string id, string type, string v = null) { if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); var documentType = documentTypeResolver.GetDocumentType(type); var currentResult = await documentService.GetDocumentAsType(id, documentType); var versionsResult = await documentService.GetAvailableVersions(id); if (!currentResult.Success) throw new Exception("Could not load current version."); if (!versionsResult.Success) throw new Exception("Could not load versions."); var viewModel = new DocumentVersionViewModel(); viewModel.AvailableVersions = versionsResult.Versions.OrderByDescending(ver => ver.DateTime); viewModel.CurrentVersion = currentResult.Document; if (!String.IsNullOrWhiteSpace(v)) { var versionResult = await documentService.GetDocumentVersionAsType(id, documentType, v); if (versionResult.Success) { viewModel.SelectedVersionId = v; viewModel.SelectedVersion = versionResult.Document; } } else { viewModel.SelectedVersion = viewModel.CurrentVersion; } return View(viewModel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RestoreVersion(string id, string type, string versionId) { if (!CurrentUserCanEdit()) return new HttpUnauthorizedResult(); var documentType = documentTypeResolver.GetDocumentType(type); var restoreResult = await documentService.RestoreDocumentVersion(id, documentType, versionId); if (!restoreResult.Success) throw new Exception("Could not restore document version."); // TODO: Change this to "restore" event, not updated await documentUpdateNotifier.DocumentUpdated(new DocumentUpdateNotification(restoreResult.RestoredDocument, GetCurrentUser())); return RedirectToAction("Index", new {id, type}); } public async Task<ActionResult> Search(string query, int page = 0, int pageSize = 20) { var viewModel = new DocumentSearchViewModel(); var result = await documentService.SearchAllDocumentsByTitle(query, pageSize, page); if (result.Success) { viewModel.Results = result.Result; viewModel.Query = query; viewModel.PageIndex = page; viewModel.PageSize = pageSize; viewModel.TotalResult = result.TotalRecords; return View(viewModel); } else { throw new Exception("Could not load search results."); } } } }
using System; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography; using System.Threading.Tasks; using Oocx.Acme.Protocol; using Oocx.Acme.Services; using Oocx.Pkcs; namespace Oocx.Acme.Console { public class AcmeProcess : IAcmeProcess { private readonly Options options; private readonly IChallengeProvider challengeProvider; private readonly IServerConfigurationProvider serverConfiguration; private readonly IAcmeClient client; public AcmeProcess( Options options, IChallengeProvider challengeProvider, IServerConfigurationProvider serverConfiguration, IAcmeClient client) { this.options = options; this.challengeProvider = challengeProvider; this.serverConfiguration = serverConfiguration; this.client = client; } public async Task StartAsync() { IgnoreSslErrors(); await RegisterWithServer(); foreach (var domain in options.Domains) { bool isAuthorized = await AuthorizeForDomain(domain); if (!isAuthorized) { Log.Error($"authorization for domain {domain} failed"); continue; } var keyPair = GetNewKeyPair(); var certificateResponse = await RequestCertificateForDomain(domain, keyPair); var certificatePath = SaveCertificateReturnedByServer(domain, certificateResponse); SaveCertificateWithPrivateKey(domain, keyPair, certificatePath); ConfigureServer(domain, certificatePath, keyPair, options.IISWebSite, options.IISBinding); } } private void ConfigureServer(string domain, string certificatePath, RSAParameters privateKey, string siteName, string binding) { var certificateHash = serverConfiguration.InstallCertificateWithPrivateKey(certificatePath, "my", privateKey); serverConfiguration.ConfigureServer(domain, certificateHash, "my", siteName, binding); } private async Task<CertificateResponse> RequestCertificateForDomain(string domain, RSAParameters key) { var csr = CreateCertificateRequest(domain, key); return await client.NewCertificateRequestAsync(csr); } private static RSAParameters GetNewKeyPair() { var rsa = new RSACryptoServiceProvider(2048); return rsa.ExportParameters(true); } private void SaveCertificateWithPrivateKey(string domain, RSAParameters key, string certificatePath) { Log.Info("generating pfx file with certificate and private key"); GetPfxPasswordFromUser(); try { var pfxPath = Path.Combine(Environment.CurrentDirectory, $"{domain}.pfx"); Pkcs12.CreatePfxFile(key, certificatePath, options.PfxPassword, pfxPath); Log.Info($"pfx file saved to {pfxPath}"); } catch (Exception ex) { Log.Error("could not create pfx file: " + ex); } } private byte[] CreateCertificateRequest(string domain, RSAParameters key) { var data = new CertificateRequestData(domain, key); return Pkcs10.EncodeAsDer(data); } private void GetPfxPasswordFromUser() { System.Console.CursorVisible = false; while (string.IsNullOrWhiteSpace(options.PfxPassword)) { System.Console.Write("Enter password for pfx file: "); var color = System.Console.ForegroundColor; System.Console.ForegroundColor = System.Console.BackgroundColor; string pass1 = System.Console.ReadLine(); System.Console.ForegroundColor = color; System.Console.Write("Repeat the password: "); System.Console.ForegroundColor = System.Console.BackgroundColor; string pass2 = System.Console.ReadLine(); System.Console.ForegroundColor = color; if (pass1 == pass2) { options.PfxPassword = pass1; } else { System.Console.WriteLine("The passwords do not match."); } } System.Console.CursorVisible = true; } private static string SaveCertificateReturnedByServer(string domain, CertificateResponse response) { var certificatePath = Path.Combine(Environment.CurrentDirectory, $"{domain}.cer"); Log.Info($"saving certificate returned by ACME server to {certificatePath}"); File.WriteAllBytes(certificatePath, response.Certificate); return certificatePath; } private async Task<bool> AuthorizeForDomain(string domain) { var authorization = await client.NewDnsAuthorizationAsync(domain); var challenge = await challengeProvider.AcceptChallengeAsync(domain, options.IISWebSite, authorization); if (challenge == null) { return false; } System.Console.WriteLine(challenge.Instructions); if (!options.AcceptInstructions) { System.Console.WriteLine("Press ENTER to continue"); System.Console.ReadLine(); } else { System.Console.WriteLine("Automatically accepting instructions."); } var challengeResult = await challenge.Complete(); return challengeResult?.Status == "valid"; } private async Task RegisterWithServer() { // note: the terms of service is automatically populated from directory.meta.terms-of-service when null var registration = await client.RegisterAsync(new NewRegistrationRequest { Agreement = options.AcceptTermsOfService ? options.TermsOfServiceUri : null, Contact = new[] { options.Contact } }); Log.Verbose($"Created at: {registration.CreatedAt}"); Log.Verbose($"Id: {registration.Id}"); Log.Verbose($"Contact: {string.Join(", ", registration.Contact)}"); Log.Verbose($"Initial Ip: {registration.InitialIp}"); if (!string.IsNullOrWhiteSpace(registration.Location) && options.AcceptTermsOfService) { Log.Info("accepting terms of service"); if (registration.Agreement != options.TermsOfServiceUri) { Log.Error($"Cannot accept terms of service. The terms of service uri is '{registration.Agreement}', expected it to be '{options.TermsOfServiceUri}'."); return; } await client.UpdateRegistrationAsync(new UpdateRegistrationRequest( location : registration.Location, agreement : registration.Agreement, contact : new[] { options.Contact } )); } } private void IgnoreSslErrors() { if (options.IgnoreSSLCertificateErrors) { ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => { if (sslPolicyErrors != SslPolicyErrors.None) { Log.Verbose($"ignoring SSL certificate error: {sslPolicyErrors}"); } return true; }; } } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using System.Drawing; using System.Threading.Tasks; using MonoTouch.CoreGraphics; using MonoTouch.CoreAnimation; namespace XamarinStore.iOS { public class ProductDetailViewController : UITableViewController { public event Action<Product> AddToBasket = delegate {}; Product CurrentProduct; ProductSize[] sizeOptions; BottomButtonView BottomView; ProductColor[] colorOptions; StringSelectionCell colorCell, sizeCell; JBKenBurnsView imageView; UIImage tshirtIcon; public ProductDetailViewController (Product product) { CurrentProduct = product; Title = CurrentProduct.Name; LoadProductData (); TableView.TableFooterView = new UIView (new RectangleF (0, 0, 0, BottomButtonView.Height)); View.AddSubview (BottomView = new BottomButtonView () { ButtonText = "Add to Basket", Button = { Image = (tshirtIcon = UIImage.FromBundle("t-shirt")), }, ButtonTapped = async () => await addToBasket () }); } async Task addToBasket() { var center = BottomView.Button.ConvertPointToView (BottomView.Button.ImageView.Center, NavigationController.View); var imageView = new UIImageView (tshirtIcon) { Center = center, ContentMode = UIViewContentMode.ScaleAspectFill }; var backgroundView = new UIImageView (UIImage.FromBundle("circle")) { Center = center, }; NavigationController.View.AddSubview (backgroundView); NavigationController.View.AddSubview (imageView); await Task.WhenAll (new [] { animateView (imageView), animateView (backgroundView), }); NavigationItem.RightBarButtonItem = AppDelegate.Shared.CreateBasketButton (); AddToBasket (CurrentProduct); } async Task animateView(UIView view) { var size = view.Frame.Size; var grow = new SizeF(size.Width * 1.7f, size.Height * 1.7f); var shrink = new SizeF(size.Width * .4f, size.Height * .4f); TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool> (); //Set the animation path var pathAnimation = CAKeyFrameAnimation.GetFromKeyPath("position"); pathAnimation.CalculationMode = CAAnimation.AnimationPaced; pathAnimation.FillMode = CAFillMode.Forwards; pathAnimation.RemovedOnCompletion = false; pathAnimation.Duration = .5; UIBezierPath path = new UIBezierPath (); path.MoveTo (view.Center); path.AddQuadCurveToPoint (new PointF (290, 34), new PointF(view.Center.X,View.Center.Y)); pathAnimation.Path = path.CGPath; //Set size change var growAnimation = CABasicAnimation.FromKeyPath("bounds.size"); growAnimation.To = NSValue.FromSizeF (grow); growAnimation.FillMode = CAFillMode.Forwards; growAnimation.Duration = .1; growAnimation.RemovedOnCompletion = false; var shrinkAnimation = CABasicAnimation.FromKeyPath("bounds.size"); shrinkAnimation.To = NSValue.FromSizeF (shrink); shrinkAnimation.FillMode = CAFillMode.Forwards; shrinkAnimation.Duration = .4; shrinkAnimation.RemovedOnCompletion = false; shrinkAnimation.BeginTime = .1; CAAnimationGroup animations = new CAAnimationGroup (); animations.FillMode = CAFillMode.Forwards; animations.RemovedOnCompletion = false; animations.Animations = new CAAnimation[] { pathAnimation, growAnimation, shrinkAnimation, }; animations.Duration = .5; animations.AnimationStopped += (sender, e) => { tcs.TrySetResult(true); }; view.Layer.AddAnimation (animations,"movetocart"); NSTimer.CreateScheduledTimer (.5, () => view.RemoveFromSuperview ()); await tcs.Task; } string[] imageUrls = new string[0]; public void LoadProductData () { // Add spinner while loading data. TableView.Source = new ProductDetailPageSource (new [] { new SpinnerCell(), }); colorOptions = CurrentProduct.Colors; sizeOptions = CurrentProduct.Sizes; imageUrls = CurrentProduct.ImageUrls.ToArray().Shuffle(); imageView = new JBKenBurnsView { Frame = new RectangleF (0, -60, 320, 400), Images = Enumerable.Range(0,imageUrls.Length).Select(x=> new UIImage()).ToList(), UserInteractionEnabled = false, }; loadImages (); var productDescriptionView = new ProductDescriptionView (CurrentProduct) { Frame = new RectangleF (0, 0, 320, 120), }; TableView.TableHeaderView = new UIView(new RectangleF(0,0,imageView.Frame.Width,imageView.Frame.Bottom)){imageView}; var tableItems = new List<UITableViewCell> () { new CustomViewCell (productDescriptionView), }; tableItems.AddRange (GetOptionsCells ()); TableView.Source = new ProductDetailPageSource (tableItems.ToArray ()); TableView.ReloadData (); } async void loadImages() { for (int i = 0; i < imageUrls.Length; i++) { var path = await FileCache.Download (Product.ImageForSize (imageUrls [i], 320 * UIScreen.MainScreen.Scale)); imageView.Images [i] = UIImage.FromFile (path); } } IEnumerable<UITableViewCell> GetOptionsCells () { yield return sizeCell = new StringSelectionCell (View) { Text = "Size", Items = sizeOptions.Select (x => x.Description), DetailText = CurrentProduct.Size.Description, SelectionChanged = () => { var size = sizeOptions [sizeCell.SelectedIndex]; CurrentProduct.Size = size; } }; yield return colorCell = new StringSelectionCell (View) { Text = "Color", Items = colorOptions.Select (x => x.Name), DetailText = CurrentProduct.Color.Name, SelectionChanged = () => { var color = colorOptions [colorCell.SelectedIndex]; CurrentProduct.Color = color; }, }; } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); NavigationItem.RightBarButtonItem = AppDelegate.Shared.CreateBasketButton (); imageView.Animate(); var bottomRow = NSIndexPath.FromRowSection (TableView.NumberOfRowsInSection (0) - 1, 0); TableView.ScrollToRow (bottomRow,UITableViewScrollPosition.Top, false); } public override void ViewDidLayoutSubviews () { base.ViewDidLayoutSubviews (); var bound = View.Bounds; bound.Y = bound.Bottom - BottomButtonView.Height; bound.Height = BottomButtonView.Height; BottomView.Frame = bound; } } public class ProductDetailPageSource : UITableViewSource { UITableViewCell[] tableItems; public ProductDetailPageSource (UITableViewCell[] items) { tableItems = items; } public override int RowsInSection (UITableView tableview, int section) { return tableItems.Length; } public override UITableViewCell GetCell (UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath) { return tableItems [indexPath.Row]; } public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { return tableItems [indexPath.Row].Frame.Height; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { if (tableItems [indexPath.Row] is StringSelectionCell) ((StringSelectionCell)tableItems [indexPath.Row]).Tap (); tableView.DeselectRow (indexPath, true); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.PolicyAnalyzer.v1 { /// <summary>The PolicyAnalyzer Service.</summary> public class PolicyAnalyzerService : 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 PolicyAnalyzerService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public PolicyAnalyzerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "policyanalyzer"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://policyanalyzer.googleapis.com/"; #else "https://policyanalyzer.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://policyanalyzer.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Policy Analyzer API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Policy Analyzer API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for PolicyAnalyzer requests.</summary> public abstract class PolicyAnalyzerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new PolicyAnalyzerBaseServiceRequest instance.</summary> protected PolicyAnalyzerBaseServiceRequest(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 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <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> [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 = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <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> [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 PolicyAnalyzer 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 "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; Locations = new LocationsResource(service); } /// <summary>Gets the Locations resource.</summary> public virtual LocationsResource Locations { get; } /// <summary>The "locations" collection of methods.</summary> public class LocationsResource { private const string Resource = "locations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LocationsResource(Google.Apis.Services.IClientService service) { this.service = service; ActivityTypes = new ActivityTypesResource(service); } /// <summary>Gets the ActivityTypes resource.</summary> public virtual ActivityTypesResource ActivityTypes { get; } /// <summary>The "activityTypes" collection of methods.</summary> public class ActivityTypesResource { private const string Resource = "activityTypes"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ActivityTypesResource(Google.Apis.Services.IClientService service) { this.service = service; Activities = new ActivitiesResource(service); } /// <summary>Gets the Activities resource.</summary> public virtual ActivitiesResource Activities { get; } /// <summary>The "activities" collection of methods.</summary> public class ActivitiesResource { private const string Resource = "activities"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ActivitiesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Queries policy activities on Google Cloud resources.</summary> /// <param name="parent"> /// Required. The container resource on which to execute the request. Acceptable formats: /// `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` /// LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/ /// </param> public virtual QueryRequest Query(string parent) { return new QueryRequest(service, parent); } /// <summary>Queries policy activities on Google Cloud resources.</summary> public class QueryRequest : PolicyAnalyzerBaseServiceRequest<Google.Apis.PolicyAnalyzer.v1.Data.GoogleCloudPolicyanalyzerV1QueryActivityResponse> { /// <summary>Constructs a new Query request.</summary> public QueryRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The container resource on which to execute the request. Acceptable formats: /// `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` /// LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/ /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. Filter expression to restrict the activities returned. For /// serviceAccountLastAuthentication activities, supported filters are: - /// `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` /// where `[STRING]` is the full resource name of the service account. For /// serviceAccountKeyLastAuthentication activities, supported filters are: - /// `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` /// where `[STRING]` is the full resource name of the service account key. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. The maximum number of results to return from this request. Max limit is 1000. /// Non-positive values are ignored. The presence of `nextPageToken` in the response indicates /// that more results might be available. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// Optional. If present, then retrieve the next batch of results from the preceding call to /// this method. `pageToken` must be the value of `nextPageToken` from the previous response. /// The values of other method parameters should be identical to those in the previous call. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "query"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+parent}/activities:query"; /// <summary>Initializes Query parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/locations/[^/]+/activityTypes/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", 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, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } } } } namespace Google.Apis.PolicyAnalyzer.v1.Data { public class GoogleCloudPolicyanalyzerV1Activity : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A struct of custom fields to explain the activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("activity")] public virtual System.Collections.Generic.IDictionary<string, object> Activity { get; set; } /// <summary>The type of the activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("activityType")] public virtual string ActivityType { get; set; } /// <summary> /// The full resource name that identifies the resource. For examples of full resource names for Google Cloud /// services, see https://cloud.google.com/iam/help/troubleshooter/full-resource-names. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("fullResourceName")] public virtual string FullResourceName { get; set; } /// <summary>The data observation period to build the activity.</summary> [Newtonsoft.Json.JsonPropertyAttribute("observationPeriod")] public virtual GoogleCloudPolicyanalyzerV1ObservationPeriod ObservationPeriod { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents data observation period.</summary> public class GoogleCloudPolicyanalyzerV1ObservationPeriod : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The observation end time. The time in this timestamp is always `07:00:00Z`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTime")] public virtual object EndTime { get; set; } /// <summary>The observation start time. The time in this timestamp is always `07:00:00Z`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("startTime")] public virtual object StartTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response to the `QueryActivity` method.</summary> public class GoogleCloudPolicyanalyzerV1QueryActivityResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The set of activities that match the filter included in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("activities")] public virtual System.Collections.Generic.IList<GoogleCloudPolicyanalyzerV1Activity> Activities { get; set; } /// <summary> /// If there might be more results than those appearing in this response, then `nextPageToken` is included. To /// get the next set of results, call this method again using the value of `nextPageToken` as `pageToken`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class DefaultIfEmptyTests { public class DefaultIfEmpty003 { private static int DefaultIfEmpty001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.DefaultIfEmpty(5); var rst2 = q.DefaultIfEmpty(5); return Verification.Allequal(rst1, rst2); } private static int DefaultIfEmpty002() { IEnumerable<int> ieInt = Functions.NumList(0, 0); var q = from x in ieInt select x; var rst1 = q.DefaultIfEmpty(88); var rst2 = q.DefaultIfEmpty(88); return Verification.Allequal(rst1, rst2); } public static int Main() { int ret = RunTest(DefaultIfEmpty001) + RunTest(DefaultIfEmpty002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty1a { // source is empty, no defaultValue passed public static int Test1a() { int?[] source = { }; int?[] expected = { null }; var actual = source.DefaultIfEmpty(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty1b { // source is empty, no defaultValue passed public static int Test1b() { int[] source = { }; int[] expected = { default(int) }; var actual = source.DefaultIfEmpty(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty1c { // source is non-empty, no defaultValue passed public static int Test1c() { int[] source = { 3 }; int[] expected = { 3 }; var actual = source.DefaultIfEmpty(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty1d { // source is non-empty, no defaultValue passed public static int Test1d() { int[] source = { 3, -1, 0, 10, 15 }; int[] expected = { 3, -1, 0, 10, 15 }; var actual = source.DefaultIfEmpty(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty2a { // source is empty, defaultValue passed public static int Test2a() { int?[] source = { }; int? defaultValue = 9; int?[] expected = { 9 }; var actual = source.DefaultIfEmpty(defaultValue); return Verification.Allequal(expected, actual); } public static int Main() { return Test2a(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty2b { // source is empty, defaultValue passed public static int Test2b() { int[] source = { }; int defaultValue = -10; int[] expected = { -10 }; var actual = source.DefaultIfEmpty(defaultValue); return Verification.Allequal(expected, actual); } public static int Main() { return Test2b(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty2c { // source is non-empty, defaultValue passed public static int Test2c() { int[] source = { 3 }; int defaultValue = 9; int[] expected = { 3 }; var actual = source.DefaultIfEmpty(defaultValue); return Verification.Allequal(expected, actual); } public static int Main() { return Test2c(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class DefaultIfEmpty2d { // source is non-empty, defaultValue passed public static int Test2d() { int[] source = { 3, -1, 0, 10, 15 }; int defaultValue = 9; int[] expected = { 3, -1, 0, 10, 15 }; var actual = source.DefaultIfEmpty(defaultValue); return Verification.Allequal(expected, actual); } public static int Main() { return Test2d(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. /* Copyright 2007-2013 The NGenerics Team (https://github.com/ngenerics/ngenerics/wiki/Team) This program is licensed under the GNU Lesser General Public License (LGPL). You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at http://www.gnu.org/copyleft/lesser.html. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace NGenerics.DataStructures.Trees { /// <summary> /// A RedBlack Tree list variant. Equivalent to <see cref="RedBlackTree{TKey,TValue}"/> where TValue is a <see cref="LinkedList{T}"/>. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> //[Serializable] internal class RedBlackTreeList<TKey, TValue> : RedBlackTree<TKey, LinkedList<TValue>> { #region Delegates private delegate bool NodeAction(TKey key, LinkedList<TValue> values); #endregion #region Construction /// <summary> /// Initializes a new instance of the <see cref="RedBlackTreeList&lt;TKey, TValue&gt;"/> class. /// </summary> /// <inheritdoc/> public RedBlackTreeList() { // Do nothing else. } /// <inheritdoc/> public RedBlackTreeList(IComparer<TKey> comparer) : base(comparer) { // Do nothing else. } /// <inheritdoc/> public RedBlackTreeList(Comparison<TKey> comparison) : base(comparison) { // Do nothing else. } #endregion #region Public Members /// <summary> /// Determines whether the specified value contains value. /// </summary> /// <param name="value">The value.</param> /// <returns> /// <c>true</c> if the specified value contains value; otherwise, <c>false</c>. /// </returns> public bool ContainsValue(TValue value) { return TraverseItems((key, list) => list.Contains(value)); } /// <summary> /// Gets the value enumerator. /// </summary> /// <returns>An enumerator to enumerate through the values contained in this instance.</returns> public IEnumerator<TValue> GetValueEnumerator() { var stack = new Stack<BinaryTree<KeyValuePair<TKey, LinkedList<TValue>>>>(); if (Tree != null) { stack.Push(Tree); } while (stack.Count > 0) { var currentNode = stack.Pop(); var list = currentNode.Data.Value; foreach (var item in list) { yield return item; } if (currentNode.Left != null) { stack.Push(currentNode.Left); } if (currentNode.Right != null) { stack.Push(currentNode.Right); } } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IEnumerator<KeyValuePair<TKey, TValue>> GetKeyEnumerator() { var stack = new Stack<BinaryTree<KeyValuePair<TKey, LinkedList<TValue>>>>(); if (Tree != null) { stack.Push(Tree); } while (stack.Count > 0) { var currentNode = stack.Pop(); var list = currentNode.Data.Value; foreach (var item in list) { yield return new KeyValuePair<TKey, TValue>(currentNode.Data.Key, item); } if (currentNode.Left != null) { stack.Push(currentNode.Left); } if (currentNode.Right != null) { stack.Push(currentNode.Right); } } } /// <summary> /// Removes the specified value. /// </summary> /// <param name="value">The value.</param> /// <param name="key">The key under which the item was found.</param> /// <returns>A value indicating whether the item was found or not.</returns> public bool Remove(TValue value, out TKey key) { var foundKey = default(TKey); var ret = TraverseItems( delegate (TKey itemKey, LinkedList<TValue> list) { if (list.Remove(value)) { if (list.Count == 0) { Remove(itemKey); } foundKey = itemKey; return true; } return false; } ); key = foundKey; return ret; } #endregion #region Private Members /// <summary> /// Traverses the items. /// </summary> /// <param name="shouldStop">A predicate that performs an action on the list, and indicates whether the enumeration of items should stop or not.</param> /// <returns>An indication of whether the enumeration was stopped prematurely.</returns> private bool TraverseItems(NodeAction shouldStop) { #region Validation Debug.Assert(shouldStop != null); #endregion var stack = new Stack<BinaryTree<KeyValuePair<TKey, LinkedList<TValue>>>>(); if (Tree != null) { stack.Push(Tree); } while (stack.Count > 0) { var currentNode = stack.Pop(); if (shouldStop(currentNode.Data.Key, currentNode.Data.Value)) { return true; } if (currentNode.Left != null) { stack.Push(currentNode.Left); } if (currentNode.Right != null) { stack.Push(currentNode.Right); } } return false; } #endregion } }
#region Apache License // // 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. // #endregion using System; using System.Text; using System.Xml; using log4net.Core; using log4net.Util; namespace log4net.Layout { /// <summary> /// Layout that formats the log events as XML elements. /// </summary> /// <remarks> /// <para> /// The output of the <see cref="XmlLayout" /> consists of a series of /// log4net:event elements. It does not output a complete well-formed XML /// file. The output is designed to be included as an <em>external entity</em> /// in a separate file to form a correct XML file. /// </para> /// <para> /// For example, if <c>abc</c> is the name of the file where /// the <see cref="XmlLayout" /> output goes, then a well-formed XML file would /// be: /// </para> /// <code lang="XML"> /// &lt;?xml version="1.0" ?&gt; /// /// &lt;!DOCTYPE log4net:events SYSTEM "log4net-events.dtd" [&lt;!ENTITY data SYSTEM "abc"&gt;]&gt; /// /// &lt;log4net:events version="1.2" xmlns:log4net="http://logging.apache.org/log4net/schemas/log4net-events-1.2&gt; /// &amp;data; /// &lt;/log4net:events&gt; /// </code> /// <para> /// This approach enforces the independence of the <see cref="XmlLayout" /> /// and the appender where it is embedded. /// </para> /// <para> /// The <c>version</c> attribute helps components to correctly /// interpret output generated by <see cref="XmlLayout" />. The value of /// this attribute should be "1.2" for release 1.2 and later. /// </para> /// <para> /// Alternatively the <c>Header</c> and <c>Footer</c> properties can be /// configured to output the correct XML header, open tag and close tag. /// When setting the <c>Header</c> and <c>Footer</c> properties it is essential /// that the underlying data store not be appendable otherwise the data /// will become invalid XML. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class XmlLayout : XmlLayoutBase { #region Public Instance Constructors /// <summary> /// Constructs an XmlLayout /// </summary> public XmlLayout() : base() { } /// <summary> /// Constructs an XmlLayout. /// </summary> /// <remarks> /// <para> /// The <b>LocationInfo</b> option takes a boolean value. By /// default, it is set to false which means there will be no location /// information output by this layout. If the the option is set to /// true, then the file name and line number of the statement /// at the origin of the log statement will be output. /// </para> /// <para> /// If you are embedding this layout within an SmtpAppender /// then make sure to set the <b>LocationInfo</b> option of that /// appender as well. /// </para> /// </remarks> public XmlLayout(bool locationInfo) : base(locationInfo) { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// The prefix to use for all element names /// </summary> /// <remarks> /// <para> /// The default prefix is <b>log4net</b>. Set this property /// to change the prefix. If the prefix is set to an empty string /// then no prefix will be written. /// </para> /// </remarks> public string Prefix { get { return m_prefix; } set { m_prefix = value; } } /// <summary> /// Set whether or not to base64 encode the message. /// </summary> /// <remarks> /// <para> /// By default the log message will be written as text to the xml /// output. This can cause problems when the message contains binary /// data. By setting this to true the contents of the message will be /// base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the log message. /// </para> /// </remarks> public bool Base64EncodeMessage { get {return m_base64Message;} set {m_base64Message=value;} } /// <summary> /// Set whether or not to base64 encode the property values. /// </summary> /// <remarks> /// <para> /// By default the properties will be written as text to the xml /// output. This can cause problems when one or more properties contain /// binary data. By setting this to true the values of the properties /// will be base64 encoded. If this is set then invalid character replacement /// (see <see cref="XmlLayoutBase.InvalidCharReplacement"/>) will not be performed /// on the property values. /// </para> /// </remarks> public bool Base64EncodeProperties { get {return m_base64Properties;} set {m_base64Properties=value;} } #endregion Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize layout options /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// Builds a cache of the element names /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); // Cache the full element names including the prefix if (m_prefix != null && m_prefix.Length > 0) { m_elmEvent = m_prefix + ":" + ELM_EVENT; m_elmMessage = m_prefix + ":" + ELM_MESSAGE; m_elmProperties = m_prefix + ":" + ELM_PROPERTIES; m_elmData = m_prefix + ":" + ELM_DATA; m_elmException = m_prefix + ":" + ELM_EXCEPTION; m_elmLocation = m_prefix + ":" + ELM_LOCATION; } } #endregion Implementation of IOptionHandler #region Override implementation of XMLLayoutBase /// <summary> /// Does the actual writing of the XML. /// </summary> /// <param name="writer">The writer to use to output the event to.</param> /// <param name="loggingEvent">The event to write.</param> /// <remarks> /// <para> /// Override the base class <see cref="XmlLayoutBase.FormatXml"/> method /// to write the <see cref="LoggingEvent"/> to the <see cref="XmlWriter"/>. /// </para> /// </remarks> override protected void FormatXml(XmlWriter writer, LoggingEvent loggingEvent) { writer.WriteStartElement(m_elmEvent); writer.WriteAttributeString(ATTR_LOGGER, loggingEvent.LoggerName); #if NET_2_0 || NETCF_2_0 || MONO_2_0 || NET_3_5 || NET_4_0 writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp, XmlDateTimeSerializationMode.Local)); #else writer.WriteAttributeString(ATTR_TIMESTAMP, XmlConvert.ToString(loggingEvent.TimeStamp)); #endif writer.WriteAttributeString(ATTR_LEVEL, loggingEvent.Level.DisplayName); writer.WriteAttributeString(ATTR_THREAD, loggingEvent.ThreadName); if (loggingEvent.Domain != null && loggingEvent.Domain.Length > 0) { writer.WriteAttributeString(ATTR_DOMAIN, loggingEvent.Domain); } if (loggingEvent.Identity != null && loggingEvent.Identity.Length > 0) { writer.WriteAttributeString(ATTR_IDENTITY, loggingEvent.Identity); } if (loggingEvent.UserName != null && loggingEvent.UserName.Length > 0) { writer.WriteAttributeString(ATTR_USERNAME, loggingEvent.UserName); } // Append the message text writer.WriteStartElement(m_elmMessage); if (!this.Base64EncodeMessage) { Transform.WriteEscapedXmlString(writer, loggingEvent.RenderedMessage, this.InvalidCharReplacement); } else { byte[] messageBytes = Encoding.UTF8.GetBytes(loggingEvent.RenderedMessage); string base64Message = Convert.ToBase64String(messageBytes, 0, messageBytes.Length); Transform.WriteEscapedXmlString(writer, base64Message,this.InvalidCharReplacement); } writer.WriteEndElement(); PropertiesDictionary properties = loggingEvent.GetProperties(); // Append the properties text if (properties.Count > 0) { writer.WriteStartElement(m_elmProperties); foreach(System.Collections.DictionaryEntry entry in properties) { writer.WriteStartElement(m_elmData); writer.WriteAttributeString(ATTR_NAME, Transform.MaskXmlInvalidCharacters((string)entry.Key,this.InvalidCharReplacement)); // Use an ObjectRenderer to convert the object to a string string valueStr =null; if (!this.Base64EncodeProperties) { valueStr = Transform.MaskXmlInvalidCharacters(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value),this.InvalidCharReplacement); } else { byte[] propertyValueBytes = Encoding.UTF8.GetBytes(loggingEvent.Repository.RendererMap.FindAndRender(entry.Value)); valueStr = Convert.ToBase64String(propertyValueBytes, 0, propertyValueBytes.Length); } writer.WriteAttributeString(ATTR_VALUE, valueStr); writer.WriteEndElement(); } writer.WriteEndElement(); } string exceptionStr = loggingEvent.GetExceptionString(); if (exceptionStr != null && exceptionStr.Length > 0) { // Append the stack trace line writer.WriteStartElement(m_elmException); Transform.WriteEscapedXmlString(writer, exceptionStr,this.InvalidCharReplacement); writer.WriteEndElement(); } if (LocationInfo) { LocationInfo locationInfo = loggingEvent.LocationInformation; writer.WriteStartElement(m_elmLocation); writer.WriteAttributeString(ATTR_CLASS, locationInfo.ClassName); writer.WriteAttributeString(ATTR_METHOD, locationInfo.MethodName); writer.WriteAttributeString(ATTR_FILE, locationInfo.FileName); writer.WriteAttributeString(ATTR_LINE, locationInfo.LineNumber); writer.WriteEndElement(); } writer.WriteEndElement(); } #endregion Override implementation of XMLLayoutBase #region Private Instance Fields /// <summary> /// The prefix to use for all generated element names /// </summary> private string m_prefix = PREFIX; private string m_elmEvent = ELM_EVENT; private string m_elmMessage = ELM_MESSAGE; private string m_elmData = ELM_DATA; private string m_elmProperties = ELM_PROPERTIES; private string m_elmException = ELM_EXCEPTION; private string m_elmLocation = ELM_LOCATION; private bool m_base64Message=false; private bool m_base64Properties=false; #endregion Private Instance Fields #region Private Static Fields private const string PREFIX = "log4net"; private const string ELM_EVENT = "event"; private const string ELM_MESSAGE = "message"; private const string ELM_PROPERTIES = "properties"; private const string ELM_GLOBAL_PROPERTIES = "global-properties"; private const string ELM_DATA = "data"; private const string ELM_EXCEPTION = "exception"; private const string ELM_LOCATION = "locationInfo"; private const string ATTR_LOGGER = "logger"; private const string ATTR_TIMESTAMP = "timestamp"; private const string ATTR_LEVEL = "level"; private const string ATTR_THREAD = "thread"; private const string ATTR_DOMAIN = "domain"; private const string ATTR_IDENTITY = "identity"; private const string ATTR_USERNAME = "username"; private const string ATTR_CLASS = "class"; private const string ATTR_METHOD = "method"; private const string ATTR_FILE = "file"; private const string ATTR_LINE = "line"; private const string ATTR_NAME = "name"; private const string ATTR_VALUE = "value"; #endregion Private Static Fields } }
//------------------------------------------------------------------------------ // <copyright file="PatternMatcher.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.IO { using System.Text; using System.Diagnostics; using System; using Microsoft.Win32; using System.Globalization; internal static class PatternMatcher { /// <devdoc> /// Private constants (directly from C header files) /// </devdoc> private const int MATCHES_ARRAY_SIZE = 16; private const char ANSI_DOS_STAR = '>'; private const char ANSI_DOS_QM = '<'; private const char DOS_DOT = '"'; /// <devdoc> /// Tells whether a given name matches the expression given with a strict (i.e. UNIX like) /// semantics. This code is a port of unmanaged code. Original code comment follows: /// /// Routine Description: /// /// This routine compares a Dbcs name and an expression and tells the caller /// if the name is in the language defined by the expression. The input name /// cannot contain wildcards, while the expression may contain wildcards. /// /// Expression wild cards are evaluated as shown in the nondeterministic /// finite automatons below. Note that ~* and ~? are DOS_STAR and DOS_QM. /// /// /// ~* is DOS_STAR, ~? is DOS_QM, and ~. is DOS_DOT /// /// /// S /// &lt;-----&lt; /// X | | e Y /// X * Y == (0)-----&gt;-(1)-&gt;-----(2)-----(3) /// /// /// S-. /// &lt;-----&lt; /// X | | e Y /// X ~* Y == (0)-----&gt;-(1)-&gt;-----(2)-----(3) /// /// /// /// X S S Y /// X ?? Y == (0)---(1)---(2)---(3)---(4) /// /// /// /// X . . Y /// X ~.~. Y == (0)---(1)----(2)------(3)---(4) /// | |________| /// | ^ | /// |_______________| /// ^EOF or .^ /// /// /// X S-. S-. Y /// X ~?~? Y == (0)---(1)-----(2)-----(3)---(4) /// | |________| /// | ^ | /// |_______________| /// ^EOF or .^ /// /// /// /// where S is any single character /// /// S-. is any single character except the final . /// /// e is a null character transition /// /// EOF is the end of the name string /// /// In words: /// /// * matches 0 or more characters. /// /// ? matches exactly 1 character. /// /// DOS_STAR matches 0 or more characters until encountering and matching /// the final . in the name. /// /// DOS_QM matches any single character, or upon encountering a period or /// end of name string, advances the expression to the end of the /// set of contiguous DOS_QMs. /// /// DOS_DOT matches either a . or zero characters beyond name string. /// /// Arguments: /// /// Expression - Supplies the input expression to check against /// /// Name - Supplies the input name to check for. /// /// Return Value: /// /// BOOLEAN - TRUE if Name is an element in the set of strings denoted /// by the input Expression and FALSE otherwise. /// /// </devdoc> public static bool StrictMatchPattern(string expression, string name) { int nameOffset; int exprOffset; int length; int srcCount; int destCount; int previousDestCount; int matchesCount; char nameChar = '\0'; char exprChar = '\0'; int[] previousMatches = new int[MATCHES_ARRAY_SIZE]; int[] currentMatches = new int[MATCHES_ARRAY_SIZE]; int maxState; int currentState; bool nameFinished = false; // // The idea behind the algorithm is pretty simple. We keep track of // all possible locations in the regular expression that are matching // the name. If when the name has been exhausted one of the locations // in the expression is also just exhausted, the name is in the language // defined by the regular expression. // if (name == null || name.Length == 0 || expression == null || expression.Length == 0) { return false; } // // Special case by far the most common wild card search of * or *.* // if (expression.Equals("*") || expression.Equals("*.*")) { return true; } // If this class is ever exposed for generic use, // we need to make sure that name doesn't contain wildcards. Currently // the only component that calls this method is FileSystemWatcher and // it will never pass a name that contains a wildcard. // // Also special case expressions of the form *X. With this and the prior // case we have covered virtually all normal queries. // if (expression[0] == '*' && expression.IndexOf('*', 1) == -1) { int rightLength = expression.Length - 1; // if name is shorter that the stuff to the right of * in expression, we don't // need to do the string compare, otherwise we compare rightlength characters // and the end of both strings. if (name.Length >= rightLength && String.Compare(expression, 1, name, name.Length - rightLength, rightLength, StringComparison.OrdinalIgnoreCase) == 0) { return true; } } // // Walk through the name string, picking off characters. We go one // character beyond the end because some wild cards are able to match // zero characters beyond the end of the string. // // With each new name character we determine a new set of states that // match the name so far. We use two arrays that we swap back and forth // for this purpose. One array lists the possible expression states for // all name characters up to but not including the current one, and other // array is used to build up the list of states considering the current // name character as well. The arrays are then switched and the process // repeated. // // There is not a one-to-one correspondence between state number and // offset into the expression. This is evident from the NFAs in the // initial comment to this function. State numbering is not continuous. // This allows a simple conversion between state number and expression // offset. Each character in the expression can represent one or two // states. * and DOS_STAR generate two states: ExprOffset*2 and // ExprOffset*2 + 1. All other expreesion characters can produce only // a single state. Thus ExprOffset = State/2. // // // Here is a short description of the variables involved: // // NameOffset - The offset of the current name char being processed. // // ExprOffset - The offset of the current expression char being processed. // // SrcCount - Prior match being investigated with current name char // // DestCount - Next location to put a matching assuming current name char // // NameFinished - Allows one more itteration through the Matches array // after the name is exhusted (to come *s for example) // // PreviousDestCount - This is used to prevent entry duplication, see coment // // PreviousMatches - Holds the previous set of matches (the Src array) // // CurrentMatches - Holds the current set of matches (the Dest array) // // AuxBuffer, LocalBuffer - the storage for the Matches arrays // // // Set up the initial variables // previousMatches[0] = 0; matchesCount = 1; nameOffset = 0; maxState = expression.Length * 2; while (! nameFinished) { if (nameOffset < name.Length) { nameChar = name[nameOffset]; length = 1; nameOffset++; } else { nameFinished = true; // // if we have already exhasted the expression, C#. Don't // continue. // if (previousMatches[matchesCount - 1] == maxState) { break; } } // // Now, for each of the previous stored expression matches, see what // we can do with this name character. // srcCount = 0; destCount = 0; previousDestCount = 0; while (srcCount < matchesCount) { // // We have to carry on our expression analysis as far as possible // for each character of name, so we loop here until the // expression stops matching. A clue here is that expression // cases that can match zero or more characters end with a // continue, while those that can accept only a single character // end with a break. // exprOffset = ((previousMatches[srcCount++] + 1) / 2); length = 0; while (true) { if ( exprOffset == expression.Length ) { break; } // // The first time through the loop we don't want // to increment ExprOffset. // exprOffset += length; currentState = exprOffset * 2; if (exprOffset == expression.Length) { currentMatches[destCount++] = maxState; break; } exprChar = expression[exprOffset]; length = 1; // // Before we get started, we have to check for something // really gross. We may be about to exhaust the local // space for ExpressionMatches[][], so we have to allocate // some pool if this is the case. Yuk! // if (destCount >= MATCHES_ARRAY_SIZE - 2) { int newSize = currentMatches.Length * 2; int [] tmp = new int[newSize]; Array.Copy(currentMatches, tmp, currentMatches.Length); currentMatches = tmp; tmp = new int[newSize]; Array.Copy(previousMatches, tmp, previousMatches.Length); previousMatches = tmp; } // // * matches any character zero or more times. // if (exprChar == '*') { currentMatches[destCount++] = currentState; currentMatches[destCount++] = (currentState + 1); continue; } // // DOS_STAR matches any character except . zero or more times. // if (exprChar == ANSI_DOS_STAR) { bool iCanEatADot = false; // // If we are at a period, determine if we are allowed to // consume it, ie. make sure it is not the last one. // if (!nameFinished && (nameChar == '.') ) { char tmpChar; int offset; int nameLength = name.Length; for (offset = nameOffset; offset < nameLength; offset ++ ) { tmpChar = name[offset]; length = 1; if (tmpChar == '.') { iCanEatADot = true; break; } } } if (nameFinished || (nameChar != '.') || iCanEatADot) { currentMatches[destCount++] = currentState; currentMatches[destCount++] = (currentState + 1); continue; } else { // // We are at a period. We can only match zero // characters (ie. the epsilon transition). // currentMatches[destCount++] = (currentState + 1); continue; } } // // The following expreesion characters all match by consuming // a character, thus force the expression, and thus state // forward. // currentState += length * 2; // // DOS_QM is the most complicated. If the name is finished, // we can match zero characters. If this name is a '.', we // don't match, but look at the next expression. Otherwise // we match a single character. // if (exprChar == ANSI_DOS_QM) { if (nameFinished || (nameChar == '.') ) { continue; } currentMatches[destCount++] = currentState; break; } // // A DOS_DOT can match either a period, or zero characters // beyond the end of name. // if (exprChar == DOS_DOT) { if (nameFinished) { continue; } if (nameChar == '.') { currentMatches[destCount++] = currentState; break; } } // // From this point on a name character is required to even // continue, let alone make a match. // if (nameFinished) { break; } // // If this expression was a '?' we can match it once. // if (exprChar == '?') { currentMatches[destCount++] = currentState; break; } // // Finally, check if the expression char matches the name char // if (exprChar == nameChar) { currentMatches[destCount++] = currentState; break; } // // The expression didn't match so go look at the next // previous match. // break; } // // Prevent duplication in the destination array. // // Each of the arrays is montonically increasing and non- // duplicating, thus we skip over any source element in the src // array if we just added the same element to the destination // array. This guarentees non-duplication in the dest. array. // if ((srcCount < matchesCount) && (previousDestCount < destCount) ) { while (previousDestCount < destCount) { int previousLength = previousMatches.Length; while ((srcCount < previousLength) && (previousMatches[srcCount] < currentMatches[previousDestCount])) { srcCount += 1; } previousDestCount += 1; } } } // // If we found no matches in the just finished itteration, it's time // to bail. // if ( destCount == 0 ) { return false; } // // Swap the meaning the two arrays // { int[] tmp; tmp = previousMatches; previousMatches = currentMatches; currentMatches = tmp; } matchesCount = destCount; } currentState = previousMatches[matchesCount - 1]; return currentState == maxState; } } }
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 BTDB.Buffer; using BTDB.Collections; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ChunkCache { public class DiskChunkCache : IChunkCache, IDisposable { readonly IFileCollection _fileCollection; readonly int _keySize; readonly long _cacheCapacity; readonly int _sizeLimitOfOneValueFile; readonly int _maxValueFileCount; readonly ConcurrentDictionary<ByteStructs.Key20, CacheValue> _cache = new ConcurrentDictionary<ByteStructs.Key20, CacheValue>(new ByteStructs.Key20EqualityComparer()); readonly ConcurrentDictionary<uint, IFileInfo> _fileInfos = new ConcurrentDictionary<uint, IFileInfo>(); uint _cacheValueFileId; IFileCollectionFile? _cacheValueFile; ISpanWriter? _cacheValueWriter; long _fileGeneration; Task? _compactionTask; internal Task? CurrentCompactionTask() => _compactionTask; CancellationTokenSource? _compactionCts; readonly object _startNewValueFileLocker = new object(); internal static readonly byte[] MagicStartOfFile = { (byte)'B', (byte)'T', (byte)'D', (byte)'B', (byte)'C', (byte)'h', (byte)'u', (byte)'n', (byte)'k', (byte)'C', (byte)'a', (byte)'c', (byte)'h', (byte)'e', (byte)'1' }; struct CacheValue { internal uint AccessRate; internal uint FileId; internal uint FileOfs; internal uint ContentLength; } public DiskChunkCache(IFileCollection fileCollection, int keySize, long cacheCapacity) { if (keySize != 20) throw new NotSupportedException("Only keySize of 20 (Useful for SHA1) is supported for now"); if (cacheCapacity < 1000) throw new ArgumentOutOfRangeException(nameof(cacheCapacity), "Minimum for cache capacity is 1kB"); _fileCollection = fileCollection; _keySize = keySize; _cacheCapacity = cacheCapacity; cacheCapacity = cacheCapacity / 1000 * (980 - keySize); // decrease for size of HashIndex if (cacheCapacity / 8 > int.MaxValue) { _maxValueFileCount = checked((int)(cacheCapacity / int.MaxValue)); _sizeLimitOfOneValueFile = int.MaxValue; } else { _maxValueFileCount = 8; _sizeLimitOfOneValueFile = (int)(cacheCapacity / 8); } try { LoadContent(); } catch { _cache.Clear(); } if (_cache.Count != 0) return; foreach (var collectionFile in _fileInfos.Keys) { _fileCollection.GetFile(collectionFile).Remove(); } _fileInfos.Clear(); _fileGeneration = 0; } void LoadContent() { SpanReader reader; foreach (var collectionFile in _fileCollection.Enumerate()) { reader = new SpanReader(collectionFile.GetExclusiveReader()); if (!reader.CheckMagic(MagicStartOfFile)) continue; // Don't touch files alien files var fileType = (DiskChunkFileType)reader.ReadUInt8(); var fileInfo = fileType switch { DiskChunkFileType.HashIndex => new FileHashIndex(ref reader), DiskChunkFileType.PureValues => new FilePureValues(ref reader), _ => UnknownFile.Instance }; if (_fileGeneration < fileInfo.Generation) _fileGeneration = fileInfo.Generation; _fileInfos.TryAdd(collectionFile.Index, fileInfo); } var hashFilePair = _fileInfos.Where(f => f.Value.FileType == DiskChunkFileType.HashIndex).OrderByDescending( f => f.Value.Generation).FirstOrDefault(); if (hashFilePair.Value == null) return; reader = new SpanReader(_fileCollection.GetFile(hashFilePair.Key).GetExclusiveReader()); FileHashIndex.SkipHeader(ref reader); if (((FileHashIndex)hashFilePair.Value).KeySize != _keySize) return; var keyBuf = ByteBuffer.NewSync(new byte[_keySize]); while (true) { var cacheValue = new CacheValue(); cacheValue.FileOfs = reader.ReadVUInt32(); if (cacheValue.FileOfs == 0) break; cacheValue.FileId = reader.ReadVUInt32(); cacheValue.AccessRate = reader.ReadVUInt32(); cacheValue.ContentLength = reader.ReadVUInt32(); reader.ReadBlock(keyBuf); _cache.TryAdd(new ByteStructs.Key20(keyBuf), cacheValue); } } public void Put(ByteBuffer key, ByteBuffer content) { if (key.Length != _keySize) throw new ArgumentException("Key has wrong Length not equal to KeySize"); if (content.Length == 0) throw new ArgumentException("Empty Content cannot be stored"); var k = new ByteStructs.Key20(key); if (_cache.TryGetValue(k, out var cacheValue)) { return; } cacheValue.AccessRate = 1; again: var writer = _cacheValueWriter; while (writer == null || writer.GetCurrentPositionWithoutWriter() + content.Length > _sizeLimitOfOneValueFile) { StartNewValueFile(); writer = _cacheValueWriter; } lock (writer) { if (writer != _cacheValueWriter) goto again; cacheValue.FileId = _cacheValueFileId; cacheValue.FileOfs = (uint)writer.GetCurrentPositionWithoutWriter(); var trueWriter = new SpanWriter(writer); trueWriter.WriteBlock(content); trueWriter.Sync(); _cacheValueFile!.Flush(); } cacheValue.ContentLength = (uint)content.Length; _cache.TryAdd(k, cacheValue); } void StartNewValueFile() { lock (_startNewValueFileLocker) { QuickFinishCompaction(); var fileInfo = new FilePureValues(AllocNewFileGeneration()); if (_cacheValueWriter != null) { lock (_cacheValueWriter) { _cacheValueFile!.HardFlush(); SetNewValueFile(); } } else { SetNewValueFile(); } var writer = new SpanWriter(_cacheValueWriter!); fileInfo.WriteHeader(ref writer); writer.Sync(); _fileInfos.TryAdd(_cacheValueFileId, fileInfo); _compactionCts = new CancellationTokenSource(); _compactionTask = Task.Factory.StartNew(CompactionCore, _compactionCts!.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } void SetNewValueFile() { _cacheValueFile = _fileCollection.AddFile("cav"); _cacheValueFileId = _cacheValueFile.Index; _cacheValueWriter = _cacheValueFile.GetAppenderWriter(); } readonly struct RateFilePair { internal RateFilePair(ulong accessRate, uint fileId) { AccessRate = accessRate; FileId = fileId; } internal readonly ulong AccessRate; internal readonly uint FileId; } void CompactionCore() { var token = _compactionCts!.Token; var usage = new Dictionary<uint, ulong>(); var finishedUsageStats = true; uint maxAccessRate = 0; foreach (var cacheValue in _cache.Values) { if (token.IsCancellationRequested) { finishedUsageStats = false; break; } usage.TryGetValue(cacheValue.FileId, out var accessRateRunningTotal); var accessRate = cacheValue.AccessRate; if (maxAccessRate < accessRate) maxAccessRate = accessRate; accessRateRunningTotal += accessRate; usage[cacheValue.FileId] = accessRateRunningTotal; } var usageList = new List<RateFilePair>(); var fileIdsToRemove = new StructList<uint>(); foreach (var fileInfo in _fileInfos) { if (fileInfo.Value.FileType != DiskChunkFileType.PureValues) continue; if (fileInfo.Key == _cacheValueFileId) continue; if (!usage.TryGetValue(fileInfo.Key, out var accessRate) && finishedUsageStats) { fileIdsToRemove.Add(fileInfo.Key); continue; } usageList.Add(new RateFilePair(accessRate, fileInfo.Key)); } usageList.Sort((a, b) => a.AccessRate > b.AccessRate ? -1 : a.AccessRate < b.AccessRate ? 1 : 0); while (usageList.Count >= _maxValueFileCount) { var fileId = usageList.Last().FileId; if (usageList.Count == _maxValueFileCount) PreserveJustMostOftenUsed(fileId); else ClearFileFromCache(fileId); fileIdsToRemove.Add(fileId); usageList.RemoveAt(usageList.Count - 1); } FlushCurrentValueFile(); StoreHashIndex(); foreach (var fileId in fileIdsToRemove) { _fileCollection.GetFile(fileId).Remove(); _fileInfos.TryRemove(fileId); } } void FlushCurrentValueFile() { var writer = _cacheValueWriter; if (writer != null) lock (writer) { _cacheValueFile!.HardFlush(); } } void PreserveJustMostOftenUsed(uint fileId) { var frequencies = new List<uint>(); foreach (var itemPair in _cache) { if (itemPair.Value.FileId == fileId) { frequencies.Add(itemPair.Value.AccessRate); } } var preserveRate = frequencies.OrderByDescending(r => r).Skip(frequencies.Count / 5).FirstOrDefault(); foreach (var itemPair in _cache) { if (itemPair.Value.FileId == fileId) { if (preserveRate < itemPair.Value.AccessRate) { var cacheValue = itemPair.Value; var content = new byte[cacheValue.ContentLength]; _fileCollection.GetFile(cacheValue.FileId).RandomRead(content.AsSpan(0, (int)cacheValue.ContentLength), cacheValue.FileOfs, true); var writer = _cacheValueWriter; if (writer == null) { goto remove; } lock (writer) { if (writer != _cacheValueWriter) { goto remove; } if (writer.GetCurrentPositionWithoutWriter() + cacheValue.ContentLength > _sizeLimitOfOneValueFile) { goto remove; } cacheValue.FileId = _cacheValueFileId; cacheValue.FileOfs = (uint)writer.GetCurrentPositionWithoutWriter(); var trueWriter = new SpanWriter(writer); trueWriter.WriteBlock(content); trueWriter.Sync(); } _cache.TryUpdate(itemPair.Key, cacheValue, itemPair.Value); continue; } remove: _cache.TryRemove(itemPair.Key); } } } void ClearFileFromCache(uint fileId) { foreach (var itemPair in _cache) { if (itemPair.Value.FileId == fileId) { _cache.TryRemove(itemPair.Key); } } } void QuickFinishCompaction() { _compactionCts?.Cancel(); var task = _compactionTask; if (task == null) return; try { task.Wait(); } catch { // ignored because any error is irrelevant due to canceling } } public Task<ByteBuffer> Get(ByteBuffer key) { if (key.Length != _keySize) throw new ArgumentException("Key has wrong Length not equal to KeySize"); var tcs = new TaskCompletionSource<ByteBuffer>(); try { var k = new ByteStructs.Key20(key); if (_cache.TryGetValue(k, out var cacheValue)) { var newCacheValue = cacheValue; newCacheValue.AccessRate = cacheValue.AccessRate + 1; _cache.TryUpdate(k, newCacheValue, cacheValue); // It is not problem if update fails, it will have just lower access rate then real var result = new byte[cacheValue.ContentLength]; _fileCollection.GetFile(cacheValue.FileId).RandomRead( result.AsSpan(0, (int)cacheValue.ContentLength), cacheValue.FileOfs, false); tcs.SetResult(ByteBuffer.NewAsync(result)); return tcs.Task; } } catch { // It is better to return nothing than throw exception } tcs.SetResult(ByteBuffer.NewEmpty()); return tcs.Task; } public string CalcStats() { var res = new StringBuilder(); res.AppendFormat("Files {0} FileInfos {1} FileGeneration {2} Cached items {3}{4}", _fileCollection.GetCount(), _fileInfos.Count, _fileGeneration, _cache.Count, Environment.NewLine); var totalSize = 0UL; var totalControlledSize = 0UL; foreach (var fileCollectionFile in _fileCollection.Enumerate()) { _fileInfos.TryGetValue(fileCollectionFile.Index, out var fileInfo); var size = fileCollectionFile.GetSize(); totalSize += size; if (fileInfo == null) { res.AppendFormat("{0} Size: {1} Unknown to cache{2}", fileCollectionFile.Index, size, Environment.NewLine); } else { res.AppendFormat("{0} Size: {1} Type: {2} {3}", fileCollectionFile.Index, size, fileInfo.FileType, Environment.NewLine); totalControlledSize += size; } } res.AppendFormat("TotalSize {0} TotalControlledSize {1} Limit {2}{3}", totalSize, totalControlledSize, _cacheCapacity, Environment.NewLine); Debug.Assert(totalControlledSize <= (ulong)_cacheCapacity); return res.ToString(); } public void Dispose() { lock (_startNewValueFileLocker) { QuickFinishCompaction(); FlushCurrentValueFile(); StoreHashIndex(); } } void StoreHashIndex() { RemoveAllHashIndexAndUnknownFiles(); var file = _fileCollection.AddFile("chi"); var writerController = file.GetExclusiveAppenderWriter(); var writer = new SpanWriter(writerController); var keyCount = _cache.Count; var fileInfo = new FileHashIndex(AllocNewFileGeneration(), _keySize, keyCount); _fileInfos.TryAdd(file.Index, fileInfo); fileInfo.WriteHeader(ref writer); var keyBuf = ByteBuffer.NewSync(new byte[_keySize]); foreach (var cachePair in _cache) { cachePair.Key.FillBuffer(keyBuf); writer.WriteVUInt32(cachePair.Value.FileOfs); writer.WriteVUInt32(cachePair.Value.FileId); writer.WriteVUInt32(cachePair.Value.AccessRate); writer.WriteVUInt32(cachePair.Value.ContentLength); writer.WriteBlock(keyBuf); } writer.WriteVUInt32(0); // Zero FileOfs as End of file mark writer.Sync(); file.HardFlushTruncateSwitchToDisposedMode(); } void RemoveAllHashIndexAndUnknownFiles() { foreach (var infoPair in _fileInfos) { if (infoPair.Value.FileType == DiskChunkFileType.HashIndex || infoPair.Value.FileType == DiskChunkFileType.Unknown) { var fileId = infoPair.Key; _fileCollection.GetFile(fileId).Remove(); _fileInfos.TryRemove(fileId); } } } long AllocNewFileGeneration() { return Interlocked.Increment(ref _fileGeneration); } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using RestEase.Implementation.Analysis; #pragma warning disable CA1822 // Mark members as static namespace RestEase.Implementation.Emission { internal partial class DiagnosticReporter { private readonly TypeModel typeModel; public DiagnosticReporter(TypeModel typeModel) { this.typeModel = typeModel; } public void ReportTypeMustBeAccessible(TypeModel typeModel) { throw new ImplementationCreationException( DiagnosticCode.InterfaceTypeMustBeAccessible, $"Type {typeModel.Type} must be public, or internal (if you add [assembly: InternalsVisibleTo(RestClient.FactoryAssemblyName)] to your assembly)"); } public void ReportHeaderOnInterfaceMustNotHaveColonInName(TypeModel _, AttributeModel<HeaderAttribute> header) { string desc = header.Attribute.Value == null ? $"Header(\"{header.Attribute.Name}\")" : $"Header(\"{header.Attribute.Name}\", \"{header.Attribute.Value}\")"; throw new ImplementationCreationException( DiagnosticCode.HeaderMustNotHaveColonInName, $"[{desc}] on interface must not have a colon in the header name"); } public void ReportHeaderOnMethodMustNotHaveColonInName(MethodModel method, AttributeModel<HeaderAttribute> header) { throw new ImplementationCreationException( DiagnosticCode.HeaderMustNotHaveColonInName, $"[Header(\"{header.Attribute.Name}\")] on method {method.MethodInfo.Name} must not have colon in its name"); } public void ReportPropertyHeaderMustNotHaveColonInName(PropertyModel property) { var headerAttribute = property.HeaderAttribute!.Attribute; throw new ImplementationCreationException( DiagnosticCode.HeaderMustNotHaveColonInName, $"[Header(\"{headerAttribute.Name}\")] on property {property.Name} must not have a colon in its name"); } public void ReportHeaderParameterMustNotHaveColonInName(MethodModel method, ParameterModel parameter) { throw new ImplementationCreationException( DiagnosticCode.HeaderMustNotHaveColonInName, $"Method '{method.MethodInfo.Name}': [Header(\"{parameter.HeaderAttribute!.Attribute.Name}\")] must not have a colon in its name"); } public void ReportHeaderOnInterfaceMustHaveValue(TypeModel _, AttributeModel<HeaderAttribute> header) { throw new ImplementationCreationException( DiagnosticCode.HeaderOnInterfaceMustHaveValue, $"[Header(\"{header.Attribute.Name}\")] on interface must have the form [Header(\"Name\", \"Value\")]"); } public void ReportAllowAnyStatusCodeAttributeNotAllowedOnParentInterface(TypeModel _, AttributeModel<AllowAnyStatusCodeAttribute> attribute) { throw new ImplementationCreationException( DiagnosticCode.AllowAnyStatusCodeAttributeNotAllowedOnParentInterface, $"Parent interface {attribute.DeclaringMember!.Name} may not have any [AllowAnyStatusCode] attributes"); } public void ReportEventNotAllowed(EventModel _) { throw new ImplementationCreationException( DiagnosticCode.EventsNotAllowed, "Interfaces must not have any events"); } public void ReportPropertyMustHaveOneAttribute(PropertyModel property) { throw new ImplementationCreationException( DiagnosticCode.PropertyMustHaveOneAttribute, $"Property {property.PropertyInfo.Name} must have exactly one attribute"); } public void ReportPropertyMustBeReadOnly(PropertyModel property) { throw new ImplementationCreationException( DiagnosticCode.PropertyMustBeReadOnly, $"Property {property.PropertyInfo.Name} must have a getter but not a setter"); } public void ReportPropertyMustBeReadWrite(PropertyModel property) { throw new ImplementationCreationException( DiagnosticCode.PropertyMustBeReadWrite, $"Property {property.PropertyInfo.Name} must have a getter and a setter"); } public void ReportRequesterPropertyMustHaveZeroAttributes(PropertyModel property, List<AttributeModel> attributes) { throw new ImplementationCreationException( DiagnosticCode.RequesterPropertyMustHaveZeroAttributes, $"{nameof(IRequester)} property {property.PropertyInfo.Name} must not have the following attributes: {string.Join(", ", attributes.Select(x => x.AttributeName))}"); } public void ReportMultipleRequesterProperties(PropertyModel property) { throw new ImplementationCreationException( DiagnosticCode.MultipleRequesterProperties, $"Property {property.PropertyInfo.Name}: there must not be more than one property of type {nameof(IRequester)}"); } public void ReportBaseAddressMustBeAbsolute(TypeModel _, AttributeModel<BaseAddressAttribute> attribute) { throw new ImplementationCreationException( DiagnosticCode.BaseAddressMustBeAbsolute, $"Base address '{attribute.Attribute.BaseAddress}' must be an absolute URI"); } public void ReportMissingPathPropertyForBaseAddressPlaceholder(TypeModel _, AttributeModel<BaseAddressAttribute> attribute, string missingParam) { throw new ImplementationCreationException( DiagnosticCode.MissingPathPropertyForBaseAddressPlaceholder, $"Unable to find a [Path(\"{missingParam}\")] property for the path placeholder '{{{missingParam}}}' in [BaseAddress(\"{attribute.Attribute.BaseAddress}\")]"); } public void ReportMissingPathPropertyForBasePathPlaceholder(TypeModel _, AttributeModel<BasePathAttribute> attribute, string missingParam) { throw new ImplementationCreationException( DiagnosticCode.MissingPathPropertyForBasePathPlaceholder, $"Unable to find a [Path(\"{missingParam}\")] property for the path placeholder '{{{missingParam}}}' in [BasePath(\"{attribute.Attribute.BasePath}\")]"); } public void ReportMethodMustHaveRequestAttribute(MethodModel method) { throw new ImplementationCreationException( DiagnosticCode.MethodMustHaveRequestAttribute, $"Method {method.MethodInfo.Name} does not have a suitable [Get] / [Post] / etc attribute on it"); } public void ReportMethodMustHaveOneRequestAttribute(MethodModel method) { throw new ImplementationCreationException( DiagnosticCode.MethodMustHaveOneRequestAttribute, $"Method {method.MethodInfo.Name} must have a single request-related attribute, found " + $"({string.Join(", ", method.RequestAttributes.Select(x => Regex.Replace(x.AttributeName, "Attribute$", "")))})"); } public void ReportMultiplePathPropertiesForKey(string key, IEnumerable<PropertyModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultiplePathPropertiesForKey, $"Found more than one path property for key {key}"); } public void ReportMultiplePathParametersForKey(MethodModel method, string key, IEnumerable<ParameterModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultiplePathParametersForKey, $"Method '{method.MethodInfo.Name}': Found more than one path property for key '{key}'"); } public void ReportHeaderPropertyWithValueMustBeNullable(PropertyModel property) { var headerAttribute = property.HeaderAttribute!.Attribute; throw new ImplementationCreationException( DiagnosticCode.HeaderPropertyWithValueMustBeNullable, $"[Header(\"{headerAttribute.Name}\", \"{headerAttribute.Value}\")] on property {property.Name} (i.e. containing a default value) can only be used if the property type is nullable"); } public void ReportMissingPathPropertyOrParameterForPlaceholder(MethodModel method, AttributeModel<RequestAttributeBase> _, string placeholder) { throw new ImplementationCreationException( DiagnosticCode.MissingPathPropertyOrParameterForPlaceholder, $"Method '{method.MethodInfo.Name}': unable to find a [Path(\"{placeholder}\")] property or parameter for the path placeholder '{{{placeholder}}}'"); } public void ReportMissingPlaceholderForPathParameter(MethodModel method, string placeholder, IEnumerable<ParameterModel> _) { throw new ImplementationCreationException( DiagnosticCode.MissingPlaceholderForPathParameter, $"Method '{method.MethodInfo.Name}': unable to find to find a placeholder {{{placeholder}}} for the path parameter '{placeholder}'"); } public void ReportMultipleHttpRequestMessagePropertiesForKey(string key, IEnumerable<PropertyModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultipleHttpRequestMessagePropertiesForKey, $"Found more than one property with a HttpRequestMessageProperty key of '{key}'"); } public void ReportHttpRequestMessageParamDuplicatesPropertyForKey(MethodModel method, string key, PropertyModel property, ParameterModel parameter) { throw new ImplementationCreationException( DiagnosticCode.HttpRequestMessageParamDuplicatesPropertyForKey, $"Method '{method.MethodInfo.Name}': HttpRequestMessageProperty parameter '{parameter.Name}' with key '{key}' duplicates property '{property.Name}'"); } public void ReportMultipleHttpRequestMessageParametersForKey(MethodModel method, string key, IEnumerable<ParameterModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultipleHttpRequestMessageParametersForKey, $"Method '{method.MethodInfo.Name}': found more than one parameter with a HttpRequestMessageProperty key of '{key}'"); } public void ReportParameterMustHaveZeroOrOneAttributes(MethodModel method, ParameterModel parameter, List<AttributeModel> attributes) { throw new ImplementationCreationException( DiagnosticCode.ParameterMustHaveZeroOrOneAttributes, $"Method '{method.MethodInfo.Name}': parameter '{parameter.Name}' has {attributes.Count} attributes, but it must have zero or one"); } public void ReportParameterMustNotBeByRef(MethodModel method, ParameterModel parameter) { throw new ImplementationCreationException( DiagnosticCode.ParameterMustNotBeByRef, $"Method '{method.MethodInfo.Name}': parameter '{parameter.Name}' must not be ref, in or out"); } public void ReportMultipleCancellationTokenParameters(MethodModel method, IEnumerable<ParameterModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultipleCancellationTokenParameters, $"Method '{method.MethodInfo.Name}': only a single CancellationToken parameter is allowed"); } public void ReportCancellationTokenMustHaveZeroAttributes(MethodModel method, ParameterModel parameter) { throw new ImplementationCreationException( DiagnosticCode.CancellationTokenMustHaveZeroAttributes, $"Method '{method.MethodInfo.Name}': CancellationToken parameter '{parameter.Name}' must not have any attributes"); } public void ReportMultipleBodyParameters(MethodModel method, IEnumerable<ParameterModel> _) { throw new ImplementationCreationException( DiagnosticCode.MultipleBodyParameters, $"Method '{method.MethodInfo.Name}': found more than one parameter with a [Body] attribute"); } public void ReportQueryMapParameterIsNotADictionary(MethodModel method, ParameterModel _) { throw new ImplementationCreationException( DiagnosticCode.QueryMapParameterIsNotADictionary, $"Method '{method.MethodInfo.Name}': [QueryMap] parameter is not of type IDictionary or IDictionary<TKey, TValue> (or one of their descendents)"); } public void ReportHeaderParameterMustNotHaveValue(MethodModel method, ParameterModel parameter) { var attribute = parameter.HeaderAttribute!.Attribute; throw new ImplementationCreationException( DiagnosticCode.HeaderParameterMustNotHaveValue, $"Method '{method.MethodInfo.Name}': [Header(\"{attribute.Name}\", \"{attribute.Value}\")] must have the form [Header(\"Name\")], not [Header(\"Name\", \"Value\")]"); } public void ReportMethodMustHaveValidReturnType(MethodModel method) { throw new ImplementationCreationException( DiagnosticCode.MethodMustHaveValidReturnType, $"Method '{method.MethodInfo.Name}': must have a return type of Task<T> or Task"); } } } #pragma warning restore CA1822 // Mark members as static
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using App.Animation; namespace AnimationPipeline { /// <summary> /// This class extends the standard ModelProcessor to include code /// that extracts a skeleton, pulls any animations, and does any /// necessary prep work to support animation and skinning. /// </summary> [ContentProcessor(DisplayName = "Animation Processor")] public class AnimationProcessor : ModelProcessor { /// <summary> /// The model we are reading /// </summary> private ModelContent model; /// <summary> /// Extra content to associated with the model. This is where we put the stuff that is /// unique to this project. /// </summary> private ModelExtra modelExtra = new ModelExtra(); /// <summary> /// A lookup dictionary that remembers when we changes a material to /// skinned material. /// </summary> private Dictionary<MaterialContent, SkinnedMaterialContent> toSkinnedMaterial = new Dictionary<MaterialContent, SkinnedMaterialContent>(); /// <summary> /// The function to process a model from original content into model content for export /// </summary> /// <param name="input"></param> /// <param name="context"></param> /// <returns></returns> public override ModelContent Process(NodeContent input, ContentProcessorContext context) { // Process the skeleton for skinned character animation BoneContent skeleton = ProcessSkeleton(input); SwapSkinnedMaterial(input); model = base.Process(input, context); ProcessAnimations(model, input, context); // Add the extra content to the model model.Tag = modelExtra; return model; } #region Skeleton Support /// <summary> /// Process the skeleton in support of skeletal animation... /// </summary> /// <param name="input"></param> private BoneContent ProcessSkeleton(NodeContent input) { // Find the skeleton. BoneContent skeleton = MeshHelper.FindSkeleton(input); if (skeleton == null) return null; // We don't want to have to worry about different parts of the model being // in different local coordinate systems, so let's just bake everything. FlattenTransforms(input, skeleton); // // 3D Studio Max includes helper bones that end with "Nub" // These are not part of the skinning system and can be // discarded. TrimSkeleton removes them from the geometry. // TrimSkeleton(skeleton); // Convert the heirarchy of nodes and bones into a list List<NodeContent> nodes = FlattenHeirarchy(input); IList<BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton); // Create a dictionary to convert a node to an index into the array of nodes Dictionary<NodeContent, int> nodeToIndex = new Dictionary<NodeContent, int>(); for (int i = 0; i < nodes.Count; i++) { nodeToIndex[nodes[i]] = i; } // Now create the array that maps the bones to the nodes foreach (BoneContent bone in bones) { modelExtra.Skeleton.Add(nodeToIndex[bone]); } return skeleton; } /// <summary> /// Convert a tree of nodes into a list of nodes in topological order. /// </summary> /// <param name="item">The root of the heirarchy</param> /// <returns></returns> private List<NodeContent> FlattenHeirarchy(NodeContent item) { List<NodeContent> nodes = new List<NodeContent>(); nodes.Add(item); foreach (NodeContent child in item.Children) { FlattenHeirarchy(nodes, child); } return nodes; } private void FlattenHeirarchy(List<NodeContent> nodes, NodeContent item) { nodes.Add(item); foreach (NodeContent child in item.Children) { FlattenHeirarchy(nodes, child); } } /// <summary> /// Bakes unwanted transforms into the model geometry, /// so everything ends up in the same coordinate system. /// </summary> void FlattenTransforms(NodeContent node, BoneContent skeleton) { foreach (NodeContent child in node.Children) { // Don't process the skeleton, because that is special. if (child == skeleton) continue; // This is important: Don't bake in the transforms except // for geometry that is part of a skinned mesh if(IsSkinned(child)) { FlattenAllTransforms(child); } } } /// <summary> /// Recursively flatten all transforms from this node down /// </summary> /// <param name="node"></param> void FlattenAllTransforms(NodeContent node) { // Bake the local transform into the actual geometry. MeshHelper.TransformScene(node, node.Transform); // Having baked it, we can now set the local // coordinate system back to identity. node.Transform = Matrix.Identity; foreach (NodeContent child in node.Children) { FlattenAllTransforms(child); } } /// <summary> /// 3D Studio Max includes an extra help bone at the end of each /// IK chain that doesn't effect the skinning system and is /// redundant as far as any game is concerned. This function /// looks for children who's name ends with "Nub" and removes /// them from the heirarchy. /// </summary> /// <param name="skeleton">Root of the skeleton tree</param> void TrimSkeleton(NodeContent skeleton) { List<NodeContent> todelete = new List<NodeContent>(); foreach (NodeContent child in skeleton.Children) { if (child.Name.EndsWith("Nub") || child.Name.EndsWith("Footsteps")) todelete.Add(child); else TrimSkeleton(child); } foreach (NodeContent child in todelete) { skeleton.Children.Remove(child); } } #endregion #region Skinned Support /// <summary> /// Determine if a node is a skinned node, meaning it has bone weights /// associated with it. /// </summary> /// <param name="node"></param> /// <returns></returns> bool IsSkinned(NodeContent node) { // It has to be a MeshContent node MeshContent mesh = node as MeshContent; if (mesh != null) { // In the geometry we have to find a vertex channel that // has a bone weight collection foreach (GeometryContent geometry in mesh.Geometry) { foreach (VertexChannel vchannel in geometry.Vertices.Channels) { if (vchannel is VertexChannel<BoneWeightCollection>) return true; } } } return false; } /// <summary> /// If a node is skinned, we need to use the skinned model /// effect rather than basic effect. This function runs through the /// geometry and finds the meshes that have bone weights associated /// and swaps in the skinned effect. /// </summary> /// <param name="node"></param> void SwapSkinnedMaterial(NodeContent node) { // It has to be a MeshContent node MeshContent mesh = node as MeshContent; if (mesh != null) { // In the geometry we have to find a vertex channel that // has a bone weight collection foreach (GeometryContent geometry in mesh.Geometry) { bool swap = false; foreach (VertexChannel vchannel in geometry.Vertices.Channels) { if (vchannel is VertexChannel<BoneWeightCollection>) { swap = true; break; } } if (swap) { if (toSkinnedMaterial.ContainsKey(geometry.Material)) { // We have already swapped it geometry.Material = toSkinnedMaterial[geometry.Material]; } else { SkinnedMaterialContent smaterial = new SkinnedMaterialContent(); BasicMaterialContent bmaterial = geometry.Material as BasicMaterialContent; // Copy over the data smaterial.Alpha = bmaterial.Alpha; smaterial.DiffuseColor = bmaterial.DiffuseColor; smaterial.EmissiveColor = bmaterial.EmissiveColor; smaterial.SpecularColor = bmaterial.SpecularColor; smaterial.SpecularPower = bmaterial.SpecularPower; smaterial.Texture = bmaterial.Texture; smaterial.WeightsPerVertex = 4; toSkinnedMaterial[geometry.Material] = smaterial; geometry.Material = smaterial; } } } } foreach (NodeContent child in node.Children) { SwapSkinnedMaterial(child); } } #endregion #region Animation Support /// <summary> /// Bones lookup table, converts bone names to indices. /// </summary> private Dictionary<string, int> bones = new Dictionary<string, int>(); /// <summary> /// This will keep track of all of the bone transforms for a base pose /// </summary> private Matrix[] boneTransforms; /// <summary> /// A dictionary so we can keep track of the clips by name /// </summary> private Dictionary<string, AnimationClip> clips = new Dictionary<string, AnimationClip>(); /// <summary> /// Entry point for animation processing. /// </summary> /// <param name="model"></param> /// <param name="input"></param> /// <param name="context"></param> private void ProcessAnimations(ModelContent model, NodeContent input, ContentProcessorContext context) { // First build a lookup table so we can determine the // index into the list of bones from a bone name. for (int i = 0; i < model.Bones.Count; i++) { bones[model.Bones[i].Name] = i; } // For saving the bone transforms boneTransforms = new Matrix[model.Bones.Count]; // // Collect up all of the animation data // ProcessAnimationsRecursive(input); // Ensure there is always a clip, even if none is included in the FBX // That way we can create poses using FBX files as one-frame // animation clips if (modelExtra.Clips.Count == 0) { AnimationClip clip = new AnimationClip(); modelExtra.Clips.Add(clip); string clipName = "Take 001"; // Retain by name clips[clipName] = clip; clip.Name = clipName; foreach (ModelBoneContent bone in model.Bones) { AnimationClip.Bone clipBone = new AnimationClip.Bone(); clipBone.Name = bone.Name; clip.Bones.Add(clipBone); } } // Ensure all animations have a first key frame for every bone foreach (AnimationClip clip in modelExtra.Clips) { for (int b = 0; b < bones.Count; b++) { List<AnimationClip.Keyframe> keyframes = clip.Bones[b].Keyframes; if (keyframes.Count == 0 || keyframes[0].Time > 0) { AnimationClip.Keyframe keyframe = new AnimationClip.Keyframe(); keyframe.Time = 0; keyframe.Transform = boneTransforms[b]; keyframes.Insert(0, keyframe); } } } } /// <summary> /// Recursive function that processes the entire scene graph, collecting up /// all of the animation data. /// </summary> private void ProcessAnimationsRecursive(NodeContent input) { // Look up the bone for this input channel int inputBoneIndex; if (bones.TryGetValue(input.Name, out inputBoneIndex)) { // Save the transform boneTransforms[inputBoneIndex] = input.Transform; } foreach (KeyValuePair<string, AnimationContent> animation in input.Animations) { // Do we have this animation before? AnimationClip clip; string clipName = animation.Key; if (!clips.TryGetValue(clipName, out clip)) { // Never seen before clip clip = new AnimationClip(); modelExtra.Clips.Add(clip); // Retain by name clips[clipName] = clip; clip.Name = clipName; foreach (ModelBoneContent bone in model.Bones) { AnimationClip.Bone clipBone = new AnimationClip.Bone(); clipBone.Name = bone.Name; clip.Bones.Add(clipBone); } } // Ensure the duration is always set if (animation.Value.Duration.TotalSeconds > clip.Duration) clip.Duration = animation.Value.Duration.TotalSeconds; // // For each channel, determine the bone and then process all of the // keyframes for that bone. // foreach (KeyValuePair<string, AnimationChannel> channel in animation.Value.Channels) { // What is the bone index? int boneIndex; if (!bones.TryGetValue(channel.Key, out boneIndex)) continue; // Ignore if not a named bone // An animation is useless if it is for a bone not assigned to any meshes at all if (UselessAnimationTest(boneIndex)) continue; // I'm collecting up in a linked list so we can process the data // and remove redundant keyframes LinkedList<AnimationClip.Keyframe> keyframes = new LinkedList<AnimationClip.Keyframe>(); foreach (AnimationKeyframe keyframe in channel.Value) { Matrix transform = keyframe.Transform; // Keyframe transformation AnimationClip.Keyframe newKeyframe = new AnimationClip.Keyframe(); newKeyframe.Time = keyframe.Time.TotalSeconds; newKeyframe.Transform = transform; keyframes.AddLast(newKeyframe); } LinearKeyframeReduction(keyframes); foreach (AnimationClip.Keyframe keyframe in keyframes) { clip.Bones[boneIndex].Keyframes.Add(keyframe); } } } foreach (NodeContent child in input.Children) { ProcessAnimationsRecursive(child); } } private const float TinyLength = 1e-8f; private const float TinyCosAngle = 0.9999999f; /// <summary> /// This function filters out keyframes that can be approximated well with /// linear interpolation. /// </summary> /// <param name="keyframes"></param> private void LinearKeyframeReduction(LinkedList<AnimationClip.Keyframe> keyframes) { if (keyframes.Count < 3) return; for (LinkedListNode<AnimationClip.Keyframe> node = keyframes.First.Next; ; ) { LinkedListNode<AnimationClip.Keyframe> next = node.Next; if (next == null) break; // Determine nodes before and after the current node. AnimationClip.Keyframe a = node.Previous.Value; AnimationClip.Keyframe b = node.Value; AnimationClip.Keyframe c = next.Value; float t = (float)((node.Value.Time - node.Previous.Value.Time) / (next.Value.Time - node.Previous.Value.Time)); Vector3 translation = Vector3.Lerp(a.Translation, c.Translation, t); Quaternion rotation = Quaternion.Slerp(a.Rotation, c.Rotation, t); if ((translation - b.Translation).LengthSquared() < TinyLength && Quaternion.Dot(rotation, b.Rotation) > TinyCosAngle) { keyframes.Remove(node); } node = next; } } /// <summary> /// Discard any animation not assigned to a mesh or the skeleton /// </summary> /// <param name="boneId"></param> /// <returns></returns> bool UselessAnimationTest(int boneId) { // If any mesh is assigned to this bone, it is not useless foreach (ModelMeshContent mesh in model.Meshes) { if (mesh.ParentBone.Index == boneId) return false; } // If this bone is in the skeleton, it is not useless foreach (int b in modelExtra.Skeleton) { if (boneId == b) return false; } // Otherwise, it is useless return true; } #endregion } }
// // PlaylistFileUtil.cs // // Authors: // Trey Ethridge <tale@juno.com> // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // Ting Z Zhou <ting.z.zhou@intel.com> // // Copyright (C) 2007 Trey Ethridge // Copyright (C) 2007-2009 Novell, Inc. // Copyright (C) 2010 Intel Corp // // 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.IO; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.Database; using Banshee.Sources; using Banshee.Playlists.Formats; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Streaming; namespace Banshee.Playlist { public class PlaylistImportCanceledException : ApplicationException { public PlaylistImportCanceledException (string message) : base (message) { } public PlaylistImportCanceledException () : base () { } } public static class PlaylistFileUtil { public static readonly SchemaEntry<string> DefaultExportFormat = new SchemaEntry<string> ( "player_window", "default_export_format", String.Empty, "Export Format", "The default playlist export format" ); private static PlaylistFormatDescription [] export_formats = new PlaylistFormatDescription [] { M3uPlaylistFormat.FormatDescription, PlsPlaylistFormat.FormatDescription, XspfPlaylistFormat.FormatDescription }; public static readonly string [] PlaylistExtensions = new string [] { M3uPlaylistFormat.FormatDescription.FileExtension, PlsPlaylistFormat.FormatDescription.FileExtension, XspfPlaylistFormat.FormatDescription.FileExtension }; public static PlaylistFormatDescription [] ExportFormats { get { return export_formats; } } public static bool IsSourceExportSupported (Source source) { bool supported = true; if (source == null || !(source is AbstractPlaylistSource)) { supported = false; } return supported; } public static PlaylistFormatDescription GetDefaultExportFormat () { PlaylistFormatDescription default_format = null; try { string exportFormat = DefaultExportFormat.Get (); PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; foreach (PlaylistFormatDescription format in formats) { if (format.FileExtension.Equals (exportFormat)) { default_format = format; break; } } } catch { // Ignore errors, return our default if we encounter an error. } finally { if (default_format == null) { default_format = M3uPlaylistFormat.FormatDescription; } } return default_format; } public static void SetDefaultExportFormat (PlaylistFormatDescription format) { try { DefaultExportFormat.Set (format.FileExtension); } catch (Exception) { } } public static int GetFormatIndex (PlaylistFormatDescription [] formats, PlaylistFormatDescription playlist) { int default_export_index = -1; foreach (PlaylistFormatDescription format in formats) { default_export_index++; if (format.FileExtension.Equals (playlist.FileExtension)) { break; } } return default_export_index; } public static bool PathHasPlaylistExtension (string playlistUri) { if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri).ToLower (); foreach (PlaylistFormatDescription format in PlaylistFileUtil.ExportFormats) { if (extension.Equals ("." + format.FileExtension)) { return true; } } } return false; } public static IPlaylistFormat Load (string playlistUri, Uri baseUri, Uri rootPath) { PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; // If the file has an extenstion, rearrange the format array so that the // appropriate format is tried first. if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri); extension = extension.ToLower (); int index = -1; foreach (PlaylistFormatDescription format in formats) { index++; if (extension.Equals ("." + format.FileExtension)) { break; } } if (index != -1 && index != 0 && index < formats.Length) { // Move to first position in array. PlaylistFormatDescription preferredFormat = formats[index]; formats[index] = formats[0]; formats[0] = preferredFormat; } } foreach (PlaylistFormatDescription format in formats) { try { IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type); playlist.BaseUri = baseUri; playlist.RootPath = rootPath; playlist.Load (Banshee.IO.File.OpenRead (new SafeUri (playlistUri)), true); return playlist; } catch (InvalidPlaylistException) { } } return null; } public static void ImportPlaylistToLibrary (string path) { ImportPlaylistToLibrary (path, null, null); } public static void ImportPlaylistToLibrary (string path, PrimarySource source, DatabaseImportManager importer) { try { Log.InformationFormat ("Importing playlist {0} to library", path); SafeUri uri = new SafeUri (path); string relative_dir = System.IO.Path.GetDirectoryName (uri.LocalPath); if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar) { relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar; } var parsed_playlist = PlaylistParser.Parse (uri, new Uri (relative_dir)); if (parsed_playlist != null) { List<string> uris = new List<string> (); foreach (PlaylistElement element in parsed_playlist.Elements) { if (element.Uri.IsFile) { uris.Add (element.Uri.LocalPath); } else { Log.InformationFormat ("Ignoring invalid playlist element: {0}", element.Uri.OriginalString); } } if (source == null) { if (uris.Count > 0) { // Get the media attribute of the 1st Uri in Playlist // and then determine whether the playlist belongs to Video or Music SafeUri uri1 = new SafeUri (uris[0]); var track = new TrackInfo (); StreamTagger.TrackInfoMerge (track, uri1); if (track.HasAttribute (TrackMediaAttributes.VideoStream)) Log.Information("Ignoring playlist containing videos"); else source = ServiceManager.SourceManager.MusicLibrary; } } // Give source a fallback value - MusicLibrary when it's null if (source == null) { source = ServiceManager.SourceManager.MusicLibrary; } // Only import an non-empty playlist if (uris.Count > 0) { ImportPlaylistWorker worker = new ImportPlaylistWorker ( parsed_playlist.Title, uris.ToArray (), source, importer); worker.Import (); } } } catch (Exception e) { Log.Error (e); } } } public class ImportPlaylistWorker { private string [] uris; private string name; private PrimarySource source; private DatabaseImportManager importer; private bool finished; public ImportPlaylistWorker (string name, string [] uris, PrimarySource source, DatabaseImportManager importer) { this.name = name; this.uris = uris; this.source = source; this.importer = importer; } public void Import () { try { if (importer == null) { importer = new Banshee.Library.LibraryImportManager (); } finished = false; importer.Finished += CreatePlaylist; importer.Enqueue (uris); } catch (PlaylistImportCanceledException e) { Log.Warning (e); } } private void CreatePlaylist (object o, EventArgs args) { if (finished) { return; } finished = true; try { PlaylistSource playlist = new PlaylistSource (name, source); playlist.Save (); source.AddChildSource (playlist); HyenaSqliteCommand insert_command = new HyenaSqliteCommand (String.Format ( @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES ({0}, ?)", playlist.DbId)); //ServiceManager.DbConnection.BeginTransaction (); foreach (string uri in uris) { // FIXME: Does the following call work if the source is just a PrimarySource (not LibrarySource)? long track_id = source.GetTrackIdForUri (uri); if (track_id > 0) { ServiceManager.DbConnection.Execute (insert_command, track_id); } } playlist.Reload (); playlist.NotifyUser (); } catch (Exception e) { Log.Error (e); } } } }
using System; using NUnit.Framework; using it.unifi.dsi.stlab.networkreasoner.model.textualinterface; using it.unifi.dsi.stlab.networkreasoner.model.gas; using System.Collections.Generic; using log4net; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance; using System.IO; using log4net.Config; using it.unifi.dsi.stlab.networkreasoner.gas.system.formulae; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.listeners; using it.unifi.dsi.stlab.utilities.object_with_substitution; using it.unifi.dsi.stlab.networkreasoner.gas.system.exactly_dimensioned_instance.unknowns_initializations; using it.unifi.dsi.stlab.math.algebra; using it.unifi.dsi.stlab.networkreasoner.gas.system.state_visitors.summary_table; namespace it.unifi.dsi.stlab.networkreasoner.gas.system.tests { [TestFixture()] public class NetwonRaphsonSystemFiveNodesWithNegativePressures { [Test()] public void simple_network_with_potential_negative_pressure_for_nodes_with_load_gadgets () { TextualGheoNetInputParser parser = new TextualGheoNetInputParser ( new FileInfo ("gheonet-textual-networks/five-nodes-network.dat")); SystemRunnerFromTextualGheoNetInput systemRunner = parser.parse (new SpecificationAssemblerAllInOneFile () ); RunnableSystem runnableSystem = new RunnableSystemCompute { LogConfigFileInfo = new FileInfo ( "log4net-configurations/for-five-nodes-network-with-negative-pressures.xml"), Precision = 1e-8, UnknownInitialization = new UnknownInitializationSimplyRandomized () }; runnableSystem = new RunnableSystemWithDecorationComputeCompletedHandler{ DecoredRunnableSystem = runnableSystem, OnComputeCompletedHandler = assertsForSpecificationAllInOneFile }; systemRunner.run (runnableSystem); } #region assertions for the single system relative to all-in-one file specification // this method contains assertions for the test above. void assertsForSpecificationAllInOneFile ( string systemName, FluidDynamicSystemStateAbstract aSystemState) { Assert.That (aSystemState, Is.InstanceOf (typeof(FluidDynamicSystemStateNegativeLoadsCorrected))); OneStepMutationResults results = (aSystemState as FluidDynamicSystemStateNegativeLoadsCorrected). FluidDynamicSystemStateMathematicallySolved.MutationResult; Vector<NodeForNetwonRaphsonSystem> relativeUnknowns = results.makeUnknownsDimensional ().WrappedObject; var node1 = results.StartingUnsolvedState.findNodeByIdentifier ("N1"); var node2 = results.StartingUnsolvedState.findNodeByIdentifier ("N2"); var node3 = results.StartingUnsolvedState.findNodeByIdentifier ("N3"); var node4 = results.StartingUnsolvedState.findNodeByIdentifier ("N4"); Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (30.000).Within (1e-3)); Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (27.792).Within (1e-3)); Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (25.527).Within (1e-3)); Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (27.016).Within (1e-3)); var edgeR1 = results.StartingUnsolvedState.findEdgeByIdentifier ("R1"); var edgeR2 = results.StartingUnsolvedState.findEdgeByIdentifier ("R2"); var edgeR3 = results.StartingUnsolvedState.findEdgeByIdentifier ("R3"); Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (200.000).Within (1e-3)); Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (-100.000).Within (1e-3)); Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (-100.000).Within (1e-3)); } #endregion /// <summary> /// Simple_network_with_potential_negative_pressure_for_nodes_with_load_gadgets_with_splitted_specification this instance. /// The following test is used with a big input instance in the splitted file. It is used only for testing a ``real word'' /// splitted configuration, but we do not do any assert, hence this test always succeeds. /// </summary> [Test()] public void simple_network_with_potential_negative_pressure_for_nodes_with_load_gadgets_with_splitted_specification () { TextualGheoNetInputParser parser = new TextualGheoNetInputParser ( new FileInfo ("gheonet-textual-networks/five-nodes-network.dat")); SystemRunnerFromTextualGheoNetInput systemRunner = parser.parse (new SpecificationAssemblerSplitted ( new FileInfo ("gheonet-textual-networks/five-nodes-network-extension.dat")) ); RunnableSystem runnableSystem = new RunnableSystemCompute { LogConfigFileInfo = new FileInfo ( "log4net-configurations/for-five-nodes-network-with-negative-pressures.xml"), Precision = 1e-8, UnknownInitialization = new UnknownInitializationSimplyRandomized () }; runnableSystem = new RunnableSystemWithDecorationComputeCompletedHandler{ DecoredRunnableSystem = runnableSystem, OnComputeCompletedHandler = noAssertionsForGivenSystem }; var summaryTableVisitor = new FluidDynamicSystemStateVisitorBuildSummaryTable (); runnableSystem = new RunnableSystemWithDecorationApplySystemStateVisitor{ DecoredRunnableSystem = runnableSystem, SystemStateVisitor = summaryTableVisitor }; systemRunner.run (runnableSystem); File.WriteAllText ("gheonet-textual-networks/five-nodes-network-output.dat", summaryTableVisitor.buildSummaryContent ()); } void noAssertionsForGivenSystem (string systemName, FluidDynamicSystemStateAbstract aSystemState) { // simply do no assertion at all for the given system and its results. } [Test()] public void simple_network_with_potential_negative_pressure_for_nodes_with_load_gadgets_with_splitted_specification_small_instace () { TextualGheoNetInputParser parser = new TextualGheoNetInputParser ( new FileInfo ("gheonet-textual-networks/five-nodes-network.dat")); SystemRunnerFromTextualGheoNetInput systemRunner = parser.parse (new SpecificationAssemblerSplitted ( new FileInfo ("gheonet-textual-networks/five-nodes-network-extension-small.dat")) ); RunnableSystem runnableSystem = new RunnableSystemCompute { LogConfigFileInfo = new FileInfo ( "log4net-configurations/for-five-nodes-network-with-negative-pressures.xml"), Precision = 1e-8, UnknownInitialization = new UnknownInitializationSimplyRandomized () }; runnableSystem = new RunnableSystemWithDecorationComputeCompletedHandler{ DecoredRunnableSystem = runnableSystem, OnComputeCompletedHandler = assertsForSpecificationInSplittedFiles }; var summaryTableVisitor = new FluidDynamicSystemStateVisitorBuildSummaryTable (); runnableSystem = new RunnableSystemWithDecorationApplySystemStateVisitor{ DecoredRunnableSystem = runnableSystem, SystemStateVisitor = summaryTableVisitor }; systemRunner.run (runnableSystem); File.WriteAllText ("gheonet-textual-networks/five-nodes-network-output-small.dat", summaryTableVisitor.buildSummaryContent ()); } #region assertions for the five systems relative to splitted configuration // this method contains assertions for the test above. We need to provide // tests for 5 systems, hence we procede by cases, creating the // submethods below. void assertsForSpecificationInSplittedFiles ( string systemName, FluidDynamicSystemStateAbstract aSystemState) { Assert.That (aSystemState, Is.InstanceOf (typeof(FluidDynamicSystemStateNegativeLoadsCorrected))); OneStepMutationResults results = (aSystemState as FluidDynamicSystemStateNegativeLoadsCorrected). FluidDynamicSystemStateMathematicallySolved.MutationResult; Dictionary<String, Action<OneStepMutationResults>> assertionsBySystems = new Dictionary<string, Action<OneStepMutationResults>> (); // assertionsBySystems.Add ("0", assertionForSystem0); // assertionsBySystems.Add ("1", assertionForSystem1); // assertionsBySystems.Add ("2", assertionForSystem2); // assertionsBySystems.Add ("3", assertionForSystem3); // assertionsBySystems.Add ("4", assertionForSystem4); //assertionsBySystems [systemName].Invoke (results); } // void assertionForSystem0 (OneStepMutationResults results) // { // var relativeUnknownsWrapper = results.StartingUnsolvedState. // makeUnknownsDimensional (results.Unknowns); // // var relativeUnknowns = relativeUnknownsWrapper.WrappedObject; // // var node1 = results.findNodeByIdentifier ("N1"); // var node2 = results.findNodeByIdentifier ("N2"); // var node3 = results.findNodeByIdentifier ("N3"); // var node4 = results.findNodeByIdentifier ("N4"); // Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (32.34).Within (1e-5)); // // // var edgeR1 = results.findEdgeByIdentifier ("R1"); // var edgeR2 = results.findEdgeByIdentifier ("R2"); // var edgeR3 = results.findEdgeByIdentifier ("R3"); // Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (32.34).Within (1e-5)); // } // // void assertionForSystem1 (OneStepMutationResults results) // { // var relativeUnknownsWrapper = results.StartingUnsolvedState. // makeUnknownsDimensional (results.Unknowns); // // var relativeUnknowns = relativeUnknownsWrapper.WrappedObject; // // var node1 = results.findNodeByIdentifier ("N1"); // var node2 = results.findNodeByIdentifier ("N2"); // var node3 = results.findNodeByIdentifier ("N3"); // var node4 = results.findNodeByIdentifier ("N4"); // Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (32.34).Within (1e-5)); // // // var edgeR1 = results.findEdgeByIdentifier ("R1"); // var edgeR2 = results.findEdgeByIdentifier ("R2"); // var edgeR3 = results.findEdgeByIdentifier ("R3"); // Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (32.34).Within (1e-5)); // } // // void assertionForSystem2 (OneStepMutationResults results) // { // // var relativeUnknownsWrapper = results.StartingUnsolvedState. // makeUnknownsDimensional (results.Unknowns); // // var relativeUnknowns = relativeUnknownsWrapper.WrappedObject; // // var node1 = results.findNodeByIdentifier ("N1"); // var node2 = results.findNodeByIdentifier ("N2"); // var node3 = results.findNodeByIdentifier ("N3"); // var node4 = results.findNodeByIdentifier ("N4"); // Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (32.34).Within (1e-5)); // // // var edgeR1 = results.findEdgeByIdentifier ("R1"); // var edgeR2 = results.findEdgeByIdentifier ("R2"); // var edgeR3 = results.findEdgeByIdentifier ("R3"); // Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (32.34).Within (1e-5)); // } // // void assertionForSystem3 (OneStepMutationResults results) // { // // var relativeUnknownsWrapper = results.StartingUnsolvedState. // makeUnknownsDimensional (results.Unknowns); // // var relativeUnknowns = relativeUnknownsWrapper.WrappedObject; // // var node1 = results.findNodeByIdentifier ("N1"); // var node2 = results.findNodeByIdentifier ("N2"); // var node3 = results.findNodeByIdentifier ("N3"); // var node4 = results.findNodeByIdentifier ("N4"); // Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (32.34).Within (1e-5)); // // // var edgeR1 = results.findEdgeByIdentifier ("R1"); // var edgeR2 = results.findEdgeByIdentifier ("R2"); // var edgeR3 = results.findEdgeByIdentifier ("R3"); // Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (32.34).Within (1e-5)); // } // // void assertionForSystem4 (OneStepMutationResults results) // { // // var relativeUnknownsWrapper = results.StartingUnsolvedState. // makeUnknownsDimensional (results.Unknowns); // // var relativeUnknowns = relativeUnknownsWrapper.WrappedObject; // // var node1 = results.findNodeByIdentifier ("N1"); // var node2 = results.findNodeByIdentifier ("N2"); // var node3 = results.findNodeByIdentifier ("N3"); // var node4 = results.findNodeByIdentifier ("N4"); // Assert.That (relativeUnknowns.valueAt (node1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node3), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (relativeUnknowns.valueAt (node4), Is.EqualTo (32.34).Within (1e-5)); // // // var edgeR1 = results.findEdgeByIdentifier ("R1"); // var edgeR2 = results.findEdgeByIdentifier ("R2"); // var edgeR3 = results.findEdgeByIdentifier ("R3"); // Assert.That (results.Qvector.valueAt (edgeR1), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR2), Is.EqualTo (32.34).Within (1e-5)); // Assert.That (results.Qvector.valueAt (edgeR3), Is.EqualTo (32.34).Within (1e-5)); // } // #endregion } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class RelativeLayout : android.view.ViewGroup { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RelativeLayout() { InitJNI(); } protected RelativeLayout(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.view.ViewGroup.MarginLayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static LayoutParams() { InitJNI(); } protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _debug11752; public virtual global::java.lang.String debug(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams._debug11752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._debug11752, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _addRule11753; public virtual void addRule(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams._addRule11753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._addRule11753, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addRule11754; public virtual void addRule(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams._addRule11754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._addRule11754, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getRules11755; public virtual int[] getRules() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams._getRules11755)) as int[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._getRules11755)) as int[]; } internal static global::MonoJavaBridge.MethodId _LayoutParams11756; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._LayoutParams11756, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11757; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._LayoutParams11757, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11758; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._LayoutParams11758, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11759; public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.LayoutParams.staticClass, global::android.widget.RelativeLayout.LayoutParams._LayoutParams11759, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _alignWithParent11760; public bool alignWithParent { get { return default(bool); } set { } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RelativeLayout.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RelativeLayout$LayoutParams")); global::android.widget.RelativeLayout.LayoutParams._debug11752 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "debug", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.widget.RelativeLayout.LayoutParams._addRule11753 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "addRule", "(I)V"); global::android.widget.RelativeLayout.LayoutParams._addRule11754 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "addRule", "(II)V"); global::android.widget.RelativeLayout.LayoutParams._getRules11755 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "getRules", "()[I"); global::android.widget.RelativeLayout.LayoutParams._LayoutParams11756 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.RelativeLayout.LayoutParams._LayoutParams11757 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "<init>", "(II)V"); global::android.widget.RelativeLayout.LayoutParams._LayoutParams11758 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.RelativeLayout.LayoutParams._LayoutParams11759 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V"); } } internal static global::MonoJavaBridge.MethodId _dispatchPopulateAccessibilityEvent11761; public override bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.RelativeLayout._dispatchPopulateAccessibilityEvent11761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._dispatchPopulateAccessibilityEvent11761, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setGravity11762; public virtual void setGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._setGravity11762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._setGravity11762, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onLayout11763; protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._onLayout11763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._onLayout11763, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } internal static global::MonoJavaBridge.MethodId _getBaseline11764; public override int getBaseline() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.RelativeLayout._getBaseline11764); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._getBaseline11764); } internal static global::MonoJavaBridge.MethodId _requestLayout11765; public override void requestLayout() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._requestLayout11765); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._requestLayout11765); } internal static global::MonoJavaBridge.MethodId _onMeasure11766; protected override void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._onMeasure11766, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._onMeasure11766, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _checkLayoutParams11767; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.RelativeLayout._checkLayoutParams11767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._checkLayoutParams11767, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11768; public virtual new global::android.widget.RelativeLayout.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout._generateLayoutParams11768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.RelativeLayout.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._generateLayoutParams11768, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.RelativeLayout.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11769; protected override global::android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout._generateLayoutParams11769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._generateLayoutParams11769, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.ViewGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateDefaultLayoutParams11770; protected override global::android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout._generateDefaultLayoutParams11770)) as android.view.ViewGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._generateDefaultLayoutParams11770)) as android.view.ViewGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _setHorizontalGravity11771; public virtual void setHorizontalGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._setHorizontalGravity11771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._setHorizontalGravity11771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setVerticalGravity11772; public virtual void setVerticalGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._setVerticalGravity11772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._setVerticalGravity11772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setIgnoreGravity11773; public virtual void setIgnoreGravity(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout._setIgnoreGravity11773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._setIgnoreGravity11773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _RelativeLayout11774; public RelativeLayout(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._RelativeLayout11774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _RelativeLayout11775; public RelativeLayout(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._RelativeLayout11775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _RelativeLayout11776; public RelativeLayout(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RelativeLayout.staticClass, global::android.widget.RelativeLayout._RelativeLayout11776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } public static int TRUE { get { return -1; } } public static int LEFT_OF { get { return 0; } } public static int RIGHT_OF { get { return 1; } } public static int ABOVE { get { return 2; } } public static int BELOW { get { return 3; } } public static int ALIGN_BASELINE { get { return 4; } } public static int ALIGN_LEFT { get { return 5; } } public static int ALIGN_TOP { get { return 6; } } public static int ALIGN_RIGHT { get { return 7; } } public static int ALIGN_BOTTOM { get { return 8; } } public static int ALIGN_PARENT_LEFT { get { return 9; } } public static int ALIGN_PARENT_TOP { get { return 10; } } public static int ALIGN_PARENT_RIGHT { get { return 11; } } public static int ALIGN_PARENT_BOTTOM { get { return 12; } } public static int CENTER_IN_PARENT { get { return 13; } } public static int CENTER_HORIZONTAL { get { return 14; } } public static int CENTER_VERTICAL { get { return 15; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RelativeLayout.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RelativeLayout")); global::android.widget.RelativeLayout._dispatchPopulateAccessibilityEvent11761 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z"); global::android.widget.RelativeLayout._setGravity11762 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "setGravity", "(I)V"); global::android.widget.RelativeLayout._onLayout11763 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "onLayout", "(ZIIII)V"); global::android.widget.RelativeLayout._getBaseline11764 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "getBaseline", "()I"); global::android.widget.RelativeLayout._requestLayout11765 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "requestLayout", "()V"); global::android.widget.RelativeLayout._onMeasure11766 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "onMeasure", "(II)V"); global::android.widget.RelativeLayout._checkLayoutParams11767 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z"); global::android.widget.RelativeLayout._generateLayoutParams11768 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/RelativeLayout$LayoutParams;"); global::android.widget.RelativeLayout._generateLayoutParams11769 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "generateLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Landroid/view/ViewGroup$LayoutParams;"); global::android.widget.RelativeLayout._generateDefaultLayoutParams11770 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "generateDefaultLayoutParams", "()Landroid/view/ViewGroup$LayoutParams;"); global::android.widget.RelativeLayout._setHorizontalGravity11771 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "setHorizontalGravity", "(I)V"); global::android.widget.RelativeLayout._setVerticalGravity11772 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "setVerticalGravity", "(I)V"); global::android.widget.RelativeLayout._setIgnoreGravity11773 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "setIgnoreGravity", "(I)V"); global::android.widget.RelativeLayout._RelativeLayout11774 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "<init>", "(Landroid/content/Context;)V"); global::android.widget.RelativeLayout._RelativeLayout11775 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.RelativeLayout._RelativeLayout11776 = @__env.GetMethodIDNoThrow(global::android.widget.RelativeLayout.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); } } }
// <copyright file="StreamCompiler.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using BeanIO.Config; using BeanIO.Internal.Config; using BeanIO.Internal.Config.Xml; using BeanIO.Internal.Util; using BeanIO.Types; using JetBrains.Annotations; namespace BeanIO.Internal.Compiler { /// <summary> /// Compiles a mapping file read from an <see cref="System.IO.Stream"/> into a collection of /// <see cref="Parser.Stream"/> parsers. /// </summary> internal class StreamCompiler { /// <summary> /// Initializes a new instance of the <see cref="StreamCompiler"/> class. /// </summary> public StreamCompiler() { DefaultConfigurationLoader = new XmlConfigurationLoader(); } /// <summary> /// Gets the default mapping configuration loader /// </summary> public IConfigurationLoader DefaultConfigurationLoader { get; } /// <summary> /// Gets or sets the mapping configuration loader /// </summary> public IConfigurationLoader ConfigurationLoader { get; set; } /// <summary> /// Creates a new Stream from its configuration /// </summary> /// <param name="config">the <see cref="StreamConfig"/></param> /// <returns>the built <see cref="Parser.Stream"/> definition</returns> public Parser.Stream Build(StreamConfig config) { var typeHandlerFactory = CreateTypeHandlerFactory(TypeHandlerFactory.Default, config.Handlers); var factory = CreateParserFactory(config.Format); factory.TypeHandlerFactory = typeHandlerFactory; return factory.CreateStream(config); } /// <summary> /// Loads a mapping file /// </summary> /// <param name="input">the <see cref="System.IO.Stream"/> to load the mapping file from</param> /// <param name="properties">the <see cref="Properties"/></param> /// <returns>the <see cref="Parser.Stream"/> parsers configured in the loaded mapping file</returns> public IReadOnlyCollection<Parser.Stream> LoadMapping(System.IO.Stream input, Properties properties) { var loader = ConfigurationLoader ?? DefaultConfigurationLoader; var configurations = loader.LoadConfiguration(input, properties); if (configurations.Count == 0) return ObjectUtils.Empty<Parser.Stream>(); // check for duplicate stream names... { var set = new HashSet<string>(); foreach (var streamConfig in configurations.SelectMany(x => x.StreamConfigurations)) { if (!set.Add(streamConfig.Name)) throw new BeanIOConfigurationException($"Duplicate stream name '{streamConfig.Name}'"); } } if (configurations.Count == 1) return CreateStreamDefinitions(configurations.Single()).ToList(); var list = configurations.SelectMany(CreateStreamDefinitions).ToList(); return list; } /// <summary> /// Creates stream definitions from a BeanIO stream mapping configuration /// </summary> /// <param name="config">the BeanIO stream mapping configuration</param> /// <returns>the collection of stream definitions</returns> protected IEnumerable<Parser.Stream> CreateStreamDefinitions([NotNull] BeanIOConfig config) { if (config == null) throw new ArgumentNullException(nameof(config)); Contract.EndContractBlock(); var parent = CreateTypeHandlerFactory(TypeHandlerFactory.Default, config.TypeHandlerConfigurations); var streamDefinitions = new List<Parser.Stream>(config.StreamConfigurations.Count); foreach (var streamConfiguration in config.StreamConfigurations) { var typeHandlerFactory = CreateTypeHandlerFactory(parent, streamConfiguration.Handlers); var factory = CreateParserFactory(streamConfiguration.Format); factory.TypeHandlerFactory = typeHandlerFactory; try { streamDefinitions.Add(factory.CreateStream(streamConfiguration)); } catch (BeanIOConfigurationException ex) when (config.Source != null) { throw new BeanIOConfigurationException($"Invalid mapping file '{config.Source}': {ex.Message}", ex); } } return streamDefinitions; } /// <summary> /// Instantiates the factory implementation to create the stream definition /// </summary> /// <param name="format">the stream format</param> /// <returns>the stream definition factory</returns> protected IParserFactory CreateParserFactory(string format) { var propertyName = $"org.beanio.{format}.streamDefinitionFactory"; var typeName = Settings.Instance[propertyName]; if (typeName == null) throw new BeanIOConfigurationException($"A stream definition factory is not configured for format '{format}'"); var factory = BeanUtil.CreateBean(typeName) as IParserFactory; if (factory == null) { throw new BeanIOConfigurationException( $"Configured stream definition factory '{typeName}' does not implement '{typeof(IParserFactory)}'"); } return factory; } /// <summary> /// Creates a type handler factory for a list of configured type handlers /// </summary> /// <param name="parent">the parent <see cref="TypeHandlerFactory"/></param> /// <param name="typeHandlerConfigurations">the list of type handler configurations</param> /// <returns>the new <see cref="TypeHandlerFactory"/>, or <code>parent</code> if the configuration list was empty</returns> private TypeHandlerFactory CreateTypeHandlerFactory(TypeHandlerFactory parent, IReadOnlyCollection<TypeHandlerConfig> typeHandlerConfigurations) { if (typeHandlerConfigurations == null || typeHandlerConfigurations.Count == 0) return parent; var factory = new TypeHandlerFactory(parent); foreach (var handlerConfig in typeHandlerConfigurations) { if (handlerConfig.Name == null && handlerConfig.Type == null) throw new BeanIOConfigurationException("Type handler must specify either 'type' or 'name'"); var createFunc = handlerConfig.Create; if (createFunc == null) { object bean; try { bean = BeanUtil.CreateBean(handlerConfig.ClassName, handlerConfig.Properties); } catch (BeanIOConfigurationException ex) { if (handlerConfig.Name != null) throw new BeanIOConfigurationException($"Failed to create type handler named '{handlerConfig.Name}'", ex); throw new BeanIOConfigurationException($"Failed to create type handler for type '{handlerConfig.Type}'", ex); } // validate the configured class is assignable to the target class if (!(bean is ITypeHandler)) { throw new BeanIOConfigurationException( $"Type handler class '{handlerConfig.ClassName}' does not implement TypeHandler interface"); } var funcHandlerConfig = handlerConfig; createFunc = () => (ITypeHandler)BeanUtil.CreateBean(funcHandlerConfig.ClassName, funcHandlerConfig.Properties); } if (handlerConfig.Name != null) factory.RegisterHandler(handlerConfig.Name, createFunc); if (handlerConfig.Type != null) { try { // type handlers configured for java types may be registered for a specific stream format factory.RegisterHandlerFor(handlerConfig.Type, createFunc, handlerConfig.Format); } catch (Exception ex) { throw new BeanIOConfigurationException("Invalid type handler configuration", ex); } } } return factory; } } }
// // Mono.Data.Tds.Protocol.TdsComm.cs // // Author: // Tim Coleman (tim@timcoleman.com) // // Copyright (C) 2002 Tim Coleman // // // 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.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace Mono.Data.Tds.Protocol { internal sealed class TdsComm { #region Fields NetworkStream stream; int packetSize; TdsPacketType packetType = TdsPacketType.None; Encoding encoder; string dataSource; int commandTimeout; int connectionTimeout; byte[] outBuffer; int outBufferLength; int nextOutBufferIndex = 0; byte[] inBuffer; int inBufferLength; int inBufferIndex = 0; static int headerLength = 8; byte[] tmpBuf = new byte[8]; byte[] resBuffer = new byte[256]; int packetsSent = 0; int packetsReceived = 0; Socket socket; TdsVersion tdsVersion; ManualResetEvent connected = new ManualResetEvent (false); #endregion // Fields #region Constructors [MonoTODO ("Fix when asynchronous socket connect works on Linux.")] public TdsComm (string dataSource, int port, int packetSize, int timeout, TdsVersion tdsVersion) { this.packetSize = packetSize; this.tdsVersion = tdsVersion; this.dataSource = dataSource; this.connectionTimeout = timeout; outBuffer = new byte[packetSize]; inBuffer = new byte[packetSize]; outBufferLength = packetSize; inBufferLength = packetSize; socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPHostEntry hostEntry = Dns.Resolve (dataSource); IPEndPoint endPoint; endPoint = new IPEndPoint (hostEntry.AddressList [0], port); // This replaces the code below for now socket.Connect (endPoint); /* FIXME: Asynchronous socket connection doesn't work right on linux, so comment this out for now. This *does* do the right thing on windows connected.Reset (); IAsyncResult asyncResult = socket.BeginConnect (endPoint, new AsyncCallback (ConnectCallback), socket); if (timeout > 0 && !connected.WaitOne (new TimeSpan (0, 0, timeout), true)) throw Tds.CreateTimeoutException (dataSource, "Open()"); else if (timeout > 0 && !connected.WaitOne ()) throw Tds.CreateTimeoutException (dataSource, "Open()"); */ stream = new NetworkStream (socket); } #endregion // Constructors #region Properties public int CommandTimeout { get { return commandTimeout; } set { commandTimeout = value; } } internal Encoding Encoder { set { encoder = value; } } public int PacketSize { get { return packetSize; } set { packetSize = value; } } #endregion // Properties #region Methods public byte[] Swap(byte[] toswap) { byte[] ret = new byte[toswap.Length]; for(int i = 0; i < toswap.Length; i++) ret [toswap.Length - i - 1] = toswap[i]; return ret; } public void Append (object o) { switch (o.GetType ().ToString ()) { case "System.Byte": Append ((byte) o); return; case "System.Byte[]": Append ((byte[]) o); return; case "System.Int16": Append ((short) o); return; case "System.Int32": Append ((int) o); return; case "System.String": Append ((string) o); return; case "System.Double": Append ((double) o); return; case "System.Int64": Append ((long) o); return; } } public void Append (byte b) { if (nextOutBufferIndex == outBufferLength) { SendPhysicalPacket (false); nextOutBufferIndex = headerLength; } Store (nextOutBufferIndex, b); nextOutBufferIndex++; } public void Append (byte[] b) { Append (b, b.Length, (byte) 0); } public void Append (byte[] b, int len, byte pad) { int i = 0; for ( ; i < b.Length && i < len; i++) Append (b[i]); for ( ; i < len; i++) Append (pad); } public void Append (short s) { if(!BitConverter.IsLittleEndian) Append (Swap (BitConverter.GetBytes(s))); else Append (BitConverter.GetBytes (s)); } public void Append (int i) { if(!BitConverter.IsLittleEndian) Append (Swap (BitConverter.GetBytes(i))); else Append (BitConverter.GetBytes (i)); } public void Append (string s) { if (tdsVersion < TdsVersion.tds70) Append (encoder.GetBytes (s)); else foreach (char c in s) if(!BitConverter.IsLittleEndian) Append (Swap (BitConverter.GetBytes (c))); else Append (BitConverter.GetBytes (c)); } // Appends with padding public byte[] Append (string s, int len, byte pad) { if (s == null) return new byte[0]; byte[] result = encoder.GetBytes (s); Append (result, len, pad); return result; } public void Append (double value) { Append (BitConverter.DoubleToInt64Bits (value)); } public void Append (long l) { if (tdsVersion < TdsVersion.tds70) { Append ((byte) (((byte) (l >> 56)) & 0xff)); Append ((byte) (((byte) (l >> 48)) & 0xff)); Append ((byte) (((byte) (l >> 40)) & 0xff)); Append ((byte) (((byte) (l >> 32)) & 0xff)); Append ((byte) (((byte) (l >> 24)) & 0xff)); Append ((byte) (((byte) (l >> 16)) & 0xff)); Append ((byte) (((byte) (l >> 8)) & 0xff)); Append ((byte) (((byte) (l >> 0)) & 0xff)); } else if (!BitConverter.IsLittleEndian) Append (Swap (BitConverter.GetBytes (l))); else Append (BitConverter.GetBytes (l)); } public void Close () { stream.Close (); } private void ConnectCallback (IAsyncResult ar) { Socket s = (Socket) ar.AsyncState; if (Poll (s, connectionTimeout, SelectMode.SelectWrite)) { socket.EndConnect (ar); connected.Set (); } } public byte GetByte () { byte result; if (inBufferIndex >= inBufferLength) { // out of data, read another physical packet. GetPhysicalPacket (); } result = inBuffer[inBufferIndex++]; return result; } public byte[] GetBytes (int len, bool exclusiveBuffer) { byte[] result = null; int i; // Do not keep an internal result buffer larger than 16k. // This would unnecessarily use up memory. if (exclusiveBuffer || len > 16384) result = new byte[len]; else { if (resBuffer.Length < len) resBuffer = new byte[len]; result = resBuffer; } for (i = 0; i<len; ) { if (inBufferIndex >= inBufferLength) GetPhysicalPacket (); int avail = inBufferLength - inBufferIndex; avail = avail>len-i ? len-i : avail; System.Array.Copy (inBuffer, inBufferIndex, result, i, avail); i += avail; inBufferIndex += avail; } return result; } public string GetString (int len) { if (tdsVersion == TdsVersion.tds70) return GetString (len, true); else return GetString (len, false); } public string GetString (int len, bool wide) { if (wide) { char[] chars = new char[len]; for (int i = 0; i < len; ++i) { int lo = ((byte) GetByte ()) & 0xFF; int hi = ((byte) GetByte ()) & 0xFF; chars[i] = (char) (lo | ( hi << 8)); } return new String (chars); } else { byte[] result = new byte[len]; Array.Copy (GetBytes (len, false), result, len); return (encoder.GetString (result)); } } public int GetNetShort () { byte[] tmp = new byte[2]; tmp[0] = GetByte (); tmp[1] = GetByte (); return Ntohs (tmp, 0); } public short GetTdsShort () { byte[] input = new byte[2]; for (int i = 0; i < 2; i += 1) input[i] = GetByte (); if(!BitConverter.IsLittleEndian) return (BitConverter.ToInt16 (Swap (input), 0)); else return (BitConverter.ToInt16 (input, 0)); } public int GetTdsInt () { byte[] input = new byte[4]; for (int i = 0; i < 4; i += 1) input[i] = GetByte (); if(!BitConverter.IsLittleEndian) return (BitConverter.ToInt32 (Swap (input), 0)); else return (BitConverter.ToInt32 (input, 0)); } public long GetTdsInt64 () { byte[] input = new byte[8]; for (int i = 0; i < 8; i += 1) input[i] = GetByte (); if(!BitConverter.IsLittleEndian) return (BitConverter.ToInt64 (Swap (input), 0)); else return (BitConverter.ToInt64 (input, 0)); } private void GetPhysicalPacket () { int dataLength = GetPhysicalPacketHeader (); GetPhysicalPacketData (dataLength); } private int GetPhysicalPacketHeader () { int nread = 0; // read the header while (nread < 8) nread += stream.Read (tmpBuf, nread, 8 - nread); TdsPacketType packetType = (TdsPacketType) tmpBuf[0]; if (packetType != TdsPacketType.Logon && packetType != TdsPacketType.Query && packetType != TdsPacketType.Reply) { throw new Exception (String.Format ("Unknown packet type {0}", tmpBuf[0])); } // figure out how many bytes are remaining in this packet. int len = Ntohs (tmpBuf, 2) - 8; if (len >= inBuffer.Length) inBuffer = new byte[len]; if (len < 0) { throw new Exception (String.Format ("Confused by a length of {0}", len)); } return len; } private void GetPhysicalPacketData (int length) { // now get the data int nread = 0; while (nread < length) { nread += stream.Read (inBuffer, nread, length - nread); } packetsReceived++; // adjust the bookkeeping info about the incoming buffer inBufferLength = length; inBufferIndex = 0; } private static int Ntohs (byte[] buf, int offset) { int lo = ((int) buf[offset + 1] & 0xff); int hi = (((int) buf[offset] & 0xff ) << 8); return hi | lo; // return an int since we really want an _unsigned_ } public byte Peek () { // If out of data, read another physical packet. if (inBufferIndex >= inBufferLength) GetPhysicalPacket (); return inBuffer[inBufferIndex]; } public bool Poll (int seconds, SelectMode selectMode) { return Poll (socket, seconds, selectMode); } private bool Poll (Socket s, int seconds, SelectMode selectMode) { long uSeconds = seconds * 1000000; bool bState = false; while (uSeconds > (long) Int32.MaxValue) { bState = s.Poll (Int32.MaxValue, selectMode); if (bState) return true; uSeconds -= Int32.MaxValue; } return s.Poll ((int) uSeconds, selectMode); } internal void ResizeOutBuf (int newSize) { if (newSize > outBufferLength) { byte[] newBuf = new byte [newSize]; Array.Copy (outBuffer, 0, newBuf, 0, outBufferLength); outBufferLength = newSize; outBuffer = newBuf; } } public void SendPacket () { SendPhysicalPacket (true); nextOutBufferIndex = 0; packetType = TdsPacketType.None; } private void SendPhysicalPacket (bool isLastSegment) { if (nextOutBufferIndex > headerLength || packetType == TdsPacketType.Cancel) { // packet type Store (0, (byte) packetType); Store (1, (byte) (isLastSegment ? 1 : 0)); Store (2, (short) nextOutBufferIndex ); Store (4, (byte) 0); Store (5, (byte) 0); Store (6, (byte) (tdsVersion == TdsVersion.tds70 ? 0x1 : 0x0)); Store (7, (byte) 0); stream.Write (outBuffer, 0, nextOutBufferIndex); stream.Flush (); packetsSent++; } } public void Skip (int i) { for ( ; i > 0; i--) GetByte (); } public void StartPacket (TdsPacketType type) { if (type != TdsPacketType.Cancel && inBufferIndex != inBufferLength) inBufferIndex = inBufferLength; packetType = type; nextOutBufferIndex = headerLength; } private void Store (int index, byte value) { outBuffer[index] = value; } private void Store (int index, short value) { outBuffer[index] = (byte) (((byte) (value >> 8)) & 0xff); outBuffer[index + 1] = (byte) (((byte) (value >> 0)) & 0xff); } #endregion // Methods #if NET_2_0 #region Async Methods public IAsyncResult BeginReadPacket (AsyncCallback callback, object stateObject) { TdsAsyncResult ar = new TdsAsyncResult (callback, stateObject); stream.BeginRead (tmpBuf, 0, 8, new AsyncCallback(OnReadPacketCallback), ar); return ar; } /// <returns>Packet size in bytes</returns> public int EndReadPacket (IAsyncResult ar) { if (!ar.IsCompleted) ar.AsyncWaitHandle.WaitOne (); return (int) ((TdsAsyncResult) ar).ReturnValue; } public void OnReadPacketCallback (IAsyncResult socketAsyncResult) { TdsAsyncResult ar = (TdsAsyncResult) socketAsyncResult.AsyncState; int nread = stream.EndRead (socketAsyncResult); while (nread < 8) nread += stream.Read (tmpBuf, nread, 8 - nread); TdsPacketType packetType = (TdsPacketType) tmpBuf[0]; if (packetType != TdsPacketType.Logon && packetType != TdsPacketType.Query && packetType != TdsPacketType.Reply) { throw new Exception (String.Format ("Unknown packet type {0}", tmpBuf[0])); } // figure out how many bytes are remaining in this packet. int len = Ntohs (tmpBuf, 2) - 8; if (len >= inBuffer.Length) inBuffer = new byte[len]; if (len < 0) { throw new Exception (String.Format ("Confused by a length of {0}", len)); } GetPhysicalPacketData (len); int value = len + 8; ar.ReturnValue = ((object)value); // packet size ar.MarkComplete (); } #endregion // Async Methods #endif // NET_2_0 } }
using System; using System.Drawing; using System.Drawing.Drawing2D; namespace DrawingEx.ColorManagement.ColorModels.Selection { public abstract class ColorSelectionModuleRGB:ColorSelectionModule { #region variables protected Color _color; #endregion #region properties public override XYZ XYZ { get { return XYZ.FromRGB(_color); } set { Color newcolor=value.ToRGB(); if(newcolor==_color) return; _color=newcolor; //update controls UpdatePlaneImage(); UpdatePlanePosition(); UpdateFaderImage(); UpdateFaderPosition(); } } #endregion } public class ColorSelectionModuleRGB_R:ColorSelectionModuleRGB { #region colorfader protected override void OnUpdateFaderImage(Bitmap bmp) { using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width), Color.FromArgb(0,_color.G,_color.B), Color.FromArgb(255,_color.G,_color.B))) { gr.FillRectangle(brs, new Rectangle(Point.Empty,bmp.Size)); } } } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=(double)(_color.R)/255.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { int newred=Math.Max(0,Math.Min(255,(int)(fader.Position*255.0))); if(newred==_color.R) return; _color=Color.FromArgb(newred,_color.G,_color.B); UpdatePlaneImage(); RaiseColorChanged(); } #endregion #region colorplane protected override void OnUpdatePlaneImage(Bitmap bmp) { double green=255.0, delta_green=-255.0/(double)bmp.Height; Color[] lincols=new Color[2]; using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width,0), Color.White,Color.White)) { for (int y=0; y<bmp.Height; y++, green+=delta_green) { int g=Math.Max(0,Math.Min(255,(int)green)); lincols[0]=Color.FromArgb(_color.R,g,0); lincols[1]=Color.FromArgb(_color.R,g,255); brs.LinearColors=lincols; gr.FillRectangle(brs,0,y,bmp.Width,1); } } } } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((double)(_color.B)/255.0, 1.0-(double)(_color.G)/255.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { int newgreen=Math.Max(0,Math.Min(255,(int)(255.0-plane.PositionY*255.0))), newblue=Math.Max(0,Math.Min(255,(int)(plane.PositionX*255.0))); if(_color.G==newgreen && _color.B==newblue) return; _color=Color.FromArgb(_color.R,newgreen,newblue); UpdateFaderImage(); RaiseColorChanged(); } #endregion } public class ColorSelectionModuleRGB_G:ColorSelectionModuleRGB { #region colorfader protected override void OnUpdateFaderImage(Bitmap bmp) { using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width), Color.FromArgb(_color.R,0,_color.B), Color.FromArgb(_color.R,255,_color.B))) { gr.FillRectangle(brs, new Rectangle(Point.Empty,bmp.Size)); } } } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=(double)(_color.G)/255.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { int newgreen=Math.Max(0,Math.Min(255,(int)(fader.Position*255.0))); if(newgreen==_color.G) return; _color=Color.FromArgb(_color.R,newgreen,_color.B); UpdatePlaneImage(); RaiseColorChanged(); } #endregion #region colorplane protected override void OnUpdatePlaneImage(Bitmap bmp) { double red=255.0, delta_red=-255.0/(double)bmp.Height; Color[] lincols=new Color[2]; using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width,0), Color.White,Color.White)) { for (int y=0; y<bmp.Height; y++, red+=delta_red) { int r=Math.Max(0,Math.Min(255,(int)red)); lincols[0]=Color.FromArgb(r,_color.G,0); lincols[1]=Color.FromArgb(r,_color.G,255); brs.LinearColors=lincols; gr.FillRectangle(brs,0,y,bmp.Width,1); } } } } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((double)(_color.B)/255.0, 1.0-(double)(_color.R)/255.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { int newred=Math.Max(0,Math.Min(255,(int)(255.0-plane.PositionY*255.0))), newblue=Math.Max(0,Math.Min(255,(int)(plane.PositionX*255.0))); if(_color.R==newred && _color.B==newblue) return; _color=Color.FromArgb(newred,_color.G,newblue); UpdateFaderImage(); RaiseColorChanged(); } #endregion } public class ColorSelectionModuleRGB_B:ColorSelectionModuleRGB { #region colorfader protected override void OnUpdateFaderImage(Bitmap bmp) { using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width), Color.FromArgb(_color.R,_color.G,0), Color.FromArgb(_color.R,_color.G,255))) { gr.FillRectangle(brs, new Rectangle(Point.Empty,bmp.Size)); } } } protected override void OnUpdateFaderPosition(ColorSelectionFader fader) { fader.Position=(double)(_color.B)/255.0; } protected override void OnFaderScroll(ColorSelectionFader fader) { int newblue=Math.Max(0,Math.Min(255,(int)(fader.Position*255.0))); if(newblue==_color.B) return; _color=Color.FromArgb(_color.R,_color.G,newblue); UpdatePlaneImage(); RaiseColorChanged(); } #endregion #region colorplane protected override void OnUpdatePlaneImage(Bitmap bmp) { double green=255.0, delta_green=-255.0/(double)bmp.Height; Color[] lincols=new Color[2]; using(Graphics gr=Graphics.FromImage(bmp)) { using(LinearGradientBrush brs=new LinearGradientBrush( new Point(0,0),new Point(bmp.Width,0), Color.White,Color.White)) { for (int y=0; y<bmp.Height; y++, green+=delta_green) { int g=Math.Max(0,Math.Min(255,(int)green)); lincols[0]=Color.FromArgb(0,g,_color.B); lincols[1]=Color.FromArgb(255,g,_color.B); brs.LinearColors=lincols; gr.FillRectangle(brs,0,y,bmp.Width,1); } } } } protected override void OnUpdatePlanePosition(ColorSelectionPlane plane) { plane.SetPosition((double)(_color.R)/255.0, 1.0-(double)(_color.G)/255.0); } protected override void OnPlaneScroll(ColorSelectionPlane plane) { int newgreen=Math.Max(0,Math.Min(255,(int)(255.0-plane.PositionY*255.0))), newred=Math.Max(0,Math.Min(255,(int)(plane.PositionX*255.0))); if(_color.R==newred && _color.G==newgreen) return; _color=Color.FromArgb(newred,newgreen,_color.B); UpdateFaderImage(); RaiseColorChanged(); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService { /// <summary> /// FileServiceClientTransport is the base class for file access family transport /// </summary> public abstract class FileServiceClientTransport : IDisposable { #region fields /// <summary> /// Indicate if this object has been disposed /// </summary> private bool disposed; #endregion #region Property /// <summary> /// To detect whether there are packets cached in the queue of Transport. /// Usually, it should be called after Disconnect to assure all events occurred in transport /// have been handled. /// </summary> /// <exception cref="System.InvalidOperationException">The transport is not connected.</exception> public abstract bool IsDataAvailable { get; } /// <summary> /// the context of client transport, that contains the runtime states and variables.<para/> /// this interface provides no method, user need to down-casting to the specified class.<para/> /// for example, down-casting to CifsClientContext, SmbClientContext or Smb2ClientGlobalContext. /// </summary> public abstract FileServiceClientContext Context { get; } #endregion #region Dispose /// <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> protected virtual 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: } // Call the appropriate methods to clean up unmanaged resources. this.disposed = true; } } /// <summary> /// finalizer /// </summary> ~FileServiceClientTransport() { Dispose(false); } #endregion #region Methods For Dfsc /// <summary> /// Set up connection with server. /// Including 4 steps: 1. Tcp connection 2. Negotiation 3. SessionSetup 4. TreeConnect in order /// </summary> /// <param name="server">server name of ip address</param> /// <param name="client">client name of 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="timeout">The pending time to get server's response in step 2, 3 or 4</param> /// <exception cref="System.Net.ProtocolViolationException">Fail to set up connection with server</exception> public abstract void Connect( string server, string client, string domain, string userName, string password, TimeSpan timeout, SecurityPackageType securityPackage, bool useServerToken); /// <summary> /// Disconnect from server. /// Including 3 steps: 1. TreeDisconnect 2. Logoff 3. Tcp disconnection in order. /// </summary> /// <param name="timeout">The pending time to get server's response in step 1 or 2</param> /// <exception cref="System.Net.ProtocolViolationException">Fail to disconnect from server</exception> /// <exception cref="System.InvalidOperationException">The transport is not connected</exception> public abstract void Disconnect(TimeSpan timeout); /// <summary> /// Send a Dfs request to server /// </summary> /// <param name="payload">REQ_GET_DFS_REFERRAL or REQ_GET_DFS_REFERRAL_EX structure in byte array</param> /// <param name="isEX">Indicates if payload contains REQ_GET_DFS_REFERRAL_EX structure</param> /// <exception cref="System.ArgumentNullException">the payload to be sent is null.</exception> /// <exception cref="ArgumentException">Transport does not support REQ_GET_DFS_REFERRAL_EX packets</exception> /// <exception cref="System.InvalidOperationException">The transport is not connected</exception> public abstract void SendDfscPayload(byte[] payload, bool isEX); /// <summary> /// Wait for the Dfs response packet from server. /// Including 3 steps: 1. TreeDisconnect 2. Logoff 3. Tcp disconnection in order. /// </summary> /// <param name="status">The status of response</param> /// <param name="payload">RESP_GET_DFS_REFERRAL structure in byte array</param> /// <param name="timeout">The pending time to get server's response</param> /// <exception cref="System.InvalidOperationException">The transport is not connected</exception> public abstract void ExpectDfscPayload(TimeSpan timeout, out uint status, out byte[] payload); #endregion #region Methods For Rpce /// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName); /// <summary> /// Connect to a share indicated by shareName in server /// This will use smb over tcp as transport. Only one server /// can be connected at one time /// </summary> /// <param name="serverName">The server Name</param> /// <param name="port">The server port</param> /// <param name="ipVersion">The ip version</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <param name="securityPackage">The security package</param> /// <param name="useServerToken">Whether to use token from server</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void ConnectShare(string serverName, int port, IpVersion ipVersion, string domain, string userName, string password, string shareName, SecurityPackageType securityPackage, bool useServerToken); /// <summary> /// Connect to a share indicated by shareName in server. /// This will use smb over netbios as transport. Only one server /// can be connected at one time. /// </summary> /// <param name="serverNetBiosName">The server netbios name</param> /// <param name="clientNetBiosName">The client netbios name</param> /// <param name="domain">The domain name</param> /// <param name="userName">The user name</param> /// <param name="password">The password</param> /// <param name="shareName">The share name</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void ConnectShare(string serverNetBiosName, string clientNetBiosName, string domain, string userName, string password, string shareName); /// <summary> /// Create File, named pipe, directory. One transport can only create one file. /// </summary> /// <param name="fileName">The file, namedpipe, directory name</param> /// <param name="desiredAccess">The desired access</param> /// <param name="impersonationLevel">The impersonation level</param> /// <param name="fileAttribute">The file attribute, this field is only valid when create file. /// </param> /// <param name="createDisposition">Defines the action the server MUST take if the file that is /// specified in the name field already exists</param> /// <param name="createOption">Specifies the options to be applied when creating or opening the file</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void Create(string fileName, FsFileDesiredAccess desiredAccess, FsImpersonationLevel impersonationLevel, FsFileAttribute fileAttribute, FsCreateDisposition createDisposition, FsCreateOption createOption); /// <summary> /// Create directory. One transport can only create one directory /// </summary> /// <param name="directoryName">The directory name</param> /// <param name="desiredAccess">The desired access</param> /// <param name="impersonationLevel">The impersonation level</param> /// <param name="fileAttribute">The file attribute, this field is only valid when create file. /// </param> /// <param name="createDisposition">Defines the action the server MUST take if the file that is /// specified in the name field already exists</param> /// <param name="createOption">Specifies the options to be applied when creating or opening the file</param> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void Create(string directoryName, FsDirectoryDesiredAccess desiredAccess, FsImpersonationLevel impersonationLevel, FsFileAttribute fileAttribute, FsCreateDisposition createDisposition, FsCreateOption createOption); /// <summary> /// Write data to server. cifs/smb implementation of this interface should pay attention to offset. /// They may not accept ulong as offset /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="offset">The offset of the file from where client wants to start writing</param> /// <param name="data">The data which will be written to server</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint Write(TimeSpan timeout, ulong offset, byte[] data); /// <summary> /// Read data from server, start at the positon indicated by offset /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="offset">From where it will read</param> /// <param name="length">The length of the data client wants to read</param> /// <param name="data">The read data</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint Read(TimeSpan timeout, ulong offset, uint length, out byte[] data); /// <summary> /// Do IO control on server, this function does not accept file system control code as control code. /// for that use, use FileSystemControl() function instead /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="controlCode">The IO control code</param> /// <param name="input">The input data of this control operation</param> /// <param name="output">The output data of this control operation</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint IoControl(TimeSpan timeout, uint controlCode, byte[] input, out byte[] output); /// <summary> /// Do IO control on server, this function does not accept file system control code as control code. /// for that use, use FileSystemControl() function instead /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="controlCode">The IO control code</param> /// <param name="input">The input data of this control operation</param> /// <param name="inputResponse">The input data in the response of this control operation</param> /// <param name="outputResponse">The output data in the response of this control operation</param> /// <param name="maxInputResponse">The maximum number of bytes that the server can return for the input data</param> /// <param name="maxOutputResponse">The maximum number of bytes that the server can return for the output data</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint IoControl(TimeSpan timeout, uint controlCode, byte[] input, out byte[] inputResponse, out byte[] outputResponse, uint maxInputResponse, uint maxOutputResponse); /// <summary> /// Do File system control on server /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="controlCode">The file system control code</param> /// <param name="input">The input data of this control operation</param> /// <param name="output">The output data of this control operation</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint IoControl(TimeSpan timeout, FsCtlCode controlCode, byte[] input, out byte[] output); /// <summary> /// Do File system control on server /// </summary> /// <param name="timeout">The pending time to get server's response</param> /// <param name="controlCode">The file system control code</param> /// <param name="input">The input data of this control operation</param> /// <param name="inputResponse">The input data in the response of this control operation</param> /// <param name="outputResponse">The output data in the response of this control operation</param> /// <param name="maxInputResponse">The maximum number of bytes that the server can return for the input data</param> /// <param name="maxOutputResponse">The maximum number of bytes that the server can return for the output data</param> /// <returns> /// a uint value that specifies the status of response packet. /// </returns> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract uint IoControl(TimeSpan timeout, FsCtlCode controlCode, byte[] input, out byte[] inputResponse, out byte[] outputResponse, uint maxInputResponse, uint maxOutputResponse); /// <summary> /// Close file, named pipe, directory /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void Close(); /// <summary> /// Disconnect share /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if there is any error occurred</exception> public abstract void DisconnetShare(); #endregion } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2014 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 11.0Release // Tag = $Name: AKW11_000 $ //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the BloodPressure profile message. /// </summary> public class BloodPressureMesg : Mesg { #region Fields #endregion #region Constructors public BloodPressureMesg() : base(Profile.mesgs[Profile.BloodPressureIndex]) { } public BloodPressureMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the Timestamp field /// Units: s</summary> /// <returns>Returns DateTime representing the Timestamp field</returns> public DateTime GetTimestamp() { return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set Timestamp field /// Units: s</summary> /// <param name="timestamp_">Nullable field value to be set</param> public void SetTimestamp(DateTime timestamp_) { SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SystolicPressure field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the SystolicPressure field</returns> public ushort? GetSystolicPressure() { return (ushort?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set SystolicPressure field /// Units: mmHg</summary> /// <param name="systolicPressure_">Nullable field value to be set</param> public void SetSystolicPressure(ushort? systolicPressure_) { SetFieldValue(0, 0, systolicPressure_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the DiastolicPressure field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the DiastolicPressure field</returns> public ushort? GetDiastolicPressure() { return (ushort?)GetFieldValue(1, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set DiastolicPressure field /// Units: mmHg</summary> /// <param name="diastolicPressure_">Nullable field value to be set</param> public void SetDiastolicPressure(ushort? diastolicPressure_) { SetFieldValue(1, 0, diastolicPressure_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the MeanArterialPressure field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the MeanArterialPressure field</returns> public ushort? GetMeanArterialPressure() { return (ushort?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MeanArterialPressure field /// Units: mmHg</summary> /// <param name="meanArterialPressure_">Nullable field value to be set</param> public void SetMeanArterialPressure(ushort? meanArterialPressure_) { SetFieldValue(2, 0, meanArterialPressure_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Map3SampleMean field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the Map3SampleMean field</returns> public ushort? GetMap3SampleMean() { return (ushort?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Map3SampleMean field /// Units: mmHg</summary> /// <param name="map3SampleMean_">Nullable field value to be set</param> public void SetMap3SampleMean(ushort? map3SampleMean_) { SetFieldValue(3, 0, map3SampleMean_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the MapMorningValues field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the MapMorningValues field</returns> public ushort? GetMapMorningValues() { return (ushort?)GetFieldValue(4, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MapMorningValues field /// Units: mmHg</summary> /// <param name="mapMorningValues_">Nullable field value to be set</param> public void SetMapMorningValues(ushort? mapMorningValues_) { SetFieldValue(4, 0, mapMorningValues_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the MapEveningValues field /// Units: mmHg</summary> /// <returns>Returns nullable ushort representing the MapEveningValues field</returns> public ushort? GetMapEveningValues() { return (ushort?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MapEveningValues field /// Units: mmHg</summary> /// <param name="mapEveningValues_">Nullable field value to be set</param> public void SetMapEveningValues(ushort? mapEveningValues_) { SetFieldValue(5, 0, mapEveningValues_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the HeartRate field /// Units: bpm</summary> /// <returns>Returns nullable byte representing the HeartRate field</returns> public byte? GetHeartRate() { return (byte?)GetFieldValue(6, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set HeartRate field /// Units: bpm</summary> /// <param name="heartRate_">Nullable field value to be set</param> public void SetHeartRate(byte? heartRate_) { SetFieldValue(6, 0, heartRate_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the HeartRateType field</summary> /// <returns>Returns nullable HrType enum representing the HeartRateType field</returns> public HrType? GetHeartRateType() { object obj = GetFieldValue(7, 0, Fit.SubfieldIndexMainField); HrType? value = obj == null ? (HrType?)null : (HrType)obj; return value; } /// <summary> /// Set HeartRateType field</summary> /// <param name="heartRateType_">Nullable field value to be set</param> public void SetHeartRateType(HrType? heartRateType_) { SetFieldValue(7, 0, heartRateType_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Status field</summary> /// <returns>Returns nullable BpStatus enum representing the Status field</returns> public BpStatus? GetStatus() { object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField); BpStatus? value = obj == null ? (BpStatus?)null : (BpStatus)obj; return value; } /// <summary> /// Set Status field</summary> /// <param name="status_">Nullable field value to be set</param> public void SetStatus(BpStatus? status_) { SetFieldValue(8, 0, status_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the UserProfileIndex field /// Comment: Associates this blood pressure message to a user. This corresponds to the index of the user profile message in the blood pressure file.</summary> /// <returns>Returns nullable ushort representing the UserProfileIndex field</returns> public ushort? GetUserProfileIndex() { return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set UserProfileIndex field /// Comment: Associates this blood pressure message to a user. This corresponds to the index of the user profile message in the blood pressure file.</summary> /// <param name="userProfileIndex_">Nullable field value to be set</param> public void SetUserProfileIndex(ushort? userProfileIndex_) { SetFieldValue(9, 0, userProfileIndex_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
using System; using System.Collections.Generic; using System.Drawing; using Sce.Atf; using Sce.Atf.Dom; using Sce.Atf.Adaptation; using Sce.Atf.Controls.Timelines; using Sce.Atf.Controls.CurveEditing; using Sce.Atf.VectorMath; using pico.Timeline; namespace picoTimelineEditor.DomNodeAdapters { /// <summary> /// Adapts DomNode to an IntervalBlendFactor</summary> public class IntervalBlendFactor : Interval, ICurveSet, ITimelineObjectCreator, ITimelineValidationCallback { /// <summary> /// Gets and sets the event's name</summary> public override string Name { get { return (string) DomNode.GetAttribute( Schema.intervalBlendFactorType.nameAttribute ); } set { DomNode.SetAttribute( Schema.intervalBlendFactorType.nameAttribute, value ); } } /// <summary> /// Gets and sets the event's length (duration)</summary> public override float Length { get { return (float) DomNode.GetAttribute( Schema.intervalBlendFactorType.lengthAttribute ); } set { float constrained = Math.Max( value, 1 ); // >= 1 constrained = (float)MathUtil.Snap( constrained, 1.0 ); // snapped to nearest integral frame number DomNode.SetAttribute( Schema.intervalBlendFactorType.lengthAttribute, constrained ); } } /// <summary> /// Gets and sets the event's color</summary> public override Color Color { get { return Color.FromArgb( (int) DomNode.GetAttribute( Schema.intervalBlendFactorType.colorAttribute ) ); } set { DomNode.SetAttribute( Schema.intervalBlendFactorType.colorAttribute, value.ToArgb() ); } } /// <summary> /// Performs initialization when the adapter is connected to the diagram annotation's DomNode. /// Raises the DomNodeAdapter NodeSet event. Creates several curves, automatically added to the animation.</summary> protected override void OnNodeSet() { base.OnNodeSet(); DomNode.AttributeChanged += DomNode_AttributeChanged; m_curves = GetChildList<ICurve>( Schema.intervalBlendFactorType.curveChild ); if ( m_curves.Count > 0 ) return; // add sample curve Curve curve = (new DomNode( Schema.curveType.Type )).As<Curve>(); curve.Name = Name; curve.DisplayName = "BlendValue:" + Name; curve.MinX = 0; curve.MaxX = (float)( Length * 0.001 ); curve.MinY = 0.0f; curve.MaxY = 1.0f; curve.CurveColor = Color; curve.PreInfinity = CurveLoopTypes.Constant; curve.PostInfinity = CurveLoopTypes.Constant; curve.XLabel = "Time"; curve.YLabel = "Value"; Vec2F pStart = new Vec2F( 0, 1 ); Vec2F pEnd = new Vec2F( curve.MaxX, 0 ); Vec2F p1 = Vec2F.Lerp( pStart, pEnd, 0.33f ); Vec2F p2 = Vec2F.Lerp( pStart, pEnd, 0.66f ); IControlPoint cp = curve.CreateControlPoint(); cp.X = pStart.X; cp.Y = pStart.Y; curve.AddControlPoint( cp ); cp = curve.CreateControlPoint(); cp.X = p1.X; cp.Y = p1.Y; curve.AddControlPoint( cp ); cp = curve.CreateControlPoint(); cp.X = p2.X; cp.Y = p2.Y; curve.AddControlPoint( cp ); cp = curve.CreateControlPoint(); cp.X = pEnd.X; cp.Y = pEnd.Y; curve.AddControlPoint( cp ); CurveUtils.ComputeTangent( curve ); m_curves.Add( curve ); } private void DomNode_AttributeChanged( object sender, AttributeEventArgs e ) { if ( e.AttributeInfo.Equivalent( Schema.intervalBlendFactorType.lengthAttribute ) ) { foreach( Curve curve in m_curves ) { float newLength = (float)( Length * 0.001 ); float oldLength = curve.MaxX; oldLength = Math.Max( oldLength, 0.001f ); float scale = newLength / oldLength; if ( scale > 1.0f ) curve.MaxX = newLength; foreach ( IControlPoint cp in curve.ControlPoints ) { cp.X = cp.X * scale; } if ( scale < 1.0f ) curve.MaxX = newLength; CurveUtils.ComputeTangent( curve ); curve.CurveColor = Color; } } else if ( e.AttributeInfo.Equivalent( Schema.intervalBlendFactorType.nameAttribute ) ) { foreach ( Curve curve in m_curves ) { curve.Name = Name; curve.DisplayName = "BlendValue: " + Name; } } else if ( e.AttributeInfo.Equivalent( Schema.intervalBlendFactorType.colorAttribute ) ) { foreach ( Curve curve in m_curves ) { curve.CurveColor = Color; } } } #region ICurveSet Members /// <summary> /// Gets list of the curves associated with an animation.</summary> public IList<ICurve> Curves { get { return m_curves; } } private IList<ICurve> m_curves; #endregion #region ITimelineObjectCreator Members ITimelineObject ITimelineObjectCreator.Create() { DomNodeType nodeType = Schema.intervalBlendFactorType.Type; DomNode dn = new DomNode( nodeType ); NodeTypePaletteItem paletteItem = nodeType.GetTag<NodeTypePaletteItem>(); if (paletteItem != null) dn.SetAttribute( nodeType.IdAttribute, paletteItem.Name ); else dn.SetAttribute( nodeType.IdAttribute, "BlendFactor" ); return dn.Cast<ITimelineObject>(); } #endregion public bool CanParentTo( DomNode parent ) { return ValidateImpl( parent, 0 ); } public bool Validate( DomNode parent ) { return ValidateImpl( parent, 1 ); } private bool ValidateImpl( DomNode parent, int validating ) { if ( parent.Type != Schema.trackBlendFactorType.Type ) return false; return true; } } }
// Copyright 2007-2014 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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. namespace MassTransit { using System; using NewIdFormatters; using NewIdProviders; /// <summary> /// A NewId is a type that fits into the same space as a Guid/Uuid/uniqueidentifier, /// but is guaranteed to be both unique and ordered, assuming it is generated using /// a single instance of the generator for each network address used. /// </summary> public struct NewId : IEquatable<NewId>, IComparable<NewId>, IComparable, IFormattable { public static readonly NewId Empty = new NewId(0, 0, 0, 0); static readonly INewIdFormatter _braceFormatter = new DashedHexFormatter('{', '}'); static readonly INewIdFormatter _dashedHexFormatter = new DashedHexFormatter(); static readonly INewIdFormatter _hexFormatter = new HexFormatter(); static readonly INewIdFormatter _parenFormatter = new DashedHexFormatter('(', ')'); static NewIdGenerator _generator; static ITickProvider _tickProvider; static IWorkerIdProvider _workerIdProvider; readonly Int32 _a; readonly Int32 _b; readonly Int32 _c; readonly Int32 _d; /// <summary> /// Creates a NewId using the specified byte array. /// </summary> /// <param name="bytes"></param> public NewId(byte[] bytes) { if (bytes == null) throw new ArgumentNullException("bytes"); if (bytes.Length != 16) throw new ArgumentException("Exactly 16 bytes expected", "bytes"); FromByteArray(bytes, out _a, out _b, out _c, out _d); } public NewId(string value) { if (string.IsNullOrEmpty(value)) throw new ArgumentException("must not be null or empty", "value"); var guid = new Guid(value); byte[] bytes = guid.ToByteArray(); FromByteArray(bytes, out _a, out _b, out _c, out _d); } public NewId(int a, int b, int c, int d) { _a = a; _b = b; _c = c; _d = d; } public NewId(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (f << 24) | (g << 16) | (h << 8) | i; _b = (j << 24) | (k << 16) | (d << 8) | e; _c = (c << 16) | b; _d = a; } static NewIdGenerator Generator { get { return _generator ?? (_generator = new NewIdGenerator(TickProvider, WorkerIdProvider)); } } static IWorkerIdProvider WorkerIdProvider { get { return _workerIdProvider ?? (_workerIdProvider = new BestPossibleWorkerIdProvider()); } } static ITickProvider TickProvider { get { return _tickProvider ?? (_tickProvider = new StopwatchTickProvider()); } } public DateTime Timestamp { get { var ticks = (long)(((ulong)_a) << 32 | (uint)_b); return new DateTime(ticks, DateTimeKind.Utc); } } public int CompareTo(object obj) { if (obj == null) return 1; if (!(obj is NewId)) throw new ArgumentException("Argument must be a NewId"); return CompareTo((NewId)obj); } public int CompareTo(NewId other) { if (_a != other._a) return ((uint)_a < (uint)other._a) ? -1 : 1; if (_b != other._b) return ((uint)_b < (uint)other._b) ? -1 : 1; if (_c != other._c) return ((uint)_c < (uint)other._c) ? -1 : 1; if (_d != other._d) return ((uint)_d < (uint)other._d) ? -1 : 1; return 0; } public bool Equals(NewId other) { return other._a == _a && other._b == _b && other._c == _c && other._d == _d; } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) format = "D"; bool sequential = false; if (format.Length == 2 && (format[1] == 'S' || format[1] == 's')) sequential = true; else if (format.Length != 1) throw new FormatException("The format string must be exactly one character or null"); char formatCh = format[0]; byte[] bytes = sequential ? GetSequentialFormatteryArray() : GetFormatteryArray(); if (formatCh == 'B' || formatCh == 'b') return _braceFormatter.Format(bytes); if (formatCh == 'P' || formatCh == 'p') return _parenFormatter.Format(bytes); if (formatCh == 'D' || formatCh == 'd') return _dashedHexFormatter.Format(bytes); if (formatCh == 'N' || formatCh == 'n') return _hexFormatter.Format(bytes); throw new FormatException("The format string was not valid"); } public string ToString(INewIdFormatter formatter, bool sequential = false) { byte[] bytes = sequential ? GetSequentialFormatteryArray() : GetFormatteryArray(); return formatter.Format(bytes); } byte[] GetFormatteryArray() { var bytes = new byte[16]; bytes[0] = (byte)(_d >> 24); bytes[1] = (byte)(_d >> 16); bytes[2] = (byte)(_d >> 8); bytes[3] = (byte)_d; bytes[4] = (byte)(_c >> 8); bytes[5] = (byte)_c; bytes[6] = (byte)(_c >> 24); bytes[7] = (byte)(_c >> 16); bytes[8] = (byte)(_b >> 8); bytes[9] = (byte)_b; bytes[10] = (byte)(_a >> 24); bytes[11] = (byte)(_a >> 16); bytes[12] = (byte)(_a >> 8); bytes[13] = (byte)_a; bytes[14] = (byte)(_b >> 24); bytes[15] = (byte)(_b >> 16); return bytes; } byte[] GetSequentialFormatteryArray() { var bytes = new byte[16]; bytes[0] = (byte)(_a >> 24); bytes[1] = (byte)(_a >> 16); bytes[2] = (byte)(_a >> 8); bytes[3] = (byte)_a; bytes[4] = (byte)(_b >> 24); bytes[5] = (byte)(_b >> 16); bytes[6] = (byte)(_b >> 8); bytes[7] = (byte)_b; bytes[8] = (byte)(_c >> 24); bytes[9] = (byte)(_c >> 16); bytes[10] = (byte)(_c >> 8); bytes[11] = (byte)_c; bytes[12] = (byte)(_d >> 24); bytes[13] = (byte)(_d >> 16); bytes[14] = (byte)(_d >> 8); bytes[15] = (byte)_d; return bytes; } public Guid ToGuid() { int a = _d; var b = (short)_c; var c = (short)(_c >> 16); var d = (byte)(_b >> 8); var e = (byte)_b; var f = (byte)(_a >> 24); var g = (byte)(_a >> 16); var h = (byte)(_a >> 8); var i = (byte)_a; var j = (byte)(_b >> 24); var k = (byte)(_b >> 16); return new Guid(a, b, c, d, e, f, g, h, i, j, k); } public Guid ToSequentialGuid() { int a = _a; var b = (short)(_b >> 16); var c = (short)_b; var d = (byte)(_c >> 24); var e = (byte)(_c >> 16); var f = (byte)(_c >> 8); var g = (byte)(_c); var h = (byte)(_d >> 24); var i = (byte)(_d >> 16); var j = (byte)(_d >> 8); var k = (byte)(_d); return new Guid(a, b, c, d, e, f, g, h, i, j, k); } public byte[] ToByteArray() { var bytes = new byte[16]; bytes[0] = (byte)(_d); bytes[1] = (byte)(_d >> 8); bytes[2] = (byte)(_d >> 16); bytes[3] = (byte)(_d >> 24); bytes[4] = (byte)(_c); bytes[5] = (byte)(_c >> 8); bytes[6] = (byte)(_c >> 16); bytes[7] = (byte)(_c >> 24); bytes[8] = (byte)(_b >> 8); bytes[9] = (byte)(_b); bytes[10] = (byte)(_a >> 24); bytes[11] = (byte)(_a >> 16); bytes[12] = (byte)(_a >> 8); bytes[13] = (byte)(_a); bytes[14] = (byte)(_b >> 24); bytes[15] = (byte)(_b >> 16); return bytes; } public override string ToString() { return ToString("D", null); } public string ToString(string format) { return ToString(format, null); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (obj.GetType() != typeof(NewId)) return false; return Equals((NewId)obj); } public override int GetHashCode() { unchecked { int result = _a; result = (result * 397) ^ _b; result = (result * 397) ^ _c; result = (result * 397) ^ _d; return result; } } public static bool operator ==(NewId left, NewId right) { return left._a == right._a && left._b == right._b && left._c == right._c && left._d == right._d; } public static bool operator !=(NewId left, NewId right) { return !(left == right); } public static void SetGenerator(NewIdGenerator generator) { _generator = generator; } public static void SetWorkerIdProvider(IWorkerIdProvider provider) { _workerIdProvider = provider; } public static void SetTickProvider(ITickProvider provider) { _tickProvider = provider; } public static NewId Next() { return Generator.Next(); } public static Guid NextGuid() { return Generator.Next().ToGuid(); } static void FromByteArray(byte[] bytes, out Int32 a, out Int32 b, out Int32 c, out Int32 d) { a = bytes[10] << 24 | bytes[11] << 16 | bytes[12] << 8 | bytes[13]; b = bytes[14] << 24 | bytes[15] << 16 | bytes[8] << 8 | bytes[9]; c = bytes[7] << 24 | bytes[6] << 16 | bytes[5] << 8 | bytes[4]; d = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections; using System.IO; using System.Globalization; using System.Diagnostics; using System.Reflection; namespace System.Xml.Serialization { ///<internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class CodeIdentifier { internal const int MaxIdentifierLength = 511; [Obsolete("This class should never get constructed as it contains only static methods.")] public CodeIdentifier() { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakePascal(string identifier) { identifier = MakeValid(identifier); if (identifier.Length <= 2) return CultureInfo.InvariantCulture.TextInfo.ToUpper(identifier); else if (char.IsLower(identifier[0])) return char.ToUpperInvariant(identifier[0]) + identifier.Substring(1); else return identifier; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakeCamel(string identifier) { identifier = MakeValid(identifier); if (identifier.Length <= 2) return CultureInfo.InvariantCulture.TextInfo.ToLower(identifier); else if (char.IsUpper(identifier[0])) return char.ToLower(identifier[0]) + identifier.Substring(1); else return identifier; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static string MakeValid(string identifier) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++) { char c = identifier[i]; if (IsValid(c)) { if (builder.Length == 0 && !IsValidStart(c)) { builder.Append("Item"); } builder.Append(c); } } if (builder.Length == 0) return "Item"; return builder.ToString(); } internal static string MakeValidInternal(string identifier) { if (identifier.Length > 30) { return "Item"; } return MakeValid(identifier); } private static bool IsValidStart(char c) { // the given char is already a valid name character #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (!IsValid(c)) throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString(CultureInfo.InvariantCulture)), "c"); #endif // First char cannot be a number if (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber) return false; return true; } private static bool IsValid(char c) { UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c); // each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc // switch (uc) { case UnicodeCategory.UppercaseLetter: // Lu case UnicodeCategory.LowercaseLetter: // Ll case UnicodeCategory.TitlecaseLetter: // Lt case UnicodeCategory.ModifierLetter: // Lm case UnicodeCategory.OtherLetter: // Lo case UnicodeCategory.DecimalDigitNumber: // Nd case UnicodeCategory.NonSpacingMark: // Mn case UnicodeCategory.SpacingCombiningMark: // Mc case UnicodeCategory.ConnectorPunctuation: // Pc break; case UnicodeCategory.LetterNumber: case UnicodeCategory.OtherNumber: case UnicodeCategory.EnclosingMark: case UnicodeCategory.SpaceSeparator: case UnicodeCategory.LineSeparator: case UnicodeCategory.ParagraphSeparator: case UnicodeCategory.Control: case UnicodeCategory.Format: case UnicodeCategory.Surrogate: case UnicodeCategory.PrivateUse: case UnicodeCategory.DashPunctuation: case UnicodeCategory.OpenPunctuation: case UnicodeCategory.ClosePunctuation: case UnicodeCategory.InitialQuotePunctuation: case UnicodeCategory.FinalQuotePunctuation: case UnicodeCategory.OtherPunctuation: case UnicodeCategory.MathSymbol: case UnicodeCategory.CurrencySymbol: case UnicodeCategory.ModifierSymbol: case UnicodeCategory.OtherSymbol: case UnicodeCategory.OtherNotAssigned: return false; default: #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe throw new ArgumentException(SR.Format(SR.XmlInternalErrorDetails, "Unhandled category " + uc), "c"); #else return false; #endif } return true; } internal static void CheckValidIdentifier(string ident) { if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(ident)) throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident)); } internal static string GetCSharpName(string name) { return EscapeKeywords(name.Replace('+', '.')); } private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb) { if (t.DeclaringType != null && t.DeclaringType != t) { index = GetCSharpName(t.DeclaringType, parameters, index, sb); sb.Append("."); } string name = t.Name; int nameEnd = name.IndexOf('`'); if (nameEnd < 0) { nameEnd = name.IndexOf('!'); } if (nameEnd > 0) { EscapeKeywords(name.Substring(0, nameEnd), sb); sb.Append("<"); int arguments = Int32.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index; for (; index < arguments; index++) { sb.Append(GetCSharpName(parameters[index])); if (index < arguments - 1) { sb.Append(","); } } sb.Append(">"); } else { EscapeKeywords(name, sb); } return index; } internal static string GetCSharpName(Type t) { int rank = 0; while (t.IsArray) { t = t.GetElementType(); rank++; } StringBuilder sb = new StringBuilder(); sb.Append("global::"); string ns = t.Namespace; if (ns != null && ns.Length > 0) { string[] parts = ns.Split(new char[] { '.' }); for (int i = 0; i < parts.Length; i++) { EscapeKeywords(parts[i], sb); sb.Append("."); } } Type[] arguments = t.IsGenericType || t.ContainsGenericParameters ? t.GetGenericArguments() : Array.Empty<Type>(); GetCSharpName(t, arguments, 0, sb); for (int i = 0; i < rank; i++) { sb.Append("[]"); } return sb.ToString(); } /* internal static string GetTypeName(string name, CodeDomProvider codeProvider) { return codeProvider.GetTypeOutput(new CodeTypeReference(name)); } */ private static void EscapeKeywords(string identifier, StringBuilder sb) { if (identifier == null || identifier.Length == 0) return; int arrayCount = 0; while (identifier.EndsWith("[]", StringComparison.Ordinal)) { arrayCount++; identifier = identifier.Substring(0, identifier.Length - 2); } if (identifier.Length > 0) { CheckValidIdentifier(identifier); identifier = CSharpHelpers.CreateEscapedIdentifier(identifier); sb.Append(identifier); } for (int i = 0; i < arrayCount; i++) { sb.Append("[]"); } } private static string EscapeKeywords(string identifier) { if (identifier == null || identifier.Length == 0) return identifier; string originalIdentifier = identifier; string[] names = identifier.Split(new char[] { '.', ',', '<', '>' }); StringBuilder sb = new StringBuilder(); int separator = -1; for (int i = 0; i < names.Length; i++) { if (separator >= 0) { sb.Append(originalIdentifier.Substring(separator, 1)); } separator++; separator += names[i].Length; string escapedName = names[i].Trim(); EscapeKeywords(escapedName, sb); } if (sb.Length != originalIdentifier.Length) return sb.ToString(); return originalIdentifier; } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input.Touch; namespace Nez { public class Camera : Component { struct CameraInset { internal float left; internal float right; internal float top; internal float bottom; } #region Fields and Properties #region 3D Camera Fields /// <summary> /// z-position of the 3D camera projections. Affects the fov greatly. Lower values make the objects appear very long in the z-direction. /// </summary> public float PositionZ3D = 2000f; /// <summary> /// near clip plane of the 3D camera projection /// </summary> public float NearClipPlane3D = 0.0001f; /// <summary> /// far clip plane of the 3D camera projection /// </summary> public float FarClipPlane3D = 5000f; #endregion /// <summary> /// shortcut to entity.transform.position /// </summary> /// <value>The position.</value> public Vector2 Position { get => Entity.Transform.Position; set => Entity.Transform.Position = value; } /// <summary> /// shortcut to entity.transform.rotation /// </summary> /// <value>The rotation.</value> public float Rotation { get => Entity.Transform.Rotation; set => Entity.Transform.Rotation = value; } /// <summary> /// raw zoom value. This is the exact value used for the scale matrix. Default is 1. /// </summary> /// <value>The raw zoom.</value> [Range(0, 30)] public float RawZoom { get => _zoom; set { if (value != _zoom) { _zoom = value; _areMatrixesDirty = true; } } } /// <summary> /// the zoom value should be between -1 and 1. This value is then translated to be from minimumZoom to maximumZoom. This lets you set /// appropriate minimum/maximum values then use a more intuitive -1 to 1 mapping to change the zoom. /// </summary> /// <value>The zoom.</value> [Range(-1, 1)] public float Zoom { get { if (_zoom == 0) return 1f; if (_zoom < 1) return Mathf.Map(_zoom, _minimumZoom, 1, -1, 0); return Mathf.Map(_zoom, 1, _maximumZoom, 0, 1); } set => SetZoom(value); } /// <summary> /// minimum non-scaled value (0 - float.Max) that the camera zoom can be. Defaults to 0.3 /// </summary> /// <value>The minimum zoom.</value> [Range(0, 30)] public float MinimumZoom { get => _minimumZoom; set => SetMinimumZoom(value); } /// <summary> /// maximum non-scaled value (0 - float.Max) that the camera zoom can be. Defaults to 3 /// </summary> /// <value>The maximum zoom.</value> [Range(0, 30)] public float MaximumZoom { get => _maximumZoom; set => SetMaximumZoom(value); } /// <summary> /// world-space bounds of the camera. useful for culling. /// </summary> /// <value>The bounds.</value> public RectangleF Bounds { get { if (_areMatrixesDirty) UpdateMatrixes(); if (_areBoundsDirty) { // top-left and bottom-right are needed by either rotated or non-rotated bounds var topLeft = ScreenToWorldPoint(new Vector2(Core.GraphicsDevice.Viewport.X + _inset.left, Core.GraphicsDevice.Viewport.Y + _inset.top)); var bottomRight = ScreenToWorldPoint(new Vector2( Core.GraphicsDevice.Viewport.X + Core.GraphicsDevice.Viewport.Width - _inset.right, Core.GraphicsDevice.Viewport.Y + Core.GraphicsDevice.Viewport.Height - _inset.bottom)); if (Entity.Transform.Rotation != 0) { // special care for rotated bounds. we need to find our absolute min/max values and create the bounds from that var topRight = ScreenToWorldPoint(new Vector2( Core.GraphicsDevice.Viewport.X + Core.GraphicsDevice.Viewport.Width - _inset.right, Core.GraphicsDevice.Viewport.Y + _inset.top)); var bottomLeft = ScreenToWorldPoint(new Vector2(Core.GraphicsDevice.Viewport.X + _inset.left, Core.GraphicsDevice.Viewport.Y + Core.GraphicsDevice.Viewport.Height - _inset.bottom)); var minX = Mathf.MinOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X); var maxX = Mathf.MaxOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X); var minY = Mathf.MinOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y); var maxY = Mathf.MaxOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y); _bounds.Location = new Vector2(minX, minY); _bounds.Width = maxX - minX; _bounds.Height = maxY - minY; } else { _bounds.Location = topLeft; _bounds.Width = bottomRight.X - topLeft.X; _bounds.Height = bottomRight.Y - topLeft.Y; } _areBoundsDirty = false; } return _bounds; } } /// <summary> /// used to convert from world coordinates to screen /// </summary> /// <value>The transform matrix.</value> public Matrix2D TransformMatrix { get { if (_areMatrixesDirty) UpdateMatrixes(); return _transformMatrix; } } /// <summary> /// used to convert from screen coordinates to world /// </summary> /// <value>The inverse transform matrix.</value> public Matrix2D InverseTransformMatrix { get { if (_areMatrixesDirty) UpdateMatrixes(); return _inverseTransformMatrix; } } /// <summary> /// the 2D Cameras projection matrix /// </summary> /// <value>The projection matrix.</value> public Matrix ProjectionMatrix { get { if (_isProjectionMatrixDirty) { Matrix.CreateOrthographicOffCenter(0, Core.GraphicsDevice.Viewport.Width, Core.GraphicsDevice.Viewport.Height, 0, 0, -1, out _projectionMatrix); _isProjectionMatrixDirty = false; } return _projectionMatrix; } } /// <summary> /// gets the view-projection matrix which is the transformMatrix * the projection matrix /// </summary> /// <value>The view projection matrix.</value> public Matrix ViewProjectionMatrix => TransformMatrix * ProjectionMatrix; #region 3D Camera Matrixes /// <summary> /// returns a perspective projection for this camera for use when rendering 3D objects /// </summary> /// <value>The projection matrix3 d.</value> public Matrix ProjectionMatrix3D { get { var targetHeight = (Core.GraphicsDevice.Viewport.Height / _zoom); var fov = (float) Math.Atan(targetHeight / (2f * PositionZ3D)) * 2f; return Matrix.CreatePerspectiveFieldOfView(fov, Core.GraphicsDevice.Viewport.AspectRatio, NearClipPlane3D, FarClipPlane3D); } } /// <summary> /// returns a view Matrix via CreateLookAt for this camera for use when rendering 3D objects /// </summary> /// <value>The view matrix3 d.</value> public Matrix ViewMatrix3D { get { // we need to always invert the y-values to match the way Batcher/SpriteBatch does things var position3D = new Vector3(Position.X, -Position.Y, PositionZ3D); return Matrix.CreateLookAt(position3D, position3D + Vector3.Forward, Vector3.Up); } } #endregion public Vector2 Origin { get => _origin; internal set { if (_origin != value) { _origin = value; _areMatrixesDirty = true; } } } float _zoom; float _minimumZoom = 0.3f; float _maximumZoom = 3f; RectangleF _bounds; CameraInset _inset; Matrix2D _transformMatrix = Matrix2D.Identity; Matrix2D _inverseTransformMatrix = Matrix2D.Identity; Matrix _projectionMatrix; Vector2 _origin; bool _areMatrixesDirty = true; bool _areBoundsDirty = true; bool _isProjectionMatrixDirty = true; #endregion public Camera() { SetZoom(0); } /// <summary> /// when the scene render target size changes we update the cameras origin and adjust the position to keep it where it was /// </summary> /// <param name="newWidth">New width.</param> /// <param name="newHeight">New height.</param> internal void OnSceneRenderTargetSizeChanged(int newWidth, int newHeight) { _isProjectionMatrixDirty = true; var oldOrigin = _origin; Origin = new Vector2(newWidth / 2f, newHeight / 2f); // offset our position to match the new center Entity.Transform.Position += (_origin - oldOrigin); } protected virtual void UpdateMatrixes() { if (!_areMatrixesDirty) return; Matrix2D tempMat; _transformMatrix = Matrix2D.CreateTranslation(-Entity.Transform.Position.X, -Entity.Transform.Position.Y); // position if (_zoom != 1f) { Matrix2D.CreateScale(_zoom, _zoom, out tempMat); // scale -> Matrix2D.Multiply(ref _transformMatrix, ref tempMat, out _transformMatrix); } if (Entity.Transform.Rotation != 0f) { Matrix2D.CreateRotation(Entity.Transform.Rotation, out tempMat); // rotation Matrix2D.Multiply(ref _transformMatrix, ref tempMat, out _transformMatrix); } Matrix2D.CreateTranslation((int) _origin.X, (int) _origin.Y, out tempMat); // translate -origin Matrix2D.Multiply(ref _transformMatrix, ref tempMat, out _transformMatrix); // calculate our inverse as well Matrix2D.Invert(ref _transformMatrix, out _inverseTransformMatrix); // whenever the matrix changes the bounds are then invalid _areBoundsDirty = true; _areMatrixesDirty = false; } #region Fluent setters /// <summary> /// sets the amount used to inset the camera bounds from the viewport edge /// </summary> /// <param name="left">The amount to set the left bounds in from the viewport.</param> /// <param name="right">The amount to set the right bounds in from the viewport.</param> /// <param name="top">The amount to set the top bounds in from the viewport.</param> /// <param name="bottom">The amount to set the bottom bounds in from the viewport.</param> public Camera SetInset(float left, float right, float top, float bottom) { _inset = new CameraInset {left = left, right = right, top = top, bottom = bottom}; _areBoundsDirty = true; return this; } /// <summary> /// shortcut to entity.transform.setPosition /// </summary> /// <param name="position">Position.</param> public Camera SetPosition(Vector2 position) { Entity.Transform.SetPosition(position); return this; } /// <summary> /// shortcut to entity.transform.setRotation /// </summary> /// <param name="radians">Radians.</param> public Camera SetRotation(float radians) { Entity.Transform.SetRotation(radians); return this; } /// <summary> /// shortcut to entity.transform.setRotationDegrees /// </summary> /// <param name="degrees">Degrees.</param> public Camera SetRotationDegrees(float degrees) { Entity.Transform.SetRotationDegrees(degrees); return this; } /// <summary> /// sets the the zoom value which should be between -1 and 1. This value is then translated to be from minimumZoom to maximumZoom. /// This lets you set appropriate minimum/maximum values then use a more intuitive -1 to 1 mapping to change the zoom. /// </summary> /// <param name="zoom">Zoom.</param> public Camera SetZoom(float zoom) { var newZoom = Mathf.Clamp(zoom, -1, 1); if (newZoom == 0) _zoom = 1f; else if (newZoom < 0) _zoom = Mathf.Map(newZoom, -1, 0, _minimumZoom, 1); else _zoom = Mathf.Map(newZoom, 0, 1, 1, _maximumZoom); _areMatrixesDirty = true; return this; } /// <summary> /// minimum non-scaled value (0 - float.Max) that the camera zoom can be. Defaults to 0.3 /// </summary> /// <param name="value">Value.</param> public Camera SetMinimumZoom(float minZoom) { Insist.IsTrue(minZoom > 0, "minimumZoom must be greater than zero"); if (_zoom < minZoom) _zoom = MinimumZoom; _minimumZoom = minZoom; return this; } /// <summary> /// maximum non-scaled value (0 - float.Max) that the camera zoom can be. Defaults to 3 /// </summary> /// <param name="maxZoom">Max zoom.</param> public Camera SetMaximumZoom(float maxZoom) { Insist.IsTrue(maxZoom > 0, "MaximumZoom must be greater than zero"); if (_zoom > maxZoom) _zoom = maxZoom; _maximumZoom = maxZoom; return this; } #endregion /// <summary> /// this forces the matrix and bounds dirty /// </summary> public void ForceMatrixUpdate() { // dirtying the matrix will automatically dirty the bounds as well _areMatrixesDirty = true; } #region component overrides public override void OnEntityTransformChanged(Transform.Component comp) { _areMatrixesDirty = true; } #endregion #region zoom helpers public void ZoomIn(float deltaZoom) { Zoom += deltaZoom; } public void ZoomOut(float deltaZoom) { Zoom -= deltaZoom; } #endregion #region transformations /// <summary> /// converts a point from world coordinates to screen /// </summary> /// <returns>The to screen point.</returns> /// <param name="worldPosition">World position.</param> public Vector2 WorldToScreenPoint(Vector2 worldPosition) { UpdateMatrixes(); Vector2Ext.Transform(ref worldPosition, ref _transformMatrix, out worldPosition); return worldPosition; } /// <summary> /// converts a point from screen coordinates to world /// </summary> /// <returns>The to world point.</returns> /// <param name="screenPosition">Screen position.</param> public Vector2 ScreenToWorldPoint(Vector2 screenPosition) { UpdateMatrixes(); Vector2Ext.Transform(ref screenPosition, ref _inverseTransformMatrix, out screenPosition); return screenPosition; } /// <summary> /// converts a point from screen coordinates to world /// </summary> /// <returns>The to world point.</returns> /// <param name="screenPosition">Screen position.</param> public Vector2 ScreenToWorldPoint(Point screenPosition) { return ScreenToWorldPoint(screenPosition.ToVector2()); } /// <summary> /// returns the mouse position in world space /// </summary> /// <returns>The to world point.</returns> public Vector2 MouseToWorldPoint() { return ScreenToWorldPoint(Input.MousePosition); } /// <summary> /// returns the touch position in world space /// </summary> /// <returns>The to world point.</returns> public Vector2 TouchToWorldPoint(TouchLocation touch) { return ScreenToWorldPoint(touch.ScaledPosition()); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// The specification for a pool. /// </summary> public partial class PoolSpecification : ITransportObjectProvider<Models.PoolSpecification>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty; public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty; public readonly PropertyAccessor<string> AutoScaleFormulaProperty; public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty; public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty; public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty; public readonly PropertyAccessor<StartTask> StartTaskProperty; public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty; public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty; public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty; public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty; public readonly PropertyAccessor<string> VirtualMachineSizeProperty; public PropertyContainer() : base(BindingState.Unbound) { this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.PoolSpecification protocolObject) : base(BindingState.Bound) { this.ApplicationLicensesProperty = this.CreatePropertyAccessor( UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o), nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableAutoScale, nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleEvaluationInterval, nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleFormula, nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.CertificateReferencesProperty = this.CreatePropertyAccessor( CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences), nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o)), nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableInterNodeCommunication, nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor( protocolObject.MaxTasksPerNode, nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.ResizeTimeoutProperty = this.CreatePropertyAccessor( protocolObject.ResizeTimeout, nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)), nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetDedicatedNodes, nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetLowPriorityNodes, nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o)), nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UserAccountsProperty = this.CreatePropertyAccessor( UserAccount.ConvertFromProtocolCollection(protocolObject.UserAccounts), nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o)), nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor( protocolObject.VmSize, nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PoolSpecification"/> class. /// </summary> public PoolSpecification() { this.propertyContainer = new PropertyContainer(); } internal PoolSpecification(Models.PoolSpecification protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region PoolSpecification /// <summary> /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the /// pool. /// </summary> /// <remarks> /// The list of application licenses must be a subset of available Batch service application licenses. /// </remarks> public IList<string> ApplicationLicenses { get { return this.propertyContainer.ApplicationLicensesProperty.Value; } set { this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value); } } /// <summary> /// Gets or sets a list of application package references to be installed on each compute node in the pool. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the pool size should automatically adjust over time. /// </summary> /// <remarks> /// <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/> /// property is required.</para> <para>If true, the <see cref="AutoScaleFormula"/> property is required. The pool /// automatically resizes according to the formula.</para> <para>The default value is false.</para> /// </remarks> public bool? AutoScaleEnabled { get { return this.propertyContainer.AutoScaleEnabledProperty.Value; } set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; } } /// <summary> /// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// The default value is 15 minutes. The minimum allowed value is 5 minutes. /// </remarks> public TimeSpan? AutoScaleEvaluationInterval { get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; } set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; } } /// <summary> /// Gets or sets a formula for the desired number of compute nodes in the pool. /// </summary> /// <remarks> /// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. /// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled /// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid, /// an exception is thrown when you try to commit the <see cref="PoolSpecification"/>.</para> /// </remarks> public string AutoScaleFormula { get { return this.propertyContainer.AutoScaleFormulaProperty.Value; } set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; } } /// <summary> /// Gets or sets a list of certificates to be installed on each compute node in the pool. /// </summary> public IList<CertificateReference> CertificateReferences { get { return this.propertyContainer.CertificateReferencesProperty.Value; } set { this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool. /// </summary> /// <remarks> /// This property is mutually exclusive with <see cref="VirtualMachineConfiguration"/>. /// </remarks> public CloudServiceConfiguration CloudServiceConfiguration { get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; } set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the display name for the pool. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets or sets whether the pool permits direct communication between its compute nodes. /// </summary> /// <remarks> /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes /// of the pool. This may result in the pool not reaching its desired size. /// </remarks> public bool? InterComputeNodeCommunicationEnabled { get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; } set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; } } /// <summary> /// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool. /// </summary> /// <remarks> /// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool /// (the <see cref="VirtualMachineSize"/> property). /// </remarks> public int? MaxTasksPerComputeNode { get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; } set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the pool as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration of the pool. /// </summary> public NetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the timeout for allocation of compute nodes to the pool. /// </summary> /// <remarks> /// <para>This timeout applies only to manual scaling; it has no effect when <see cref="AutoScaleEnabled"/> is set /// to true.</para><para>The default value is 15 minutes. The minimum value is 5 minutes.</para> /// </remarks> public TimeSpan? ResizeTimeout { get { return this.propertyContainer.ResizeTimeoutProperty.Value; } set { this.propertyContainer.ResizeTimeoutProperty.Value = value; } } /// <summary> /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to /// the pool or when the node is restarted. /// </summary> public StartTask StartTask { get { return this.propertyContainer.StartTaskProperty.Value; } set { this.propertyContainer.StartTaskProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of dedicated compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property /// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false. /// If not specified, the default is 0. /// </remarks> public int? TargetDedicatedComputeNodes { get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; } set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of low-priority compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/> /// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default /// is 0. /// </remarks> public int? TargetLowPriorityComputeNodes { get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; } set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets how tasks are distributed among compute nodes in the pool. /// </summary> public TaskSchedulingPolicy TaskSchedulingPolicy { get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; } set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; } } /// <summary> /// Gets or sets the list of user accounts to be created on each node in the pool. /// </summary> public IList<UserAccount> UserAccounts { get { return this.propertyContainer.UserAccountsProperty.Value; } set { this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool. /// </summary> /// <remarks> /// This property is mutually exclusive with <see cref="CloudServiceConfiguration"/>. /// </remarks> public VirtualMachineConfiguration VirtualMachineConfiguration { get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; } set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size. /// </summary> /// <remarks> /// <para>For information about available sizes of virtual machines for Cloud Services pools (pools created with /// a <see cref="CloudServiceConfiguration"/>), see https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/. /// Batch supports all Cloud Services VM sizes except ExtraSmall.</para><para>For information about available VM /// sizes for pools using images from the Virtual Machines Marketplace (pools created with a <see cref="VirtualMachineConfiguration"/>) /// see https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ or https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/. /// Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (for example STANDARD_GS, /// STANDARD_DS, and STANDARD_DSV2 series).</para> /// </remarks> public string VirtualMachineSize { get { return this.propertyContainer.VirtualMachineSizeProperty.Value; } set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; } } #endregion // PoolSpecification #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.PoolSpecification ITransportObjectProvider<Models.PoolSpecification>.GetTransportObject() { Models.PoolSpecification result = new Models.PoolSpecification() { ApplicationLicenses = this.ApplicationLicenses, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), EnableAutoScale = this.AutoScaleEnabled, AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval, AutoScaleFormula = this.AutoScaleFormula, CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences), CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled, MaxTasksPerNode = this.MaxTasksPerComputeNode, Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), ResizeTimeout = this.ResizeTimeout, StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()), TargetDedicatedNodes = this.TargetDedicatedComputeNodes, TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes, TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()), UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts), VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()), VmSize = this.VirtualMachineSize, }; return result; } #endregion // Internal/private methods } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Simple.Mocking.SetUp.Proxies; using Simple.Mocking.Syntax; namespace Simple.Mocking.SetUp { class InvocationMatcher : IInvocationMatcher { object target; MethodInfo method; IList<object> parameterValueConstraints; public InvocationMatcher(object target, MethodInfo method, IList<object> parameterValueConstraints) { if (InvocationTarget.IsDelegate(target) && method != null) throw new ArgumentException("Can not specify delegate target and method", "method"); this.target = target; this.method = method; this.parameterValueConstraints = parameterValueConstraints; } public object Target { get { return target; } } public MethodInfo Method { get { return method; } } public IList<object> ParameterValueConstraints { get { return parameterValueConstraints; } } public bool Matches(IInvocation invocation) { return MatchesTarget(invocation.Target) && MatchesMethod(invocation.Method, invocation.GenericArguments) && MatchesParameters(invocation.ParameterValues); } bool MatchesTarget(IProxy invocationTarget) { return ReferenceEquals(invocationTarget, InvocationTarget.UnwrapDelegateTarget(target)); } bool MatchesMethod(MethodInfo invocationMethod, IEnumerable<Type> genericArguments) { if (method == null) return (invocationMethod.DeclaringType != typeof(object)); if (genericArguments != null) invocationMethod = invocationMethod.MakeGenericMethod(genericArguments.ToArray()); return method.Equals(invocationMethod); } bool MatchesParameters(IList<object> invocationParameterValues) { if (parameterValueConstraints == null) return true; if (invocationParameterValues.Count != parameterValueConstraints.Count) return false; for (var i = 0; i < parameterValueConstraints.Count; i++) { var constraint = parameterValueConstraints[i]; var value = invocationParameterValues[i]; bool isMatch; if (constraint is IParameterValueConstraint) isMatch = ((IParameterValueConstraint)constraint).Matches(value); else if (constraint == null) isMatch = (value == null); else isMatch = constraint.Equals(value); if (!isMatch) return false; } return true; } public override string ToString() { return InvocationFormatter.Format(target, method, parameterValueConstraints); } static InvocationMatcher CreateInvocationMatcher(object target, MethodInfo method, IEnumerable<object> parameters) { if (method.IsGenericMethod) method = StripParameterValueConstraintsFromGenericArguments(method); return new InvocationMatcher(target, method, parameters.ToList()); } static MethodInfo StripParameterValueConstraintsFromGenericArguments(MethodInfo method) { var genericArguments = from type in method.GetGenericArguments() select ParameterValueConstraintTypeToIntendedType(type); return method.GetGenericMethodDefinition().MakeGenericMethod(genericArguments.ToArray()); } static Type ParameterValueConstraintTypeToIntendedType(Type type) { Type[] genericArguments; if (type.IsGenericType && (genericArguments = type.GetGenericArguments()).Length == 1 && typeof(ParameterValueConstraint<>).MakeGenericType(genericArguments).IsAssignableFrom(type)) { type = type.GetGenericArguments()[0]; } return type; } public static InvocationMatcher ForMethodCall(LambdaExpression methodCallExpression) { if (IsDelegateMethodCall(methodCallExpression)) return CreateForDelegateMethodCall(methodCallExpression); if (IsMethodCall(methodCallExpression)) return CreateForMethodCall(methodCallExpression); throw new ArgumentException( "Expected method call expression: '() => myObject.MyMethod()' or '() => myDelegateHandler()'", "methodCallExpression"); } static bool IsMethodCall(LambdaExpression methodCallExpression) { var body = methodCallExpression.Body as MethodCallExpression; return (body != null && body.Method.GetDeclaringProperty() == null && body.Method.GetDeclaringEvent() == null); } static InvocationMatcher CreateForMethodCall(LambdaExpression methodCallExpression) { var body = (MethodCallExpression)methodCallExpression.Body; var target = ResolveObjectFromExpression(body.Object); var parameters = ParseParameters(body.Arguments, body.Method); return CreateInvocationMatcher(target, body.Method, parameters); } static bool IsDelegateMethodCall(LambdaExpression methodCallExpression) { var body = methodCallExpression.Body as InvocationExpression; return (body != null && ResolveObjectFromExpression(body.Expression) is Delegate); } static InvocationMatcher CreateForDelegateMethodCall(LambdaExpression delegateCallExpression) { var body = (InvocationExpression)delegateCallExpression.Body; var target = (Delegate)ResolveObjectFromExpression(body.Expression); var parameters = ParseParameters(body.Arguments, target.Method); return new InvocationMatcher(target, null, parameters.ToList()); } public static InvocationMatcher ForPropertyGet(LambdaExpression propertyExpression) { return ForPropertyCall(propertyExpression, property => property.GetGetMethod()); } public static InvocationMatcher ForPropertySet(LambdaExpression propertyExpression, object value) { return ForPropertyCall(propertyExpression, property => property.GetSetMethod(), value); } static bool IsPropertyExpression(LambdaExpression propertyExpression) { var body = propertyExpression.Body as MemberExpression; return (body != null && body.Member is PropertyInfo); } static bool IsIndexedPropertyExpression(LambdaExpression propertyExpression) { var body = propertyExpression.Body as MethodCallExpression; return (body != null && body.Method.GetDeclaringProperty() != null); } static InvocationMatcher ForPropertyCall(LambdaExpression propertyExpression, Func<PropertyInfo, MethodInfo> methodSelector, params object[] parameters) { if (IsIndexedPropertyExpression(propertyExpression)) return CreateForIndexedPropertyCall(propertyExpression, methodSelector, parameters); if (IsPropertyExpression(propertyExpression)) return CreateForPropertyCall(propertyExpression, methodSelector, parameters); throw new ArgumentException( "Expected property expression: '() => myObject.Property' or '() => myObject[i]'", "propertyExpression"); } static InvocationMatcher CreateForPropertyCall(LambdaExpression propertyExpression, Func<PropertyInfo, MethodInfo> methodSelector, object[] parameters) { var body = (MemberExpression)propertyExpression.Body; var property = (PropertyInfo)body.Member; var target = ResolveObjectFromExpression(body.Expression); var method = methodSelector(property); return CreateInvocationMatcher(target, method, parameters); } static InvocationMatcher CreateForIndexedPropertyCall(LambdaExpression propertyExpression, Func<PropertyInfo, MethodInfo> methodSelector, object[] valueParameters) { var body = (MethodCallExpression)propertyExpression.Body; var target = ResolveObjectFromExpression(body.Object); var method = methodSelector(body.Method.GetDeclaringProperty()); var parameters = ParseParameters(body.Arguments, body.Method).Concat(valueParameters); return CreateInvocationMatcher(target, method, parameters); } public static InvocationMatcher ForEventAdd<T>(T target, string eventName, object handler) { return CreateForEventAddOrRemove(target, GetEvent<T>(eventName).GetAddMethod(), handler); } public static InvocationMatcher ForEventRemove<T>(T target, string eventName, object handler) { return CreateForEventAddOrRemove(target, GetEvent<T>(eventName).GetRemoveMethod(), handler); } static EventInfo GetEvent<T>(string eventName) { var eventMember = typeof(T).GetEvent(eventName); if (eventMember == null) throw new ArgumentException(string.Format("Event '{0}' is not defined in type '{1}'", eventName, typeof(T)), "eventName"); return eventMember; } static InvocationMatcher CreateForEventAddOrRemove(object target, MethodInfo method, object handler) { return CreateInvocationMatcher(target, method, new[] { handler }); } static IEnumerable<object> ParseParameters(IEnumerable<Expression> arguments, MethodInfo methodInfo) { var methodParameters = methodInfo.GetParameters(); return arguments.Select((argument, i) => ParseParameterConstraint(argument, methodParameters[i])); } static object ResolveObjectFromExpression(Expression expression) { return Expression.Lambda<Func<object>>(Expression.Convert(expression, typeof(object))).Compile()(); } static object ParseParameterConstraint(Expression argumentExpression, ParameterInfo parameter) { return ResolveObjectFromExpression(GetReducedParameterValueConstraintExpression(argumentExpression, parameter)); } static Expression GetReducedParameterValueConstraintExpression(Expression argumentExpression, ParameterInfo parameter) { var reducedExpression = argumentExpression; while (reducedExpression.NodeType == ExpressionType.Convert && reducedExpression is UnaryExpression) reducedExpression = ((UnaryExpression)reducedExpression).Operand; if (reducedExpression.NodeType == ExpressionType.MemberAccess && reducedExpression is MemberExpression) { var memberExpression = (MemberExpression)reducedExpression; if (IsAsRefOrOutExpression(memberExpression)) { AssertParameterTypeIsByRef(memberExpression, parameter); return memberExpression.Expression; } if (IsAsInterfaceExpression(memberExpression)) { AssertGenericArgumentIsInterface(memberExpression); return memberExpression.Expression; } } if (typeof(IParameterValueConstraint).IsAssignableFrom(reducedExpression.Type)) return reducedExpression; return argumentExpression; } static bool IsAsRefOrOutExpression(MemberExpression memberExpression) { return IsFieldInGenericTypeDefinition(memberExpression.Member, typeof(ParameterValueConstraint<>), "AsRefOrOut"); } static bool IsAsInterfaceExpression(MemberExpression memberExpression) { return IsFieldInGenericTypeDefinition(memberExpression.Member, typeof(ParameterValueConstraint<>), "AsInterface"); } static bool IsFieldInGenericTypeDefinition(MemberInfo member, Type genericType, string fieldName) { var declaringType = member.DeclaringType; return ( declaringType.IsGenericType && declaringType.GetGenericTypeDefinition() == genericType && member is FieldInfo && member.Name == fieldName); } static void AssertParameterTypeIsByRef(MemberExpression memberExpression, ParameterInfo parameter) { if (!parameter.ParameterType.IsByRef) throw new ArgumentException( string.Format("Cant set '{0}' as an value constraint for non ref/out parameter {1}", memberExpression, parameter.Name)); } static void AssertGenericArgumentIsInterface(MemberExpression memberExpression) { var genericArgument = memberExpression.Member.DeclaringType.GetGenericArguments()[0]; if (!genericArgument.IsInterface) throw new ArgumentException(string.Format("Cant set '{0}' as an value constraint for non interface type {1}", memberExpression, genericArgument)); } public static InvocationMatcher ForAnyInvocationOn(object target) { return new InvocationMatcher(target, null, null); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace System.Management.Automation.Interpreter { internal abstract partial class CallInstruction : Instruction { public abstract MethodInfo Info { get; } /// <summary> /// The number of arguments including "this" for instance methods. /// </summary> public abstract int ArgumentCount { get; } #region Construction internal CallInstruction() { } private static readonly Dictionary<MethodInfo, CallInstruction> s_cache = new Dictionary<MethodInfo, CallInstruction>(); public static CallInstruction Create(MethodInfo info) { return Create(info, info.GetParameters()); } /// <summary> /// Creates a new ReflectedCaller which can be used to quickly invoke the provided MethodInfo. /// </summary> public static CallInstruction Create(MethodInfo info, ParameterInfo[] parameters) { int argumentCount = parameters.Length; if (!info.IsStatic) { argumentCount++; } // A workaround for CLR bug #796414 (Unable to create delegates for Array.Get/Set): // T[]::Address - not supported by ETs due to T& return value if (info.DeclaringType != null && info.DeclaringType.IsArray && (info.Name == "Get" || info.Name == "Set")) { return GetArrayAccessor(info, argumentCount); } if (info is DynamicMethod || !info.IsStatic && info.DeclaringType.IsValueType) { return new MethodInfoCallInstruction(info, argumentCount); } if (argumentCount >= MaxHelpers) { // no delegate for this size, fallback to reflection invoke return new MethodInfoCallInstruction(info, argumentCount); } foreach (ParameterInfo pi in parameters) { if (pi.ParameterType.IsByRef) { // we don't support ref args via generics. return new MethodInfoCallInstruction(info, argumentCount); } } // see if we've created one w/ a delegate CallInstruction res; if (ShouldCache(info)) { lock (s_cache) { if (s_cache.TryGetValue(info, out res)) { return res; } } } // create it try { if (argumentCount < MaxArgs) { res = FastCreate(info, parameters); } else { res = SlowCreate(info, parameters); } } catch (TargetInvocationException tie) { if (!(tie.InnerException is NotSupportedException)) { throw; } res = new MethodInfoCallInstruction(info, argumentCount); } catch (NotSupportedException) { // if Delegate.CreateDelegate can't handle the method fallback to // the slow reflection version. For example this can happen w/ // a generic method defined on an interface and implemented on a class or // a virtual generic method. res = new MethodInfoCallInstruction(info, argumentCount); } // cache it for future users if it's a reasonable method to cache if (ShouldCache(info)) { lock (s_cache) { s_cache[info] = res; } } return res; } private static CallInstruction GetArrayAccessor(MethodInfo info, int argumentCount) { Type arrayType = info.DeclaringType; bool isGetter = info.Name == "Get"; switch (arrayType.GetArrayRank()) { case 1: return Create(isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int) }) : new Action<Array, int, object>(ArrayItemSetter1).GetMethodInfo() ); case 2: return Create(isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int) }) : new Action<Array, int, int, object>(ArrayItemSetter2).GetMethodInfo() ); case 3: return Create(isGetter ? arrayType.GetMethod("GetValue", new[] { typeof(int), typeof(int), typeof(int) }) : new Action<Array, int, int, int, object>(ArrayItemSetter3).GetMethodInfo() ); default: return new MethodInfoCallInstruction(info, argumentCount); } } public static void ArrayItemSetter1(Array array, int index0, object value) { array.SetValue(value, index0); } public static void ArrayItemSetter2(Array array, int index0, int index1, object value) { array.SetValue(value, index0, index1); } public static void ArrayItemSetter3(Array array, int index0, int index1, int index2, object value) { array.SetValue(value, index0, index1, index2); } private static bool ShouldCache(MethodInfo info) { return !(info is DynamicMethod); } /// <summary> /// Gets the next type or null if no more types are available. /// </summary> private static Type TryGetParameterOrReturnType(MethodInfo target, ParameterInfo[] pi, int index) { if (!target.IsStatic) { index--; if (index < 0) { return target.DeclaringType; } } if (index < pi.Length) { // next in signature return pi[index].ParameterType; } if (target.ReturnType == typeof(void) || index > pi.Length) { // no more parameters return null; } // last parameter on Invoke is return type return target.ReturnType; } private static bool IndexIsNotReturnType(int index, MethodInfo target, ParameterInfo[] pi) { return pi.Length != index || !target.IsStatic; } /// <summary> /// Uses reflection to create new instance of the appropriate ReflectedCaller. /// </summary> private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { List<Type> types = new List<Type>(); if (!info.IsStatic) types.Add(info.DeclaringType); foreach (ParameterInfo pi in pis) { types.Add(pi.ParameterType); } if (info.ReturnType != typeof(void)) { types.Add(info.ReturnType); } Type[] arrTypes = types.ToArray(); return (CallInstruction)Activator.CreateInstance(GetHelperType(info, arrTypes), info); } #endregion #region Instruction public sealed override int ProducedStack { get { return Info.ReturnType == typeof(void) ? 0 : 1; } } public sealed override int ConsumedStack { get { return ArgumentCount; } } public sealed override string InstructionName { get { return "Call"; } } public override string ToString() { return "Call(" + Info + ")"; } #endregion } internal sealed partial class MethodInfoCallInstruction : CallInstruction { private readonly MethodInfo _target; private readonly int _argumentCount; public override MethodInfo Info { get { return _target; } } public override int ArgumentCount { get { return _argumentCount; } } internal MethodInfoCallInstruction(MethodInfo target, int argumentCount) { _target = target; _argumentCount = argumentCount; } public override object Invoke(params object[] args) { return InvokeWorker(args); } public override object InvokeInstance(object instance, params object[] args) { if (_target.IsStatic) { try { return _target.Invoke(null, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } try { return _target.Invoke(instance, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } private object InvokeWorker(params object[] args) { if (_target.IsStatic) { try { return _target.Invoke(null, args); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } try { return _target.Invoke(args[0], GetNonStaticArgs(args)); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } private static object[] GetNonStaticArgs(object[] args) { object[] newArgs = new object[args.Length - 1]; for (int i = 0; i < newArgs.Length; i++) { newArgs[i] = args[i + 1]; } return newArgs; } public sealed override int Run(InterpretedFrame frame) { int first = frame.StackIndex - _argumentCount; object[] args = new object[_argumentCount]; for (int i = 0; i < args.Length; i++) { args[i] = frame.Data[first + i]; } object ret = Invoke(args); if (_target.ReturnType != typeof(void)) { frame.Data[first] = ret; frame.StackIndex = first + 1; } else { frame.StackIndex = first; } return 1; } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadROSoftDelete.Business.ERCLevel { /// <summary> /// F02_Continent (read only object).<br/> /// This is a generated base class of <see cref="F02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="F03_SubContinentObjects"/> of type <see cref="F03_SubContinentColl"/> (1:M relation to <see cref="F04_SubContinent"/>)<br/> /// This class is an item of <see cref="F01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class F02_Continent : ReadOnlyBase<F02_Continent> { #region ParentList Property /// <summary> /// Maintains metadata about <see cref="ParentList"/> property. /// </summary> [NotUndoable] [NonSerialized] public static readonly PropertyInfo<F01_ContinentColl> ParentListProperty = RegisterProperty<F01_ContinentColl>(p => p.ParentList); /// <summary> /// Provide access to the parent list reference for use in child object code. /// </summary> /// <value>The parent list reference.</value> public F01_ContinentColl ParentList { get { return ReadProperty(ParentListProperty); } internal set { LoadProperty(ParentListProperty, value); } } #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID", -1); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } } /// <summary> /// Maintains metadata about child <see cref="F03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<F03_Continent_Child> F03_Continent_SingleObjectProperty = RegisterProperty<F03_Continent_Child>(p => p.F03_Continent_SingleObject, "F03 Continent Single Object"); /// <summary> /// Gets the F03 Continent Single Object ("parent load" child property). /// </summary> /// <value>The F03 Continent Single Object.</value> public F03_Continent_Child F03_Continent_SingleObject { get { return GetProperty(F03_Continent_SingleObjectProperty); } private set { LoadProperty(F03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<F03_Continent_ReChild> F03_Continent_ASingleObjectProperty = RegisterProperty<F03_Continent_ReChild>(p => p.F03_Continent_ASingleObject, "F03 Continent ASingle Object"); /// <summary> /// Gets the F03 Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The F03 Continent ASingle Object.</value> public F03_Continent_ReChild F03_Continent_ASingleObject { get { return GetProperty(F03_Continent_ASingleObjectProperty); } private set { LoadProperty(F03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="F03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<F03_SubContinentColl> F03_SubContinentObjectsProperty = RegisterProperty<F03_SubContinentColl>(p => p.F03_SubContinentObjects, "F03 SubContinent Objects"); /// <summary> /// Gets the F03 Sub Continent Objects ("parent load" child property). /// </summary> /// <value>The F03 Sub Continent Objects.</value> public F03_SubContinentColl F03_SubContinentObjects { get { return GetProperty(F03_SubContinentObjectsProperty); } private set { LoadProperty(F03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="F02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F02_Continent"/> object.</returns> internal static F02_Continent GetF02_Continent(SafeDataReader dr) { F02_Continent obj = new F02_Continent(); obj.Fetch(dr); obj.LoadProperty(F03_SubContinentObjectsProperty, new F03_SubContinentColl()); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="F02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> internal void FetchChildren(SafeDataReader dr) { dr.NextResult(); while (dr.Read()) { var child = F03_Continent_Child.GetF03_Continent_Child(dr); var obj = ParentList.FindF02_ContinentByParentProperties(child.continent_ID1); obj.LoadProperty(F03_Continent_SingleObjectProperty, child); } dr.NextResult(); while (dr.Read()) { var child = F03_Continent_ReChild.GetF03_Continent_ReChild(dr); var obj = ParentList.FindF02_ContinentByParentProperties(child.continent_ID2); obj.LoadProperty(F03_Continent_ASingleObjectProperty, child); } dr.NextResult(); var f03_SubContinentColl = F03_SubContinentColl.GetF03_SubContinentColl(dr); f03_SubContinentColl.LoadItems(ParentList); dr.NextResult(); while (dr.Read()) { var child = F05_SubContinent_Child.GetF05_SubContinent_Child(dr); var obj = f03_SubContinentColl.FindF04_SubContinentByParentProperties(child.subContinent_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = F05_SubContinent_ReChild.GetF05_SubContinent_ReChild(dr); var obj = f03_SubContinentColl.FindF04_SubContinentByParentProperties(child.subContinent_ID2); obj.LoadChild(child); } dr.NextResult(); var f05_CountryColl = F05_CountryColl.GetF05_CountryColl(dr); f05_CountryColl.LoadItems(f03_SubContinentColl); dr.NextResult(); while (dr.Read()) { var child = F07_Country_Child.GetF07_Country_Child(dr); var obj = f05_CountryColl.FindF06_CountryByParentProperties(child.country_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = F07_Country_ReChild.GetF07_Country_ReChild(dr); var obj = f05_CountryColl.FindF06_CountryByParentProperties(child.country_ID2); obj.LoadChild(child); } dr.NextResult(); var f07_RegionColl = F07_RegionColl.GetF07_RegionColl(dr); f07_RegionColl.LoadItems(f05_CountryColl); dr.NextResult(); while (dr.Read()) { var child = F09_Region_Child.GetF09_Region_Child(dr); var obj = f07_RegionColl.FindF08_RegionByParentProperties(child.region_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = F09_Region_ReChild.GetF09_Region_ReChild(dr); var obj = f07_RegionColl.FindF08_RegionByParentProperties(child.region_ID2); obj.LoadChild(child); } dr.NextResult(); var f09_CityColl = F09_CityColl.GetF09_CityColl(dr); f09_CityColl.LoadItems(f07_RegionColl); dr.NextResult(); while (dr.Read()) { var child = F11_City_Child.GetF11_City_Child(dr); var obj = f09_CityColl.FindF10_CityByParentProperties(child.city_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = F11_City_ReChild.GetF11_City_ReChild(dr); var obj = f09_CityColl.FindF10_CityByParentProperties(child.city_ID2); obj.LoadChild(child); } dr.NextResult(); var f11_CityRoadColl = F11_CityRoadColl.GetF11_CityRoadColl(dr); f11_CityRoadColl.LoadItems(f09_CityColl); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Reflection.Emit; namespace System.Linq.Expressions.Interpreter { /// <summary> /// Contains compiler state corresponding to a LabelTarget /// See also LabelScopeInfo. /// </summary> internal sealed class LabelInfo { // The tree node representing this label private readonly LabelTarget _node; // The BranchLabel label, will be mutated if Node is redefined private BranchLabel _label; // The blocks where this label is defined. If it has more than one item, // the blocks can't be jumped to except from a child block // If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored // as a HashSet<LabelScopeInfo> private object _definitions; // Blocks that jump to this block private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>(); // True if at least one jump is across blocks // If we have any jump across blocks to this label, then the // LabelTarget can only be defined in one place private bool _acrossBlockJump; internal LabelInfo(LabelTarget node) { _node = node; } internal BranchLabel GetLabel(LightCompiler compiler) { EnsureLabel(compiler); return _label; } internal void Reference(LabelScopeInfo block) { _references.Add(block); if (HasDefinitions) { ValidateJump(block); } } internal void Define(LabelScopeInfo block) { // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) for (LabelScopeInfo j = block; j != null; j = j.Parent) { if (j.ContainsTarget(_node)) { Error.LabelTargetAlreadyDefined(_node.Name); } } AddDefinition(block); block.AddLabelInfo(_node, this); // Once defined, validate all jumps if (HasDefinitions && !HasMultipleDefinitions) { foreach (var r in _references) { ValidateJump(r); } } else { // Was just redefined, if we had any across block jumps, they're // now invalid if (_acrossBlockJump) { throw Error.AmbiguousJump(_node.Name); } // For local jumps, we need a new IL label // This is okay because: // 1. no across block jumps have been made or will be made // 2. we don't allow the label to be shadowed _label = null; } } private void ValidateJump(LabelScopeInfo reference) { // look for a simple jump out for (LabelScopeInfo j = reference; j != null; j = j.Parent) { if (DefinedIn(j)) { // found it, jump is valid! return; } if (j.Kind == LabelScopeKind.Finally || j.Kind == LabelScopeKind.Filter) { break; } } _acrossBlockJump = true; if (HasMultipleDefinitions) { throw Error.AmbiguousJump(_node.Name); } // We didn't find an outward jump. Look for a jump across blocks LabelScopeInfo def = FirstDefinition(); LabelScopeInfo common = CommonNode(def, reference, b => b.Parent); // Validate that we aren't jumping across a finally for (LabelScopeInfo j = reference; j != common; j = j.Parent) { if (j.Kind == LabelScopeKind.Finally) { throw Error.ControlCannotLeaveFinally(); } if (j.Kind == LabelScopeKind.Filter) { throw Error.ControlCannotLeaveFilterTest(); } } // Valdiate that we aren't jumping into a catch or an expression for (LabelScopeInfo j = def; j != common; j = j.Parent) { if (!j.CanJumpInto) { if (j.Kind == LabelScopeKind.Expression) { throw Error.ControlCannotEnterExpression(); } else { throw Error.ControlCannotEnterTry(); } } } } internal void ValidateFinish() { // Make sure that if this label was jumped to, it is also defined if (_references.Count > 0 && !HasDefinitions) { throw Error.LabelTargetUndefined(_node.Name); } } private void EnsureLabel(LightCompiler compiler) { if (_label == null) { _label = compiler.Instructions.MakeLabel(); } } private bool DefinedIn(LabelScopeInfo scope) { if (_definitions == scope) { return true; } HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>; if (definitions != null) { return definitions.Contains(scope); } return false; } private bool HasDefinitions { get { return _definitions != null; } } private LabelScopeInfo FirstDefinition() { LabelScopeInfo scope = _definitions as LabelScopeInfo; if (scope != null) { return scope; } foreach (var x in (HashSet<LabelScopeInfo>)_definitions) { return x; } throw new InvalidOperationException(); } private void AddDefinition(LabelScopeInfo scope) { if (_definitions == null) { _definitions = scope; } else { HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>; if (set == null) { _definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions }; } set.Add(scope); } } private bool HasMultipleDefinitions { get { return _definitions is HashSet<LabelScopeInfo>; } } internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class { var cmp = EqualityComparer<T>.Default; if (cmp.Equals(first, second)) { return first; } var set = new HashSet<T>(cmp); for (T t = first; t != null; t = parent(t)) { set.Add(t); } for (T t = second; t != null; t = parent(t)) { if (set.Contains(t)) { return t; } } return null; } } internal enum LabelScopeKind { // any "statement like" node that can be jumped into Statement, // these correspond to the node of the same name Block, Switch, Lambda, Try, // these correspond to the part of the try block we're in Catch, Finally, Filter, // the catch-all value for any other expression type // (means we can't jump into it) Expression, } // // Tracks scoping information for LabelTargets. Logically corresponds to a // "label scope". Even though we have arbitrary goto support, we still need // to track what kinds of nodes that gotos are jumping through, both to // emit property IL ("leave" out of a try block), and for validation, and // to allow labels to be duplicated in the tree, as long as the jumps are // considered "up only" jumps. // // We create one of these for every Expression that can be jumped into, as // well as creating them for the first expression we can't jump into. The // "Kind" property indicates what kind of scope this is. // internal sealed class LabelScopeInfo { private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block internal readonly LabelScopeKind Kind; internal readonly LabelScopeInfo Parent; internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) { Parent = parent; Kind = kind; } /// <summary> /// Returns true if we can jump into this node /// </summary> internal bool CanJumpInto { get { switch (Kind) { case LabelScopeKind.Block: case LabelScopeKind.Statement: case LabelScopeKind.Switch: case LabelScopeKind.Lambda: return true; } return false; } } internal bool ContainsTarget(LabelTarget target) { if (_labels == null) { return false; } return _labels.ContainsKey(target); } internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { if (_labels == null) { info = null; return false; } return _labels.TryGetValue(target, out info); } internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); if (_labels == null) { _labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>(); } _labels[target] = info; } } }
// <copyright file="HttpHandlerDiagnosticListener.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; using System.Globalization; using System.Net.Http; using System.Net.Sockets; using System.Reflection; using System.Runtime.Versioning; using System.Text.RegularExpressions; using System.Threading.Tasks; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Trace; namespace OpenTelemetry.Instrumentation.Http.Implementation { internal sealed class HttpHandlerDiagnosticListener : ListenerHandler { internal static readonly AssemblyName AssemblyName = typeof(HttpHandlerDiagnosticListener).Assembly.GetName(); internal static readonly string ActivitySourceName = AssemblyName.Name; internal static readonly Version Version = AssemblyName.Version; internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); private static readonly Regex CoreAppMajorVersionCheckRegex = new Regex("^\\.NETCoreApp,Version=v(\\d+)\\.", RegexOptions.Compiled | RegexOptions.IgnoreCase); private readonly PropertyFetcher<HttpRequestMessage> startRequestFetcher = new PropertyFetcher<HttpRequestMessage>("Request"); private readonly PropertyFetcher<HttpResponseMessage> stopResponseFetcher = new PropertyFetcher<HttpResponseMessage>("Response"); private readonly PropertyFetcher<Exception> stopExceptionFetcher = new PropertyFetcher<Exception>("Exception"); private readonly PropertyFetcher<TaskStatus> stopRequestStatusFetcher = new PropertyFetcher<TaskStatus>("RequestTaskStatus"); private readonly bool httpClientSupportsW3C; private readonly HttpClientInstrumentationOptions options; public HttpHandlerDiagnosticListener(HttpClientInstrumentationOptions options) : base("HttpHandlerDiagnosticListener") { var framework = Assembly .GetEntryAssembly()? .GetCustomAttribute<TargetFrameworkAttribute>()? .FrameworkName; // Depending on the .NET version/flavor this will look like // '.NETCoreApp,Version=v3.0', '.NETCoreApp,Version = v2.2' or '.NETFramework,Version = v4.7.1' if (framework != null) { var match = CoreAppMajorVersionCheckRegex.Match(framework); this.httpClientSupportsW3C = match.Success && int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture) >= 3; } this.options = options; } public override void OnStartActivity(Activity activity, object payload) { // The overall flow of what HttpClient library does is as below: // Activity.Start() // DiagnosticSource.WriteEvent("Start", payload) // DiagnosticSource.WriteEvent("Stop", payload) // Activity.Stop() // This method is in the WriteEvent("Start", payload) path. // By this time, samplers have already run and // activity.IsAllDataRequested populated accordingly. if (Sdk.SuppressInstrumentation) { return; } if (!this.startRequestFetcher.TryFetch(payload, out HttpRequestMessage request) || request == null) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnStartActivity)); return; } // TODO: Investigate why this check is needed. if (Propagators.DefaultTextMapPropagator.Extract(default, request, HttpRequestMessageContextPropagation.HeaderValuesGetter) != default) { // this request is already instrumented, we should back off activity.IsAllDataRequested = false; return; } // Propagate context irrespective of sampling decision var textMapPropagator = Propagators.DefaultTextMapPropagator; if (!(this.httpClientSupportsW3C && textMapPropagator is TraceContextPropagator)) { textMapPropagator.Inject(new PropagationContext(activity.Context, Baggage.Current), request, HttpRequestMessageContextPropagation.HeaderValueSetter); } // enrich Activity from payload only if sampling decision // is favorable. if (activity.IsAllDataRequested) { try { if (this.options.EventFilter(activity.OperationName, request) == false) { HttpInstrumentationEventSource.Log.RequestIsFilteredOut(activity.OperationName); activity.IsAllDataRequested = false; activity.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; return; } } catch (Exception ex) { HttpInstrumentationEventSource.Log.RequestFilterException(ex); activity.IsAllDataRequested = false; activity.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; return; } activity.DisplayName = HttpTagHelper.GetOperationNameForHttpMethod(request.Method); ActivityInstrumentationHelper.SetActivitySourceProperty(activity, ActivitySource); ActivityInstrumentationHelper.SetKindProperty(activity, ActivityKind.Client); activity.SetTag(SemanticConventions.AttributeHttpMethod, HttpTagHelper.GetNameForHttpMethod(request.Method)); activity.SetTag(SemanticConventions.AttributeHttpHost, HttpTagHelper.GetHostTagValueFromRequestUri(request.RequestUri)); activity.SetTag(SemanticConventions.AttributeHttpUrl, HttpTagHelper.GetUriTagValueFromRequestUri(request.RequestUri)); if (this.options.SetHttpFlavor) { activity.SetTag(SemanticConventions.AttributeHttpFlavor, HttpTagHelper.GetFlavorTagValueFromProtocolVersion(request.Version)); } try { this.options.Enrich?.Invoke(activity, "OnStartActivity", request); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } } public override void OnStopActivity(Activity activity, object payload) { if (activity.IsAllDataRequested) { // https://github.com/dotnet/runtime/blob/master/src/libraries/System.Net.Http/src/System/Net/Http/DiagnosticsHandler.cs // requestTaskStatus is not null _ = this.stopRequestStatusFetcher.TryFetch(payload, out var requestTaskStatus); StatusCode currentStatusCode = activity.GetStatus().StatusCode; if (requestTaskStatus != TaskStatus.RanToCompletion) { if (requestTaskStatus == TaskStatus.Canceled) { if (currentStatusCode == StatusCode.Unset) { activity.SetStatus(Status.Error); } } else if (requestTaskStatus != TaskStatus.Faulted) { if (currentStatusCode == StatusCode.Unset) { // Faults are handled in OnException and should already have a span.Status of Error w/ Description. activity.SetStatus(Status.Error); } } } if (this.stopResponseFetcher.TryFetch(payload, out HttpResponseMessage response) && response != null) { activity.SetTag(SemanticConventions.AttributeHttpStatusCode, (int)response.StatusCode); if (currentStatusCode == StatusCode.Unset) { activity.SetStatus(SpanHelper.ResolveSpanStatusForHttpStatusCode(activity.Kind, (int)response.StatusCode)); } try { this.options.Enrich?.Invoke(activity, "OnStopActivity", response); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } } } public override void OnException(Activity activity, object payload) { if (activity.IsAllDataRequested) { if (!this.stopExceptionFetcher.TryFetch(payload, out Exception exc) || exc == null) { HttpInstrumentationEventSource.Log.NullPayload(nameof(HttpHandlerDiagnosticListener), nameof(this.OnException)); return; } if (this.options.RecordException) { activity.RecordException(exc); } if (exc is HttpRequestException) { if (exc.InnerException is SocketException exception) { switch (exception.SocketErrorCode) { case SocketError.HostNotFound: activity.SetStatus(Status.Error.WithDescription(exc.Message)); return; } } if (exc.InnerException != null) { activity.SetStatus(Status.Error.WithDescription(exc.Message)); } } try { this.options.Enrich?.Invoke(activity, "OnException", exc); } catch (Exception ex) { HttpInstrumentationEventSource.Log.EnrichmentException(ex); } } } } }
// // RichTextViewBackend.cs // // Author: // Marek Habersack <grendel@xamarin.com> // // Copyright (c) 2013 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Xml; using System.Linq; using AppKit; using CoreGraphics; using Foundation; using ObjCRuntime; using Xwt.Backends; namespace Xwt.Mac { public class RichTextViewBackend : ViewBackend <NSTextView, IRichTextViewEventSink>, IRichTextViewBackend { NSFont font; MacRichTextBuffer currentBuffer; public override object Font { get { return base.Font; } set { var fd = value as FontData; if (fd != null) font = fd.Font; else font = null; base.Font = value; } } public RichTextViewBackend () { } public override void Initialize () { base.Initialize (); var tv = new MacTextView (EventSink, ApplicationContext); ViewObject = tv; tv.VerticallyResizable = false; tv.HorizontallyResizable = false; // Use cached font since Widget.Font size increases for each LoadText... It has to do // with the 'style' attribute for the 'body' element - not sure why that happens font = tv.Font; } double CalcHeight (double width) { var f = Widget.Frame; Widget.VerticallyResizable = true; Widget.Frame = new CGRect (Widget.Frame.X, Widget.Frame.Y, (float)width, 0); Widget.SizeToFit (); var h = Widget.Frame.Height; Widget.VerticallyResizable = false; Widget.Frame = f; return h; } public override Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { // set initial width to 0 to force text wrapping if inside ScrollView with disabled horizontal scrolling var width = (Widget.EnclosingScrollView?.HasHorizontalScroller == false) ? 0 : (double)Widget.TextStorage.Size.Width; if (widthConstraint.IsConstrained) width = widthConstraint.AvailableSize; if (minWidth != -1 && minWidth > width) width = minWidth; var height = CalcHeight (width); if (minHeight != -1 && minHeight > height) height = minHeight; return new Size (width, height); } public IRichTextBuffer CreateBuffer () { return new MacRichTextBuffer (); } public bool ReadOnly { get { return !Widget.Editable; } set { Widget.Editable = !value; } } public bool Selectable { get { return Widget.Selectable; } set { Widget.Selectable = value; // force NSTextView not to draw its (white) background // making it look like a label, which is the default Gtk/Wpf behaviour // the background color can still be set manually with the BackgroundColor property Widget.DrawsBackground = value; } } public override Drawing.Color BackgroundColor { get { return base.BackgroundColor; } set { base.BackgroundColor = value; Widget.BackgroundColor = value.ToNSColor (); } } public Drawing.Color TextColor { get { return Widget.TextColor.ToXwtColor (); } set { Widget.TextColor = value.ToNSColor (); } } int? lineSpacing = null; public int LineSpacing { get { return lineSpacing.HasValue ? (int)lineSpacing : 0; } set { lineSpacing = value; if (currentBuffer != null) Widget.SetAttributedString (currentBuffer.ToAttributedString (font, lineSpacing), !currentBuffer.HasForegroundAttributes); } } public IRichTextBuffer CurrentBuffer { get { return currentBuffer; } private set { if (currentBuffer != null) currentBuffer.Dispose (); currentBuffer = value as MacRichTextBuffer; } } public void SetBuffer (IRichTextBuffer buffer) { var macBuffer = buffer as MacRichTextBuffer; if (macBuffer == null) throw new ArgumentException ("Passed buffer is of incorrect type", "buffer"); CurrentBuffer = macBuffer; var tview = ViewObject as MacTextView; if (tview == null) return; tview.SetAttributedString (macBuffer.ToAttributedString (font, lineSpacing), !macBuffer.HasForegroundAttributes); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (!(eventId is RichTextViewEvent)) return; var tview = ViewObject as MacTextView; if (tview == null) return; tview.EnableEvent ((RichTextViewEvent)eventId); } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (!(eventId is RichTextViewEvent)) return; var tview = ViewObject as MacTextView; if (tview == null) return; tview.DisableEvent ((RichTextViewEvent)eventId); } protected override void Dispose (bool disposing) { if (currentBuffer != null) currentBuffer.Dispose (); base.Dispose (disposing); } } class MacTextView : NSTextView, IViewObject { IRichTextViewEventSink eventSink; ApplicationContext context; public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public MacTextView (NativeHandle p) : base (p) { CommonInit (); } public MacTextView (IRichTextViewEventSink eventSink, ApplicationContext context) { CommonInit (); this.eventSink = eventSink; this.context = context; EnableEvent (RichTextViewEvent.NavigateToUrl); } public void EnableEvent (RichTextViewEvent ev) { if (ev != RichTextViewEvent.NavigateToUrl) return; LinkClicked = TextLinkClicked; } public void DisableEvent (RichTextViewEvent ev) { if (ev != RichTextViewEvent.NavigateToUrl) return; LinkClicked = null; } bool TextLinkClicked (NSTextView textView, NSObject link, nuint charIndex) { if (eventSink == null || context == null) return false; string linkUrl; if (link is NSString) linkUrl = (link as NSString); else if (link is NSUrl) linkUrl = (link as NSUrl).AbsoluteString; else linkUrl = null; Uri url = null; if (String.IsNullOrWhiteSpace (linkUrl) || !Uri.TryCreate (linkUrl, UriKind.RelativeOrAbsolute, out url)) url = null; context.InvokeUserCode (delegate { eventSink.OnNavigateToUrl (url); }); return true; } public override void ViewDidMoveToWindow () { base.ViewDidMoveToWindow (); if (MacSystemInformation.OsVersion < MacSystemInformation.Mavericks) return; // FIXME: the NSAppearance does not define a color for links, // this may change in the future, but for now use the fallback color if (Window?.EffectiveAppearance?.Name == NSAppearance.NameVibrantDark) { var ns = new NSMutableDictionary (LinkTextAttributes); ns [NSStringAttributeKey.ForegroundColor] = Backend.Frontend.Surface.ToolkitEngine.Defaults.FallbackLinkColor.ToNSColor (); LinkTextAttributes = ns; } } public override void MouseUp (NSEvent theEvent) { if (!Selectable) { var uri = GetLinkAtPos (theEvent); string linkUrl = uri?.AbsoluteString ?? null; if (!string.IsNullOrEmpty (linkUrl)) { Uri url = null; if (string.IsNullOrWhiteSpace (linkUrl) || !Uri.TryCreate (linkUrl, UriKind.RelativeOrAbsolute, out url)) url = null; context.InvokeUserCode (delegate { eventSink.OnNavigateToUrl (url); }); } } base.MouseUp (theEvent); } NSUrl GetLinkAtPos (NSEvent theEvent) { var i = GetCharacterIndex (Window.ConvertRectToScreen (new CGRect (theEvent.LocationInWindow, CGSize.Empty)).Location); if (i >= 0) { NSRange r; var attr = TextStorage.GetAttribute (NSStringAttributeKey.Link, (nint)i, out r) as NSUrl; if (attr != null && r.Length > 0) return attr; } return null; } public override void ResetCursorRects () { base.ResetCursorRects (); // NSTextView sets the link cursors only in selectable mode // Do the same when Selectable == false if (!Selectable && TextStorage?.Length > 0) { TextStorage.EnumerateAttributes (new NSRange (0, TextStorage.Length), NSAttributedStringEnumeration.None, (NSDictionary attrs, NSRange range, ref bool stop) => { stop = false; if (attrs.ContainsKey (NSStringAttributeKey.Link)) { var rects = GetRects (range); for (nuint i = 0; i < rects.Count; i++) AddCursorRect (rects.GetItem<NSValue> (i).CGRectValue, NSCursor.PointingHandCursor); } }); } } void CommonInit () { Editable = false; } } class MacRichTextBuffer : IRichTextBuffer, IDisposable { const int HeaderIncrement = 8; static readonly string[] lineSplitChars = new string[] { Environment.NewLine }; static readonly IntPtr selInitWithHTMLDocumentAttributes_Handle = Selector.GetHandle ("initWithHTML:documentAttributes:"); readonly StringBuilder text; readonly XmlWriter xmlWriter; Stack <int> paragraphIndent; /// <summary> /// Used to identify whether we can safely update TextView's TextColor. /// Otherwise such update can override all custom ForegroundColor attributes. /// </summary> /// <value></value> public bool HasForegroundAttributes { get; private set; } public MacRichTextBuffer () { text = new StringBuilder (); xmlWriter = XmlWriter.Create (text, new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t", ConformanceLevel = ConformanceLevel.Fragment }); } public NSAttributedString ToAttributedString (NSFont font, int? lineSpacing) { xmlWriter.Flush (); var finaltext = new StringBuilder (); var finalxmlWriter = XmlWriter.Create (finaltext, new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = "\t" }); float fontSize; string fontFamily; if (font != null) { fontSize = (float) font.PointSize; fontFamily = font.FontName; } else { fontSize = 16; fontFamily = "sans-serif"; } finalxmlWriter.WriteDocType ("html", "-//W3C//DTD XHTML 1.0", "Strict//EN", null); finalxmlWriter.WriteStartElement ("html"); finalxmlWriter.WriteStartElement ("meta"); finalxmlWriter.WriteAttributeString ("http-equiv", "Content-Type"); finalxmlWriter.WriteAttributeString ("content", "text/html; charset=utf-8"); finalxmlWriter.WriteEndElement (); finalxmlWriter.WriteStartElement ("body"); string style = String.Format ("font-family: {0}; font-size: {1}", fontFamily, fontSize); if (lineSpacing.HasValue) style += "; line-height: " + (lineSpacing.Value + fontSize) + "px"; finalxmlWriter.WriteAttributeString ("style", style); finalxmlWriter.WriteRaw (text.ToString ()); finalxmlWriter.WriteEndElement (); // body finalxmlWriter.WriteEndElement (); // html finalxmlWriter.Flush (); if (finaltext == null || finaltext.Length == 0) return new NSAttributedString (String.Empty); NSDictionary docAttributes; try { return CreateStringFromHTML (finaltext.ToString (), out docAttributes); } finally { finaltext = null; ((IDisposable)finalxmlWriter).Dispose (); finalxmlWriter = null; docAttributes = null; } } NSAttributedString CreateStringFromHTML (string html, out NSDictionary docAttributes) { var data = NSData.FromString (html); IntPtr docAttributesPtr = Marshal.AllocHGlobal (4); Marshal.WriteInt32 (docAttributesPtr, 0); var attrString = new NSAttributedString (); attrString.Handle = Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr (attrString.Handle, selInitWithHTMLDocumentAttributes_Handle, data.Handle, docAttributesPtr); IntPtr docAttributesValue = Marshal.ReadIntPtr (docAttributesPtr); docAttributes = docAttributesValue != IntPtr.Zero ? Runtime.GetNSObject (docAttributesValue) as NSDictionary : null; Marshal.FreeHGlobal (docAttributesPtr); return attrString; } public string PlainText { get { return text.ToString (); } } public void EmitText (string text, RichTextInlineStyle style) { if (String.IsNullOrEmpty (text)) return; bool haveStyle = true; switch (style) { case RichTextInlineStyle.Bold: xmlWriter.WriteStartElement ("strong"); break; case RichTextInlineStyle.Italic: xmlWriter.WriteStartElement ("em"); break; case RichTextInlineStyle.Monospace: xmlWriter.WriteStartElement ("tt"); break; default: haveStyle = false; break; } bool first = true; foreach (string line in text.Split (lineSplitChars, StringSplitOptions.None)) { if (!first) { xmlWriter.WriteStartElement ("br"); xmlWriter.WriteEndElement (); } else first = false; xmlWriter.WriteString (line); } if (haveStyle) xmlWriter.WriteEndElement (); } public void EmitText (FormattedText text) { if (text.Attributes.Count == 0) { EmitText (text.Text, RichTextInlineStyle.Normal); return; } var s = text.ToAttributedString (); var options = new NSAttributedStringDocumentAttributes (); options.DocumentType = NSDocumentType.HTML; var exclude = NSArray.FromObjects (new [] { "doctype", "html", "head", "meta", "xml", "body", "p" }); options.Dictionary [NSExcludedElementsDocumentAttribute] = exclude; NSError err; var d = s.GetData (new NSRange (0, s.Length), options, out err); var str = (string)NSString.FromData (d, NSStringEncoding.UTF8); //bool first = true; foreach (string line in str.Split (lineSplitChars, StringSplitOptions.None)) { //if (!first) { // xmlWriter.WriteStartElement ("br"); // xmlWriter.WriteEndElement (); //} else // first = false; xmlWriter.WriteRaw (line); } HasForegroundAttributes |= text.Attributes.Any (a => a is Xwt.Drawing.ColorTextAttribute); } private static readonly IntPtr _AppKitHandle = Dlfcn.dlopen ("/System/Library/Frameworks/AppKit.framework/AppKit", 0); private static NSString _NSExcludedElementsDocumentAttribute; private static NSString NSExcludedElementsDocumentAttribute { get { if (_NSExcludedElementsDocumentAttribute == null) { _NSExcludedElementsDocumentAttribute = Dlfcn.GetStringConstant (_AppKitHandle, "NSExcludedElementsDocumentAttribute"); } return _NSExcludedElementsDocumentAttribute; } } public void EmitStartHeader (int level) { if (level < 1) level = 1; if (level > 6) level = 6; xmlWriter.WriteStartElement ("h" + level); } public void EmitEndHeader () { xmlWriter.WriteEndElement (); } public void EmitStartParagraph (int indentLevel) { if (paragraphIndent == null) paragraphIndent = new Stack<int> (); paragraphIndent.Push (indentLevel); // FIXME: perhaps use CSS indent? for (int i = 0; i < indentLevel; i++) xmlWriter.WriteStartElement ("blockindent"); xmlWriter.WriteStartElement ("p"); } public void EmitEndParagraph () { xmlWriter.WriteEndElement (); // </p> int indentLevel; if (paragraphIndent != null && paragraphIndent.Count > 0) indentLevel = paragraphIndent.Pop (); else indentLevel = 0; for (int i = 0; i < indentLevel; i++) xmlWriter.WriteEndElement (); // </blockindent> } public void EmitOpenList () { xmlWriter.WriteStartElement ("ul"); } public void EmitOpenBullet () { xmlWriter.WriteStartElement ("li"); } public void EmitCloseBullet () { xmlWriter.WriteEndElement (); } public void EmitCloseList () { xmlWriter.WriteEndElement (); } public void EmitStartLink (string href, string title) { xmlWriter.WriteStartElement ("a"); xmlWriter.WriteAttributeString ("href", href); // FIXME: it appears NSTextView ignores 'title' when it's told to display // link tooltips - it will use the URL instead. See if there's a way to make // it show the actual title xmlWriter.WriteAttributeString ("title", title); } public void EmitEndLink () { xmlWriter.WriteEndElement (); } public void EmitCodeBlock (string code) { xmlWriter.WriteStartElement ("pre"); xmlWriter.WriteString (code); xmlWriter.WriteEndElement (); } public void EmitHorizontalRuler () { xmlWriter.WriteStartElement ("hr"); xmlWriter.WriteEndElement (); } public void Dispose () { ((IDisposable)xmlWriter).Dispose (); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.TimerJobs.Samples.ExpandJob { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System { // The class designed as to keep minimal the working set of Uri class. // The idea is to stay with static helper methods and strings internal static partial class IPv6AddressHelper { // methods internal static unsafe string ParseCanonicalName(string str, int start, ref bool isLoopback, ref string? scopeId) { Span<ushort> numbers = stackalloc ushort[NumberOfLabels]; numbers.Clear(); Parse(str, numbers, start, ref scopeId); isLoopback = IsLoopback(numbers); // RFC 5952 Sections 4 & 5 - Compressed, lower case, with possible embedded IPv4 addresses. // Start to finish, inclusive. <-1, -1> for no compression (int rangeStart, int rangeEnd) = FindCompressionRange(numbers); bool ipv4Embedded = ShouldHaveIpv4Embedded(numbers); Span<char> stackSpace = stackalloc char[48]; // large enough for any IPv6 string, including brackets stackSpace[0] = '['; int pos = 1; int charsWritten; bool success; for (int i = 0; i < NumberOfLabels; i++) { if (ipv4Embedded && i == (NumberOfLabels - 2)) { stackSpace[pos++] = ':'; // Write the remaining digits as an IPv4 address success = (numbers[i] >> 8).TryFormat(stackSpace.Slice(pos), out charsWritten); Debug.Assert(success); pos += charsWritten; stackSpace[pos++] = '.'; success = (numbers[i] & 0xFF).TryFormat(stackSpace.Slice(pos), out charsWritten); Debug.Assert(success); pos += charsWritten; stackSpace[pos++] = '.'; success = (numbers[i + 1] >> 8).TryFormat(stackSpace.Slice(pos), out charsWritten); Debug.Assert(success); pos += charsWritten; stackSpace[pos++] = '.'; success = (numbers[i + 1] & 0xFF).TryFormat(stackSpace.Slice(pos), out charsWritten); Debug.Assert(success); pos += charsWritten; break; } // Compression; 1::1, ::1, 1:: if (rangeStart == i) { // Start compression, add : stackSpace[pos++] = ':'; } if (rangeStart <= i && rangeEnd == NumberOfLabels) { // Remainder compressed; 1:: stackSpace[pos++] = ':'; break; } if (rangeStart <= i && i < rangeEnd) { continue; // Compressed } if (i != 0) { stackSpace[pos++] = ':'; } success = numbers[i].TryFormat(stackSpace.Slice(pos), out charsWritten, format: "x"); Debug.Assert(success); pos += charsWritten; } stackSpace[pos++] = ']'; return new string(stackSpace.Slice(0, pos)); } private static unsafe bool IsLoopback(ReadOnlySpan<ushort> numbers) { // // is the address loopback? Loopback is defined as one of: // // 0:0:0:0:0:0:0:1 // 0:0:0:0:0:0:127.0.0.1 == 0:0:0:0:0:0:7F00:0001 // 0:0:0:0:0:FFFF:127.0.0.1 == 0:0:0:0:0:FFFF:7F00:0001 // return ((numbers[0] == 0) && (numbers[1] == 0) && (numbers[2] == 0) && (numbers[3] == 0) && (numbers[4] == 0)) && (((numbers[5] == 0) && (numbers[6] == 0) && (numbers[7] == 1)) || (((numbers[6] == 0x7F00) && (numbers[7] == 0x0001)) && ((numbers[5] == 0) || (numbers[5] == 0xFFFF)))); } // // InternalIsValid // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * an optional (last) 1 or 2 character prefix length field delimited by '/' // * the last 32 bits in an address can be represented as an IPv4 address // // Inputs: // <argument> name // Domain name field of a URI to check for pattern match with // IPv6 address // validateStrictAddress: if set to true, it expects strict ipv6 address. Otherwise it expects // part of the string in ipv6 format. // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> has IPv6 format/ipv6 address based on validateStrictAddress, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported private static unsafe bool InternalIsValid(char* name, int start, ref int end, bool validateStrictAddress) { int sequenceCount = 0; int sequenceLength = 0; bool haveCompressor = false; bool haveIPv4Address = false; bool havePrefix = false; bool expectingNumber = true; int lastSequence = 1; // Starting with a colon character is only valid if another colon follows. if (name[start] == ':' && (start + 1 >= end || name[start + 1] != ':')) { return false; } int i; for (i = start; i < end; ++i) { if (havePrefix ? (name[i] >= '0' && name[i] <= '9') : Uri.IsHexDigit(name[i])) { ++sequenceLength; expectingNumber = false; } else { if (sequenceLength > 4) { return false; } if (sequenceLength != 0) { ++sequenceCount; lastSequence = i - sequenceLength; } switch (name[i]) { case '%': while (true) { //accept anything in scopeID if (++i == end) { // no closing ']', fail return false; } if (name[i] == ']') { goto case ']'; } else if (name[i] == '/') { goto case '/'; } } case ']': start = i; i = end; //this will make i = end+1 continue; case ':': if ((i > 0) && (name[i - 1] == ':')) { if (haveCompressor) { // // can only have one per IPv6 address // return false; } haveCompressor = true; expectingNumber = false; } else { expectingNumber = true; } break; case '/': if (validateStrictAddress) { return false; } if ((sequenceCount == 0) || havePrefix) { return false; } havePrefix = true; expectingNumber = true; break; case '.': if (haveIPv4Address) { return false; } i = end; if (!IPv4AddressHelper.IsValid(name, lastSequence, ref i, true, false, false)) { return false; } // ipv4 address takes 2 slots in ipv6 address, one was just counted meeting the '.' ++sequenceCount; haveIPv4Address = true; --i; // it will be incremented back on the next loop break; default: return false; } sequenceLength = 0; } } // // if the last token was a prefix, check number of digits // if (havePrefix && ((sequenceLength < 1) || (sequenceLength > 2))) { return false; } // // these sequence counts are -1 because it is implied in end-of-sequence // int expectedSequenceCount = 8 + (havePrefix ? 1 : 0); if (!expectingNumber && (sequenceLength <= 4) && (haveCompressor ? (sequenceCount < expectedSequenceCount) : (sequenceCount == expectedSequenceCount))) { if (i == end + 1) { // ']' was found end = start + 1; return true; } return false; } return false; } // // IsValid // // Determine whether a name is a valid IPv6 address. Rules are: // // * 8 groups of 16-bit hex numbers, separated by ':' // * a *single* run of zeros can be compressed using the symbol '::' // * an optional string of a ScopeID delimited by '%' // * an optional (last) 1 or 2 character prefix length field delimited by '/' // * the last 32 bits in an address can be represented as an IPv4 address // // Inputs: // <argument> name // Domain name field of a URI to check for pattern match with // IPv6 address // // Outputs: // Nothing // // Assumes: // the correct name is terminated by ']' character // // Returns: // true if <name> has IPv6 format, else false // // Throws: // Nothing // // Remarks: MUST NOT be used unless all input indexes are verified and trusted. // start must be next to '[' position, or error is reported internal static unsafe bool IsValid(char* name, int start, ref int end) { return InternalIsValid(name, start, ref end, false); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ProjectTracker.AppServerHost.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // 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.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Internal.Resources.Models; namespace Microsoft.Azure.Management.Internal.Resources { public static partial class ProviderOperationsExtensions { /// <summary> /// Gets a resource provider. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider information. /// </returns> public static ProviderGetResult Get(this IProviderOperations operations, string resourceProviderNamespace) { return Task.Factory.StartNew((object s) => { return ((IProviderOperations)s).GetAsync(resourceProviderNamespace); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a resource provider. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider information. /// </returns> public static Task<ProviderGetResult> GetAsync(this IProviderOperations operations, string resourceProviderNamespace) { return operations.GetAsync(resourceProviderNamespace, CancellationToken.None); } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <returns> /// List of resource providers. /// </returns> public static ProviderListResult List(this IProviderOperations operations, ProviderListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IProviderOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of resource providers. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <returns> /// List of resource providers. /// </returns> public static Task<ProviderListResult> ListAsync(this IProviderOperations operations, ProviderListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource providers. /// </returns> public static ProviderListResult ListNext(this IProviderOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IProviderOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource providers. /// </returns> public static Task<ProviderListResult> ListNextAsync(this IProviderOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Registers provider to be used with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public static ProviderRegistionResult Register(this IProviderOperations operations, string resourceProviderNamespace) { return Task.Factory.StartNew((object s) => { return ((IProviderOperations)s).RegisterAsync(resourceProviderNamespace); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Registers provider to be used with a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public static Task<ProviderRegistionResult> RegisterAsync(this IProviderOperations operations, string resourceProviderNamespace) { return operations.RegisterAsync(resourceProviderNamespace, CancellationToken.None); } /// <summary> /// Unregisters provider from a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public static ProviderUnregistionResult Unregister(this IProviderOperations operations, string resourceProviderNamespace) { return Task.Factory.StartNew((object s) => { return ((IProviderOperations)s).UnregisterAsync(resourceProviderNamespace); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unregisters provider from a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Internal.Resources.IProviderOperations. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <returns> /// Resource provider registration information. /// </returns> public static Task<ProviderUnregistionResult> UnregisterAsync(this IProviderOperations operations, string resourceProviderNamespace) { return operations.UnregisterAsync(resourceProviderNamespace, CancellationToken.None); } } }
//--------------------------------------------------------------------- // This file is part of the CLR Managed Debugger (mdbg) Sample. // // Copyright (C) Microsoft Corporation. All rights reserved. //--------------------------------------------------------------------- // generated file; DO NOT MODIFY using System; namespace Microsoft.Samples.Tools.Mdbg.Extension { public enum ILOpCode { CEE_NOP=0, CEE_BREAK=1, CEE_LDARG_0=2, CEE_LDARG_1=3, CEE_LDARG_2=4, CEE_LDARG_3=5, CEE_LDLOC_0=6, CEE_LDLOC_1=7, CEE_LDLOC_2=8, CEE_LDLOC_3=9, CEE_STLOC_0=10, CEE_STLOC_1=11, CEE_STLOC_2=12, CEE_STLOC_3=13, CEE_LDARG_S=14, CEE_LDARGA_S=15, CEE_STARG_S=16, CEE_LDLOC_S=17, CEE_LDLOCA_S=18, CEE_STLOC_S=19, CEE_LDNULL=20, CEE_LDC_I4_M1=21, CEE_LDC_I4_0=22, CEE_LDC_I4_1=23, CEE_LDC_I4_2=24, CEE_LDC_I4_3=25, CEE_LDC_I4_4=26, CEE_LDC_I4_5=27, CEE_LDC_I4_6=28, CEE_LDC_I4_7=29, CEE_LDC_I4_8=30, CEE_LDC_I4_S=31, CEE_LDC_I4=32, CEE_LDC_I8=33, CEE_LDC_R4=34, CEE_LDC_R8=35, CEE_UNUSED49=36, CEE_DUP=37, CEE_POP=38, CEE_JMP=39, CEE_CALL=40, CEE_CALLI=41, CEE_RET=42, CEE_BR_S=43, CEE_BRFALSE_S=44, CEE_BRTRUE_S=45, CEE_BEQ_S=46, CEE_BGE_S=47, CEE_BGT_S=48, CEE_BLE_S=49, CEE_BLT_S=50, CEE_BNE_UN_S=51, CEE_BGE_UN_S=52, CEE_BGT_UN_S=53, CEE_BLE_UN_S=54, CEE_BLT_UN_S=55, CEE_BR=56, CEE_BRFALSE=57, CEE_BRTRUE=58, CEE_BEQ=59, CEE_BGE=60, CEE_BGT=61, CEE_BLE=62, CEE_BLT=63, CEE_BNE_UN=64, CEE_BGE_UN=65, CEE_BGT_UN=66, CEE_BLE_UN=67, CEE_BLT_UN=68, CEE_SWITCH=69, CEE_LDIND_I1=70, CEE_LDIND_U1=71, CEE_LDIND_I2=72, CEE_LDIND_U2=73, CEE_LDIND_I4=74, CEE_LDIND_U4=75, CEE_LDIND_I8=76, CEE_LDIND_I=77, CEE_LDIND_R4=78, CEE_LDIND_R8=79, CEE_LDIND_REF=80, CEE_STIND_REF=81, CEE_STIND_I1=82, CEE_STIND_I2=83, CEE_STIND_I4=84, CEE_STIND_I8=85, CEE_STIND_R4=86, CEE_STIND_R8=87, CEE_ADD=88, CEE_SUB=89, CEE_MUL=90, CEE_DIV=91, CEE_DIV_UN=92, CEE_REM=93, CEE_REM_UN=94, CEE_AND=95, CEE_OR=96, CEE_XOR=97, CEE_SHL=98, CEE_SHR=99, CEE_SHR_UN=100, CEE_NEG=101, CEE_NOT=102, CEE_CONV_I1=103, CEE_CONV_I2=104, CEE_CONV_I4=105, CEE_CONV_I8=106, CEE_CONV_R4=107, CEE_CONV_R8=108, CEE_CONV_U4=109, CEE_CONV_U8=110, CEE_CALLVIRT=111, CEE_CPOBJ=112, CEE_LDOBJ=113, CEE_LDSTR=114, CEE_NEWOBJ=115, CEE_CASTCLASS=116, CEE_ISINST=117, CEE_CONV_R_UN=118, CEE_UNUSED58=119, CEE_UNUSED1=120, CEE_UNBOX=121, CEE_THROW=122, CEE_LDFLD=123, CEE_LDFLDA=124, CEE_STFLD=125, CEE_LDSFLD=126, CEE_LDSFLDA=127, CEE_STSFLD=128, CEE_STOBJ=129, CEE_CONV_OVF_I1_UN=130, CEE_CONV_OVF_I2_UN=131, CEE_CONV_OVF_I4_UN=132, CEE_CONV_OVF_I8_UN=133, CEE_CONV_OVF_U1_UN=134, CEE_CONV_OVF_U2_UN=135, CEE_CONV_OVF_U4_UN=136, CEE_CONV_OVF_U8_UN=137, CEE_CONV_OVF_I_UN=138, CEE_CONV_OVF_U_UN=139, CEE_BOX=140, CEE_NEWARR=141, CEE_LDLEN=142, CEE_LDELEMA=143, CEE_LDELEM_I1=144, CEE_LDELEM_U1=145, CEE_LDELEM_I2=146, CEE_LDELEM_U2=147, CEE_LDELEM_I4=148, CEE_LDELEM_U4=149, CEE_LDELEM_I8=150, CEE_LDELEM_I=151, CEE_LDELEM_R4=152, CEE_LDELEM_R8=153, CEE_LDELEM_REF=154, CEE_STELEM_I=155, CEE_STELEM_I1=156, CEE_STELEM_I2=157, CEE_STELEM_I4=158, CEE_STELEM_I8=159, CEE_STELEM_R4=160, CEE_STELEM_R8=161, CEE_STELEM_REF=162, CEE_UNUSED2=163, CEE_UNUSED3=164, CEE_UNUSED4=165, CEE_UNUSED5=166, CEE_UNUSED6=167, CEE_UNUSED7=168, CEE_UNUSED8=169, CEE_UNUSED9=170, CEE_UNUSED10=171, CEE_UNUSED11=172, CEE_UNUSED12=173, CEE_UNUSED13=174, CEE_UNUSED14=175, CEE_UNUSED15=176, CEE_UNUSED16=177, CEE_UNUSED17=178, CEE_CONV_OVF_I1=179, CEE_CONV_OVF_U1=180, CEE_CONV_OVF_I2=181, CEE_CONV_OVF_U2=182, CEE_CONV_OVF_I4=183, CEE_CONV_OVF_U4=184, CEE_CONV_OVF_I8=185, CEE_CONV_OVF_U8=186, CEE_UNUSED50=187, CEE_UNUSED18=188, CEE_UNUSED19=189, CEE_UNUSED20=190, CEE_UNUSED21=191, CEE_UNUSED22=192, CEE_UNUSED23=193, CEE_REFANYVAL=194, CEE_CKFINITE=195, CEE_UNUSED24=196, CEE_UNUSED25=197, CEE_MKREFANY=198, CEE_UNUSED59=199, CEE_UNUSED60=200, CEE_UNUSED61=201, CEE_UNUSED62=202, CEE_UNUSED63=203, CEE_UNUSED64=204, CEE_UNUSED65=205, CEE_UNUSED66=206, CEE_UNUSED67=207, CEE_LDTOKEN=208, CEE_CONV_U2=209, CEE_CONV_U1=210, CEE_CONV_I=211, CEE_CONV_OVF_I=212, CEE_CONV_OVF_U=213, CEE_ADD_OVF=214, CEE_ADD_OVF_UN=215, CEE_MUL_OVF=216, CEE_MUL_OVF_UN=217, CEE_SUB_OVF=218, CEE_SUB_OVF_UN=219, CEE_ENDFINALLY=220, CEE_LEAVE=221, CEE_LEAVE_S=222, CEE_STIND_I=223, CEE_CONV_U=224, CEE_UNUSED26=225, CEE_UNUSED27=226, CEE_UNUSED28=227, CEE_UNUSED29=228, CEE_UNUSED30=229, CEE_UNUSED31=230, CEE_UNUSED32=231, CEE_UNUSED33=232, CEE_UNUSED34=233, CEE_UNUSED35=234, CEE_UNUSED36=235, CEE_UNUSED37=236, CEE_UNUSED38=237, CEE_UNUSED39=238, CEE_UNUSED40=239, CEE_UNUSED41=240, CEE_UNUSED42=241, CEE_UNUSED43=242, CEE_UNUSED44=243, CEE_UNUSED45=244, CEE_UNUSED46=245, CEE_UNUSED47=246, CEE_UNUSED48=247, CEE_PREFIX7=248, CEE_PREFIX6=249, CEE_PREFIX5=250, CEE_PREFIX4=251, CEE_PREFIX3=252, CEE_PREFIX2=253, CEE_PREFIX1=254, CEE_PREFIXREF=255, CEE_ARGLIST=256, CEE_CEQ=257, CEE_CGT=258, CEE_CGT_UN=259, CEE_CLT=260, CEE_CLT_UN=261, CEE_LDFTN=262, CEE_LDVIRTFTN=263, CEE_UNUSED56=264, CEE_LDARG=265, CEE_LDARGA=266, CEE_STARG=267, CEE_LDLOC=268, CEE_LDLOCA=269, CEE_STLOC=270, CEE_LOCALLOC=271, CEE_UNUSED57=272, CEE_ENDFILTER=273, CEE_UNALIGNED=274, CEE_VOLATILE=275, CEE_TAILCALL=276, CEE_INITOBJ=277, CEE_UNUSED68=278, CEE_CPBLK=279, CEE_INITBLK=280, CEE_UNUSED69=281, CEE_RETHROW=282, CEE_UNUSED51=283, CEE_SIZEOF=284, CEE_REFANYTYPE=285, CEE_UNUSED52=286, CEE_UNUSED53=287, CEE_UNUSED54=288, CEE_UNUSED55=289, CEE_UNUSED70=290, CEE_ILLEGAL=291, CEE_MACRO_END=292, CEE_COUNT=293 } public class GenTables { public static OpCodeTypeInfo[] opCodeTypeInfo = new OpCodeTypeInfo[] { new OpCodeTypeInfo("nop",0,1,255,0), new OpCodeTypeInfo("break",0,1,255,1), new OpCodeTypeInfo("ldarg.0",0,1,255,2), new OpCodeTypeInfo("ldarg.1",0,1,255,3), new OpCodeTypeInfo("ldarg.2",0,1,255,4), new OpCodeTypeInfo("ldarg.3",0,1,255,5), new OpCodeTypeInfo("ldloc.0",0,1,255,6), new OpCodeTypeInfo("ldloc.1",0,1,255,7), new OpCodeTypeInfo("ldloc.2",0,1,255,8), new OpCodeTypeInfo("ldloc.3",0,1,255,9), new OpCodeTypeInfo("stloc.0",0,1,255,10), new OpCodeTypeInfo("stloc.1",0,1,255,11), new OpCodeTypeInfo("stloc.2",0,1,255,12), new OpCodeTypeInfo("stloc.3",0,1,255,13), new OpCodeTypeInfo("ldarg.s",17,1,255,14), new OpCodeTypeInfo("ldarga.s",17,1,255,15), new OpCodeTypeInfo("starg.s",17,1,255,16), new OpCodeTypeInfo("ldloc.s",17,1,255,17), new OpCodeTypeInfo("ldloca.s",17,1,255,18), new OpCodeTypeInfo("stloc.s",17,1,255,19), new OpCodeTypeInfo("ldnull",0,1,255,20), new OpCodeTypeInfo("ldc.i4.m1",0,1,255,21), new OpCodeTypeInfo("ldc.i4.0",0,1,255,22), new OpCodeTypeInfo("ldc.i4.1",0,1,255,23), new OpCodeTypeInfo("ldc.i4.2",0,1,255,24), new OpCodeTypeInfo("ldc.i4.3",0,1,255,25), new OpCodeTypeInfo("ldc.i4.4",0,1,255,26), new OpCodeTypeInfo("ldc.i4.5",0,1,255,27), new OpCodeTypeInfo("ldc.i4.6",0,1,255,28), new OpCodeTypeInfo("ldc.i4.7",0,1,255,29), new OpCodeTypeInfo("ldc.i4.8",0,1,255,30), new OpCodeTypeInfo("ldc.i4.s",18,1,255,31), new OpCodeTypeInfo("ldc.i4",2,1,255,32), new OpCodeTypeInfo("ldc.i8",5,1,255,33), new OpCodeTypeInfo("ldc.r4",19,1,255,34), new OpCodeTypeInfo("ldc.r8",3,1,255,35), new OpCodeTypeInfo("unused",0,1,255,36), new OpCodeTypeInfo("dup",0,1,255,37), new OpCodeTypeInfo("pop",0,1,255,38), new OpCodeTypeInfo("jmp",6,1,255,39), new OpCodeTypeInfo("call",6,1,255,40), new OpCodeTypeInfo("calli",10,1,255,41), new OpCodeTypeInfo("ret",0,1,255,42), new OpCodeTypeInfo("br.s",20,1,255,43), new OpCodeTypeInfo("brfalse.s",20,1,255,44), new OpCodeTypeInfo("brtrue.s",20,1,255,45), new OpCodeTypeInfo("beq.s",20,1,255,46), new OpCodeTypeInfo("bge.s",20,1,255,47), new OpCodeTypeInfo("bgt.s",20,1,255,48), new OpCodeTypeInfo("ble.s",20,1,255,49), new OpCodeTypeInfo("blt.s",20,1,255,50), new OpCodeTypeInfo("bne.un.s",20,1,255,51), new OpCodeTypeInfo("bge.un.s",20,1,255,52), new OpCodeTypeInfo("bgt.un.s",20,1,255,53), new OpCodeTypeInfo("ble.un.s",20,1,255,54), new OpCodeTypeInfo("blt.un.s",20,1,255,55), new OpCodeTypeInfo("br",4,1,255,56), new OpCodeTypeInfo("brfalse",4,1,255,57), new OpCodeTypeInfo("brtrue",4,1,255,58), new OpCodeTypeInfo("beq",4,1,255,59), new OpCodeTypeInfo("bge",4,1,255,60), new OpCodeTypeInfo("bgt",4,1,255,61), new OpCodeTypeInfo("ble",4,1,255,62), new OpCodeTypeInfo("blt",4,1,255,63), new OpCodeTypeInfo("bne.un",4,1,255,64), new OpCodeTypeInfo("bge.un",4,1,255,65), new OpCodeTypeInfo("bgt.un",4,1,255,66), new OpCodeTypeInfo("ble.un",4,1,255,67), new OpCodeTypeInfo("blt.un",4,1,255,68), new OpCodeTypeInfo("switch",13,1,255,69), new OpCodeTypeInfo("ldind.i1",0,1,255,70), new OpCodeTypeInfo("ldind.u1",0,1,255,71), new OpCodeTypeInfo("ldind.i2",0,1,255,72), new OpCodeTypeInfo("ldind.u2",0,1,255,73), new OpCodeTypeInfo("ldind.i4",0,1,255,74), new OpCodeTypeInfo("ldind.u4",0,1,255,75), new OpCodeTypeInfo("ldind.i8",0,1,255,76), new OpCodeTypeInfo("ldind.i",0,1,255,77), new OpCodeTypeInfo("ldind.r4",0,1,255,78), new OpCodeTypeInfo("ldind.r8",0,1,255,79), new OpCodeTypeInfo("ldind.ref",0,1,255,80), new OpCodeTypeInfo("stind.ref",0,1,255,81), new OpCodeTypeInfo("stind.i1",0,1,255,82), new OpCodeTypeInfo("stind.i2",0,1,255,83), new OpCodeTypeInfo("stind.i4",0,1,255,84), new OpCodeTypeInfo("stind.i8",0,1,255,85), new OpCodeTypeInfo("stind.r4",0,1,255,86), new OpCodeTypeInfo("stind.r8",0,1,255,87), new OpCodeTypeInfo("add",0,1,255,88), new OpCodeTypeInfo("sub",0,1,255,89), new OpCodeTypeInfo("mul",0,1,255,90), new OpCodeTypeInfo("div",0,1,255,91), new OpCodeTypeInfo("div.un",0,1,255,92), new OpCodeTypeInfo("rem",0,1,255,93), new OpCodeTypeInfo("rem.un",0,1,255,94), new OpCodeTypeInfo("and",0,1,255,95), new OpCodeTypeInfo("or",0,1,255,96), new OpCodeTypeInfo("xor",0,1,255,97), new OpCodeTypeInfo("shl",0,1,255,98), new OpCodeTypeInfo("shr",0,1,255,99), new OpCodeTypeInfo("shr.un",0,1,255,100), new OpCodeTypeInfo("neg",0,1,255,101), new OpCodeTypeInfo("not",0,1,255,102), new OpCodeTypeInfo("conv.i1",0,1,255,103), new OpCodeTypeInfo("conv.i2",0,1,255,104), new OpCodeTypeInfo("conv.i4",0,1,255,105), new OpCodeTypeInfo("conv.i8",0,1,255,106), new OpCodeTypeInfo("conv.r4",0,1,255,107), new OpCodeTypeInfo("conv.r8",0,1,255,108), new OpCodeTypeInfo("conv.u4",0,1,255,109), new OpCodeTypeInfo("conv.u8",0,1,255,110), new OpCodeTypeInfo("callvirt",6,1,255,111), new OpCodeTypeInfo("cpobj",8,1,255,112), new OpCodeTypeInfo("ldobj",8,1,255,113), new OpCodeTypeInfo("ldstr",9,1,255,114), new OpCodeTypeInfo("newobj",6,1,255,115), new OpCodeTypeInfo("castclass",8,1,255,116), new OpCodeTypeInfo("isinst",8,1,255,117), new OpCodeTypeInfo("conv.r.un",0,1,255,118), new OpCodeTypeInfo("unused",0,1,255,119), new OpCodeTypeInfo("unused",0,1,255,120), new OpCodeTypeInfo("unbox",8,1,255,121), new OpCodeTypeInfo("throw",0,1,255,122), new OpCodeTypeInfo("ldfld",7,1,255,123), new OpCodeTypeInfo("ldflda",7,1,255,124), new OpCodeTypeInfo("stfld",7,1,255,125), new OpCodeTypeInfo("ldsfld",7,1,255,126), new OpCodeTypeInfo("ldsflda",7,1,255,127), new OpCodeTypeInfo("stsfld",7,1,255,128), new OpCodeTypeInfo("stobj",8,1,255,129), new OpCodeTypeInfo("conv.ovf.i1.un",0,1,255,130), new OpCodeTypeInfo("conv.ovf.i2.un",0,1,255,131), new OpCodeTypeInfo("conv.ovf.i4.un",0,1,255,132), new OpCodeTypeInfo("conv.ovf.i8.un",0,1,255,133), new OpCodeTypeInfo("conv.ovf.u1.un",0,1,255,134), new OpCodeTypeInfo("conv.ovf.u2.un",0,1,255,135), new OpCodeTypeInfo("conv.ovf.u4.un",0,1,255,136), new OpCodeTypeInfo("conv.ovf.u8.un",0,1,255,137), new OpCodeTypeInfo("conv.ovf.i.un",0,1,255,138), new OpCodeTypeInfo("conv.ovf.u.un",0,1,255,139), new OpCodeTypeInfo("box",8,1,255,140), new OpCodeTypeInfo("newarr",8,1,255,141), new OpCodeTypeInfo("ldlen",0,1,255,142), new OpCodeTypeInfo("ldelema",8,1,255,143), new OpCodeTypeInfo("ldelem.i1",0,1,255,144), new OpCodeTypeInfo("ldelem.u1",0,1,255,145), new OpCodeTypeInfo("ldelem.i2",0,1,255,146), new OpCodeTypeInfo("ldelem.u2",0,1,255,147), new OpCodeTypeInfo("ldelem.i4",0,1,255,148), new OpCodeTypeInfo("ldelem.u4",0,1,255,149), new OpCodeTypeInfo("ldelem.i8",0,1,255,150), new OpCodeTypeInfo("ldelem.i",0,1,255,151), new OpCodeTypeInfo("ldelem.r4",0,1,255,152), new OpCodeTypeInfo("ldelem.r8",0,1,255,153), new OpCodeTypeInfo("ldelem.ref",0,1,255,154), new OpCodeTypeInfo("stelem.i",0,1,255,155), new OpCodeTypeInfo("stelem.i1",0,1,255,156), new OpCodeTypeInfo("stelem.i2",0,1,255,157), new OpCodeTypeInfo("stelem.i4",0,1,255,158), new OpCodeTypeInfo("stelem.i8",0,1,255,159), new OpCodeTypeInfo("stelem.r4",0,1,255,160), new OpCodeTypeInfo("stelem.r8",0,1,255,161), new OpCodeTypeInfo("stelem.ref",0,1,255,162), new OpCodeTypeInfo("unused",0,1,255,163), new OpCodeTypeInfo("unused",0,1,255,164), new OpCodeTypeInfo("unused",0,1,255,165), new OpCodeTypeInfo("unused",0,1,255,166), new OpCodeTypeInfo("unused",0,1,255,167), new OpCodeTypeInfo("unused",0,1,255,168), new OpCodeTypeInfo("unused",0,1,255,169), new OpCodeTypeInfo("unused",0,1,255,170), new OpCodeTypeInfo("unused",0,1,255,171), new OpCodeTypeInfo("unused",0,1,255,172), new OpCodeTypeInfo("unused",0,1,255,173), new OpCodeTypeInfo("unused",0,1,255,174), new OpCodeTypeInfo("unused",0,1,255,175), new OpCodeTypeInfo("unused",0,1,255,176), new OpCodeTypeInfo("unused",0,1,255,177), new OpCodeTypeInfo("unused",0,1,255,178), new OpCodeTypeInfo("conv.ovf.i1",0,1,255,179), new OpCodeTypeInfo("conv.ovf.u1",0,1,255,180), new OpCodeTypeInfo("conv.ovf.i2",0,1,255,181), new OpCodeTypeInfo("conv.ovf.u2",0,1,255,182), new OpCodeTypeInfo("conv.ovf.i4",0,1,255,183), new OpCodeTypeInfo("conv.ovf.u4",0,1,255,184), new OpCodeTypeInfo("conv.ovf.i8",0,1,255,185), new OpCodeTypeInfo("conv.ovf.u8",0,1,255,186), new OpCodeTypeInfo("unused",0,1,255,187), new OpCodeTypeInfo("unused",0,1,255,188), new OpCodeTypeInfo("unused",0,1,255,189), new OpCodeTypeInfo("unused",0,1,255,190), new OpCodeTypeInfo("unused",0,1,255,191), new OpCodeTypeInfo("unused",0,1,255,192), new OpCodeTypeInfo("unused",0,1,255,193), new OpCodeTypeInfo("refanyval",8,1,255,194), new OpCodeTypeInfo("ckfinite",0,1,255,195), new OpCodeTypeInfo("unused",0,1,255,196), new OpCodeTypeInfo("unused",0,1,255,197), new OpCodeTypeInfo("mkrefany",8,1,255,198), new OpCodeTypeInfo("unused",0,1,255,199), new OpCodeTypeInfo("unused",0,1,255,200), new OpCodeTypeInfo("unused",0,1,255,201), new OpCodeTypeInfo("unused",0,1,255,202), new OpCodeTypeInfo("unused",0,1,255,203), new OpCodeTypeInfo("unused",0,1,255,204), new OpCodeTypeInfo("unused",0,1,255,205), new OpCodeTypeInfo("unused",0,1,255,206), new OpCodeTypeInfo("unused",0,1,255,207), new OpCodeTypeInfo("ldtoken",12,1,255,208), new OpCodeTypeInfo("conv.u2",0,1,255,209), new OpCodeTypeInfo("conv.u1",0,1,255,210), new OpCodeTypeInfo("conv.i",0,1,255,211), new OpCodeTypeInfo("conv.ovf.i",0,1,255,212), new OpCodeTypeInfo("conv.ovf.u",0,1,255,213), new OpCodeTypeInfo("add.ovf",0,1,255,214), new OpCodeTypeInfo("add.ovf.un",0,1,255,215), new OpCodeTypeInfo("mul.ovf",0,1,255,216), new OpCodeTypeInfo("mul.ovf.un",0,1,255,217), new OpCodeTypeInfo("sub.ovf",0,1,255,218), new OpCodeTypeInfo("sub.ovf.un",0,1,255,219), new OpCodeTypeInfo("endfinally",0,1,255,220), new OpCodeTypeInfo("leave",4,1,255,221), new OpCodeTypeInfo("leave.s",20,1,255,222), new OpCodeTypeInfo("stind.i",0,1,255,223), new OpCodeTypeInfo("conv.u",0,1,255,224), new OpCodeTypeInfo("unused",0,1,255,225), new OpCodeTypeInfo("unused",0,1,255,226), new OpCodeTypeInfo("unused",0,1,255,227), new OpCodeTypeInfo("unused",0,1,255,228), new OpCodeTypeInfo("unused",0,1,255,229), new OpCodeTypeInfo("unused",0,1,255,230), new OpCodeTypeInfo("unused",0,1,255,231), new OpCodeTypeInfo("unused",0,1,255,232), new OpCodeTypeInfo("unused",0,1,255,233), new OpCodeTypeInfo("unused",0,1,255,234), new OpCodeTypeInfo("unused",0,1,255,235), new OpCodeTypeInfo("unused",0,1,255,236), new OpCodeTypeInfo("unused",0,1,255,237), new OpCodeTypeInfo("unused",0,1,255,238), new OpCodeTypeInfo("unused",0,1,255,239), new OpCodeTypeInfo("unused",0,1,255,240), new OpCodeTypeInfo("unused",0,1,255,241), new OpCodeTypeInfo("unused",0,1,255,242), new OpCodeTypeInfo("unused",0,1,255,243), new OpCodeTypeInfo("unused",0,1,255,244), new OpCodeTypeInfo("unused",0,1,255,245), new OpCodeTypeInfo("unused",0,1,255,246), new OpCodeTypeInfo("unused",0,1,255,247), new OpCodeTypeInfo("prefix7",0,1,255,248), new OpCodeTypeInfo("prefix6",0,1,255,249), new OpCodeTypeInfo("prefix5",0,1,255,250), new OpCodeTypeInfo("prefix4",0,1,255,251), new OpCodeTypeInfo("prefix3",0,1,255,252), new OpCodeTypeInfo("prefix2",0,1,255,253), new OpCodeTypeInfo("prefix1",0,1,255,254), new OpCodeTypeInfo("prefixref",0,1,255,255), new OpCodeTypeInfo("arglist",0,2,254,0), new OpCodeTypeInfo("ceq",0,2,254,1), new OpCodeTypeInfo("cgt",0,2,254,2), new OpCodeTypeInfo("cgt.un",0,2,254,3), new OpCodeTypeInfo("clt",0,2,254,4), new OpCodeTypeInfo("clt.un",0,2,254,5), new OpCodeTypeInfo("ldftn",6,2,254,6), new OpCodeTypeInfo("ldvirtftn",6,2,254,7), new OpCodeTypeInfo("unused",0,2,254,8), new OpCodeTypeInfo("ldarg",1,2,254,9), new OpCodeTypeInfo("ldarga",1,2,254,10), new OpCodeTypeInfo("starg",1,2,254,11), new OpCodeTypeInfo("ldloc",1,2,254,12), new OpCodeTypeInfo("ldloca",1,2,254,13), new OpCodeTypeInfo("stloc",1,2,254,14), new OpCodeTypeInfo("localloc",0,2,254,15), new OpCodeTypeInfo("unused",0,2,254,16), new OpCodeTypeInfo("endfilter",0,2,254,17), new OpCodeTypeInfo("unaligned.",18,2,254,18), new OpCodeTypeInfo("volatile.",0,2,254,19), new OpCodeTypeInfo("tail.",0,2,254,20), new OpCodeTypeInfo("initobj",8,2,254,21), new OpCodeTypeInfo("unused",0,2,254,22), new OpCodeTypeInfo("cpblk",0,2,254,23), new OpCodeTypeInfo("initblk",0,2,254,24), new OpCodeTypeInfo("unused",0,2,254,25), new OpCodeTypeInfo("rethrow",0,2,254,26), new OpCodeTypeInfo("unused",0,2,254,27), new OpCodeTypeInfo("sizeof",8,2,254,28), new OpCodeTypeInfo("refanytype",0,2,254,29), new OpCodeTypeInfo("unused",0,2,254,30), new OpCodeTypeInfo("unused",0,2,254,31), new OpCodeTypeInfo("unused",0,2,254,32), new OpCodeTypeInfo("unused",0,2,254,33), new OpCodeTypeInfo("unused",0,2,254,34), new OpCodeTypeInfo("illegal",0,0,0,0), new OpCodeTypeInfo("endmac",0,0,0,0), new OpCodeTypeInfo("brnull",0,0,0,0), new OpCodeTypeInfo("brnull.s",0,0,0,0), new OpCodeTypeInfo("brzero",0,0,0,0), new OpCodeTypeInfo("brzero.s",0,0,0,0), new OpCodeTypeInfo("brinst",0,0,0,0), new OpCodeTypeInfo("brinst.s",0,0,0,0), new OpCodeTypeInfo("ldind.u8",0,0,0,0), new OpCodeTypeInfo("ldelem.u8",0,0,0,0), new OpCodeTypeInfo("ldc.i4.M1",0,0,0,0), new OpCodeTypeInfo("endfault",0,0,0,0) }; } }
using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Web; using ServiceStack.Common; using ServiceStack.Common.Web; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints; using HttpRequestWrapper = ServiceStack.WebHost.Endpoints.Extensions.HttpRequestWrapper; namespace ServiceStack.ServiceHost { public static class HttpRequestExtensions { /// <summary> /// Gets string value from Items[name] then Cookies[name] if exists. /// Useful when *first* setting the users response cookie in the request filter. /// To access the value for this initial request you need to set it in Items[]. /// </summary> /// <returns>string value or null if it doesn't exist</returns> public static string GetItemOrCookie(this IHttpRequest httpReq, string name) { object value; if (httpReq.Items.TryGetValue(name, out value)) return value.ToString(); Cookie cookie; if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value; return null; } /// <summary> /// Gets request paramater string value by looking in the following order: /// - QueryString[name] /// - FormData[name] /// - Cookies[name] /// - Items[name] /// </summary> /// <returns>string value or null if it doesn't exist</returns> public static string GetParam(this IHttpRequest httpReq, string name) { string value; if ((value = httpReq.Headers[HttpHeaders.XParamOverridePrefix + name]) != null) return value; if ((value = httpReq.QueryString[name]) != null) return value; if ((value = httpReq.FormData[name]) != null) return value; //IIS will assign null to params without a name: .../?some_value can be retrieved as req.Params[null] //TryGetValue is not happy with null dictionary keys, so we should bail out here if (string.IsNullOrEmpty(name)) return null; Cookie cookie; if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value; object oValue; if (httpReq.Items.TryGetValue(name, out oValue)) return oValue.ToString(); return null; } public static string GetParentAbsolutePath(this IHttpRequest httpReq) { return httpReq.GetAbsolutePath().ToParentPath(); } public static string GetAbsolutePath(this IHttpRequest httpReq) { var resolvedPathInfo = httpReq.PathInfo; var pos = httpReq.RawUrl.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase); if (pos == -1) throw new ArgumentException( String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl)); return httpReq.RawUrl.Substring(0, pos + resolvedPathInfo.Length); } public static string GetParentPathUrl(this IHttpRequest httpReq) { return httpReq.GetPathUrl().ToParentPath(); } public static string GetPathUrl(this IHttpRequest httpReq) { var resolvedPathInfo = httpReq.PathInfo; var pos = resolvedPathInfo == String.Empty ? httpReq.AbsoluteUri.Length : httpReq.AbsoluteUri.IndexOf(resolvedPathInfo, StringComparison.InvariantCultureIgnoreCase); if (pos == -1) throw new ArgumentException( String.Format("PathInfo '{0}' is not in Url '{1}'", resolvedPathInfo, httpReq.RawUrl)); return httpReq.AbsoluteUri.Substring(0, pos + resolvedPathInfo.Length); } public static string GetUrlHostName(this IHttpRequest httpReq) { var aspNetReq = httpReq as HttpRequestWrapper; if (aspNetReq != null) { return aspNetReq.UrlHostName; } var uri = httpReq.AbsoluteUri; var pos = uri.IndexOf("://") + "://".Length; var partialUrl = uri.Substring(pos); var endPos = partialUrl.IndexOf('/'); if (endPos == -1) endPos = partialUrl.Length; var hostName = partialUrl.Substring(0, endPos).Split(':')[0]; return hostName; } public static string GetPhysicalPath(this IHttpRequest httpReq) { var aspNetReq = httpReq as HttpRequestWrapper; var res = aspNetReq != null ? aspNetReq.Request.PhysicalPath : EndpointHostConfig.Instance.WebHostPhysicalPath.CombineWith(httpReq.PathInfo); return res; } public static string GetApplicationUrl(this HttpRequest httpReq) { var appPath = httpReq.ApplicationPath; var baseUrl = httpReq.Url.Scheme + "://" + httpReq.Url.Host; if (httpReq.Url.Port != 80) baseUrl += ":" + httpReq.Url.Port; var appUrl = baseUrl.CombineWith(appPath); return appUrl; } public static string GetApplicationUrl(this IHttpRequest httpReq) { var url = new Uri(httpReq.AbsoluteUri); var baseUrl = url.Scheme + "://" + url.Host; if (url.Port != 80) baseUrl += ":" + url.Port; var appUrl = baseUrl.CombineWith(EndpointHost.Config.ServiceStackHandlerFactoryPath); return appUrl; } public static string GetHttpMethodOverride(this IHttpRequest httpReq) { var httpMethod = httpReq.HttpMethod; if (httpMethod != HttpMethods.Post) return httpMethod; var overrideHttpMethod = httpReq.Headers[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty() ?? httpReq.FormData[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty() ?? httpReq.QueryString[HttpHeaders.XHttpMethodOverride].ToNullIfEmpty(); if (overrideHttpMethod != null) { if (overrideHttpMethod != HttpMethods.Get && overrideHttpMethod != HttpMethods.Post) httpMethod = overrideHttpMethod; } return httpMethod; } public static string GetFormatModifier(this IHttpRequest httpReq) { var format = httpReq.QueryString["format"]; if (format == null) return null; var parts = format.SplitOnFirst('.'); return parts.Length > 1 ? parts[1] : null; } public static bool HasNotModifiedSince(this IHttpRequest httpReq, DateTime? dateTime) { if (!dateTime.HasValue) return false; var strHeader = httpReq.Headers[HttpHeaders.IfModifiedSince]; try { if (strHeader != null) { var dateIfModifiedSince = DateTime.ParseExact(strHeader, "r", null); var utcFromDate = dateTime.Value.ToUniversalTime(); //strip ms utcFromDate = new DateTime( utcFromDate.Ticks - (utcFromDate.Ticks % TimeSpan.TicksPerSecond), utcFromDate.Kind ); return utcFromDate <= dateIfModifiedSince; } return false; } catch { return false; } } public static bool DidReturn304NotModified(this IHttpRequest httpReq, DateTime? dateTime, IHttpResponse httpRes) { if (httpReq.HasNotModifiedSince(dateTime)) { httpRes.StatusCode = (int) HttpStatusCode.NotModified; return true; } return false; } public static string GetJsonpCallback(this IHttpRequest httpReq) { return httpReq == null ? null : httpReq.QueryString["callback"]; } public static Dictionary<string, string> CookiesAsDictionary(this IHttpRequest httpReq) { var map = new Dictionary<string, string>(); var aspNet = httpReq.OriginalRequest as HttpRequest; if (aspNet != null) { foreach (var name in aspNet.Cookies.AllKeys) { var cookie = aspNet.Cookies[name]; if (cookie == null) continue; map[name] = cookie.Value; } } else { var httpListener = httpReq.OriginalRequest as HttpListenerRequest; if (httpListener != null) { for (var i = 0; i < httpListener.Cookies.Count; i++) { var cookie = httpListener.Cookies[i]; if (cookie == null || cookie.Name == null) continue; map[cookie.Name] = cookie.Value; } } } return map; } public static int ToStatusCode(this Exception ex) { int errorStatus; if (EndpointHost.Config != null && EndpointHost.Config.MapExceptionToStatusCode.TryGetValue(ex.GetType(), out errorStatus)) { return errorStatus; } if (ex is HttpError) return ((HttpError)ex).Status; if (ex is NotImplementedException || ex is NotSupportedException) return (int)HttpStatusCode.MethodNotAllowed; if (ex is ArgumentException || ex is SerializationException) return (int)HttpStatusCode.BadRequest; if (ex is UnauthorizedAccessException) return (int) HttpStatusCode.Forbidden; return (int)HttpStatusCode.InternalServerError; } public static string ToErrorCode(this Exception ex) { if (ex is HttpError) return ((HttpError)ex).ErrorCode; return ex.GetType().Name; } } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Text.Util.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Android.Text.Util { /// <summary> /// <para>This class stores an RFC 822-like name, address, and comment, and provides methods to convert them to quoted strings. </para> /// </summary> /// <java-name> /// android/text/util/Rfc822Token /// </java-name> [Dot42.DexImport("android/text/util/Rfc822Token", AccessFlags = 33)] public partial class Rfc822Token /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new Rfc822Token with the specified name, address, and comment. </para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public Rfc822Token(string name, string address, string comment) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name part. </para> /// </summary> /// <java-name> /// getName /// </java-name> [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the address part. </para> /// </summary> /// <java-name> /// getAddress /// </java-name> [Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetAddress() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the comment part. </para> /// </summary> /// <java-name> /// getComment /// </java-name> [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetComment() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Changes the name to the specified name. </para> /// </summary> /// <java-name> /// setName /// </java-name> [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetName(string name) /* MethodBuilder.Create */ { } /// <summary> /// <para>Changes the address to the specified address. </para> /// </summary> /// <java-name> /// setAddress /// </java-name> [Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetAddress(string address) /* MethodBuilder.Create */ { } /// <summary> /// <para>Changes the comment to the specified comment. </para> /// </summary> /// <java-name> /// setComment /// </java-name> [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)] public virtual void SetComment(string comment) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name (with quoting added if necessary), the comment (in parentheses), and the address (in angle brackets). This should be suitable for inclusion in an RFC 822 address list. </para> /// </summary> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the name, conservatively quoting it if there are any characters that are likely to cause trouble outside of a quoted string, or returning it literally if it seems safe. </para> /// </summary> /// <java-name> /// quoteNameIfNecessary /// </java-name> [Dot42.DexImport("quoteNameIfNecessary", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteNameIfNecessary(string name) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the name, with internal backslashes and quotation marks preceded by backslashes. The outer quote marks themselves are not added by this method. </para> /// </summary> /// <java-name> /// quoteName /// </java-name> [Dot42.DexImport("quoteName", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteName(string name) /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the comment, with internal backslashes and parentheses preceded by backslashes. The outer parentheses themselves are not added by this method. </para> /// </summary> /// <java-name> /// quoteComment /// </java-name> [Dot42.DexImport("quoteComment", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 9)] public static string QuoteComment(string comment) /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object o) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal Rfc822Token() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name part. </para> /// </summary> /// <java-name> /// getName /// </java-name> public string Name { [Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetName(); } [Dot42.DexImport("setName", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetName(value); } } /// <summary> /// <para>Returns the address part. </para> /// </summary> /// <java-name> /// getAddress /// </java-name> public string Address { [Dot42.DexImport("getAddress", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetAddress(); } [Dot42.DexImport("setAddress", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetAddress(value); } } /// <summary> /// <para>Returns the comment part. </para> /// </summary> /// <java-name> /// getComment /// </java-name> public string Comment { [Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetComment(); } [Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1)] set{ SetComment(value); } } } /// <summary> /// <para>Linkify take a piece of text and a regular expression and turns all of the regex matches in the text into clickable links. This is particularly useful for matching things like email addresses, web urls, etc. and making them actionable.</para><para>Alone with the pattern that is to be matched, a url scheme prefix is also required. Any pattern match that does not begin with the supplied scheme will have the scheme prepended to the matched text when the clickable url is created. For instance, if you are matching web urls you would supply the scheme <code></code>. If the pattern matches example.com, which does not have a url scheme prefix, the supplied scheme will be prepended to create <code></code> when the clickable url link is created. </para> /// </summary> /// <java-name> /// android/text/util/Linkify /// </java-name> [Dot42.DexImport("android/text/util/Linkify", AccessFlags = 33)] public partial class Linkify /* scope: __dot42__ */ { /// <summary> /// <para>Bit field indicating that web URLs should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// WEB_URLS /// </java-name> [Dot42.DexImport("WEB_URLS", "I", AccessFlags = 25)] public const int WEB_URLS = 1; /// <summary> /// <para>Bit field indicating that email addresses should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// EMAIL_ADDRESSES /// </java-name> [Dot42.DexImport("EMAIL_ADDRESSES", "I", AccessFlags = 25)] public const int EMAIL_ADDRESSES = 2; /// <summary> /// <para>Bit field indicating that phone numbers should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// PHONE_NUMBERS /// </java-name> [Dot42.DexImport("PHONE_NUMBERS", "I", AccessFlags = 25)] public const int PHONE_NUMBERS = 4; /// <summary> /// <para>Bit field indicating that street addresses should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// MAP_ADDRESSES /// </java-name> [Dot42.DexImport("MAP_ADDRESSES", "I", AccessFlags = 25)] public const int MAP_ADDRESSES = 8; /// <summary> /// <para>Bit mask indicating that all available patterns should be matched in methods that take an options mask </para> /// </summary> /// <java-name> /// ALL /// </java-name> [Dot42.DexImport("ALL", "I", AccessFlags = 25)] public const int ALL = 15; /// <summary> /// <para>Filters out web URL matches that occur after an at-sign (@). This is to prevent turning the domain name in an email address into a web link. </para> /// </summary> /// <java-name> /// sUrlMatchFilter /// </java-name> [Dot42.DexImport("sUrlMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.IMatchFilter SUrlMatchFilter; /// <summary> /// <para>Filters out URL matches that don't have enough digits to be a phone number. </para> /// </summary> /// <java-name> /// sPhoneNumberMatchFilter /// </java-name> [Dot42.DexImport("sPhoneNumberMatchFilter", "Landroid/text/util/Linkify$MatchFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.IMatchFilter SPhoneNumberMatchFilter; /// <summary> /// <para>Transforms matched phone number text into something suitable to be used in a tel: URL. It does this by removing everything but the digits and plus signs. For instance: '+1 (919) 555-1212' becomes '+19195551212' </para> /// </summary> /// <java-name> /// sPhoneNumberTransformFilter /// </java-name> [Dot42.DexImport("sPhoneNumberTransformFilter", "Landroid/text/util/Linkify$TransformFilter;", AccessFlags = 25)] public static readonly global::Android.Text.Util.Linkify.ITransformFilter SPhoneNumberTransformFilter; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Linkify() /* MethodBuilder.Create */ { } /// <summary> /// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para> /// </summary> /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;I)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable text, int mask) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Scans the text of the provided Spannable and turns all occurrences of the link types indicated in the mask into clickable links. If the mask is nonzero, it also removes any existing URLSpans attached to the Spannable, to avoid problems if you call it repeatedly on the same text. </para> /// </summary> /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;I)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Widget.TextView text, int mask) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;)V", AccessFlags = 25)] public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */ { } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/widget/TextView;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/tex" + "t/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)V", AccessFlags = 25)] public static void AddLinks(global::Android.Widget.TextView textView, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */ { } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// addLinks /// </java-name> [Dot42.DexImport("addLinks", "(Landroid/text/Spannable;Ljava/util/regex/Pattern;Ljava/lang/String;Landroid/text" + "/util/Linkify$MatchFilter;Landroid/text/util/Linkify$TransformFilter;)Z", AccessFlags = 25)] public static bool AddLinks(global::Android.Text.ISpannable spannable, global::Java.Util.Regex.Pattern pattern, string @string, global::Android.Text.Util.Linkify.IMatchFilter matchFilter, global::Android.Text.Util.Linkify.ITransformFilter transformFilter) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>TransformFilter enables client code to have more control over how matched patterns are represented as URLs.</para><para>For example: when converting a phone number such as (919) 555-1212 into a tel: URL the parentheses, white space, and hyphen need to be removed to produce tel:9195551212. </para> /// </summary> /// <java-name> /// android/text/util/Linkify$TransformFilter /// </java-name> [Dot42.DexImport("android/text/util/Linkify$TransformFilter", AccessFlags = 1545)] public partial interface ITransformFilter /* scope: __dot42__ */ { /// <summary> /// <para>Examines the matched text and either passes it through or uses the data in the Matcher state to produce a replacement.</para><para></para> /// </summary> /// <returns> /// <para>The transformed form of the URL </para> /// </returns> /// <java-name> /// transformUrl /// </java-name> [Dot42.DexImport("transformUrl", "(Ljava/util/regex/Matcher;Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)] string TransformUrl(global::Java.Util.Regex.Matcher match, string url) /* MethodBuilder.Create */ ; } /// <summary> /// <para>MatchFilter enables client code to have more control over what is allowed to match and become a link, and what is not.</para><para>For example: when matching web urls you would like things like to match, as well as just example.com itelf. However, you would not want to match against the domain in . So, when matching against a web url pattern you might also include a MatchFilter that disallows the match if it is immediately preceded by an at-sign (@). </para> /// </summary> /// <java-name> /// android/text/util/Linkify$MatchFilter /// </java-name> [Dot42.DexImport("android/text/util/Linkify$MatchFilter", AccessFlags = 1545)] public partial interface IMatchFilter /* scope: __dot42__ */ { /// <summary> /// <para>Examines the character span matched by the pattern and determines if the match should be turned into an actionable link.</para><para></para> /// </summary> /// <returns> /// <para>Whether this match should be turned into a link </para> /// </returns> /// <java-name> /// acceptMatch /// </java-name> [Dot42.DexImport("acceptMatch", "(Ljava/lang/CharSequence;II)Z", AccessFlags = 1025)] bool AcceptMatch(global::Java.Lang.ICharSequence s, int start, int end) /* MethodBuilder.Create */ ; } } /// <summary> /// <para>This class works as a Tokenizer for MultiAutoCompleteTextView for address list fields, and also provides a method for converting a string of addresses (such as might be typed into such a field) into a series of Rfc822Tokens. </para> /// </summary> /// <java-name> /// android/text/util/Rfc822Tokenizer /// </java-name> [Dot42.DexImport("android/text/util/Rfc822Tokenizer", AccessFlags = 33)] public partial class Rfc822Tokenizer : global::Android.Widget.MultiAutoCompleteTextView.ITokenizer /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Rfc822Tokenizer() /* MethodBuilder.Create */ { } /// <summary> /// <para>This constructor will try to take a string like "Foo Bar (something) &amp;lt;foo\@google.com&amp;gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens, output into the supplied collection.</para><para>It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para> /// </summary> /// <java-name> /// tokenize /// </java-name> [Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;Ljava/util/Collection;)V", AccessFlags = 9, Signature = "(Ljava/lang/CharSequence;Ljava/util/Collection<Landroid/text/util/Rfc822Token;>;)" + "V")] public static void Tokenize(global::Java.Lang.ICharSequence text, global::Java.Util.ICollection<global::Android.Text.Util.Rfc822Token> @out) /* MethodBuilder.Create */ { } /// <summary> /// <para>This method will try to take a string like "Foo Bar (something) &amp;lt;foo\@google.com&amp;gt;, blah\@google.com (something)" and convert it into one or more Rfc822Tokens. It does <b>not</b> decode MIME encoded-words; charset conversion must already have taken place if necessary. It will try to be tolerant of broken syntax instead of returning an error. </para> /// </summary> /// <java-name> /// tokenize /// </java-name> [Dot42.DexImport("tokenize", "(Ljava/lang/CharSequence;)[Landroid/text/util/Rfc822Token;", AccessFlags = 9)] public static global::Android.Text.Util.Rfc822Token[] Tokenize(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */ { return default(global::Android.Text.Util.Rfc822Token[]); } /// <summary> /// <para><para>Returns the start of the token that ends at offset <code>cursor</code> within <code>text</code>.</para> </para> /// </summary> /// <java-name> /// findTokenStart /// </java-name> [Dot42.DexImport("findTokenStart", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)] public virtual int FindTokenStart(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para><para>Returns the end of the token (minus trailing punctuation) that begins at offset <code>cursor</code> within <code>text</code>.</para> </para> /// </summary> /// <java-name> /// findTokenEnd /// </java-name> [Dot42.DexImport("findTokenEnd", "(Ljava/lang/CharSequence;I)I", AccessFlags = 1)] public virtual int FindTokenEnd(global::Java.Lang.ICharSequence text, int cursor) /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Terminates the specified address with a comma and space. This assumes that the specified text already has valid syntax. The Adapter subclass's convertToString() method must make that guarantee. </para> /// </summary> /// <java-name> /// terminateToken /// </java-name> [Dot42.DexImport("terminateToken", "(Ljava/lang/CharSequence;)Ljava/lang/CharSequence;", AccessFlags = 1)] public virtual global::Java.Lang.ICharSequence TerminateToken(global::Java.Lang.ICharSequence text) /* MethodBuilder.Create */ { return default(global::Java.Lang.ICharSequence); } } }
using System; using System.IO; using System.Security.Principal; using System.Web; using System.Web.Mvc; using System.Web.Routing; using MvcContrib.UI.MenuBuilder; using NUnit.Framework; using Rhino.Mocks; namespace MvcContrib.UnitTests.UI.MenuBuilder { [TestFixture, Obsolete] public class MenuBuilderTests { [SetUp] public void Setup() { writer = new StringWriter(); RouteTable.Routes.Clear(); RouteTable.Routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); var requestContext = GetRequestContext(); var controller = new HomeController(); controllerContext = new ControllerContext(requestContext, controller); } [TearDown] public void Teardown() { RouteTable.Routes.Clear(); //To prevent other tests from failing. } private RequestContext GetRequestContext() { HttpContextBase httpcontext = GetHttpContext(@"Home/Index"); RouteData rd = new RouteData(); rd.Values.Add("controller", "Home"); rd.Values.Add("action", "Index"); return new RequestContext(httpcontext, rd); } private HttpContextBase GetHttpContext(string appPath) { var mockContext = MockRepository.GenerateMock<HttpContextBase>(); var mockRequest = MockRepository.GenerateMock<HttpRequestBase>(); if (!String.IsNullOrEmpty(appPath)) { mockRequest.Stub(o => o.ApplicationPath).Return(appPath); } Uri uri = new Uri("http://localhost/"); mockRequest.Stub(o => o.Url).Return(uri); mockRequest.Stub(o => o.PathInfo).Return(String.Empty); mockContext.Stub(o => o.Request).Return(mockRequest); mockContext.Stub(o => o.Session).Return(null); var mockResponse = MockRepository.GenerateMock<HttpResponseBase>(); mockResponse.Stub(o => o.ApplyAppPathModifier(null)).IgnoreArguments().Do((Func<string, string>)(s => s)); mockContext.Stub(o => o.Response).Return(mockResponse); mockRequest.Stub(o => o.Path).Return("Home/Index/"); var principal = MockRepository.GenerateMock<IPrincipal>(); mockContext.Stub(o => o.User).Return(principal); identity = new TestIdentity() { IsAuthenticated = false }; principal.Stub(o => o.Identity).Return(identity); return mockContext; } /// <summary> /// I'm sure there's some magic mocking-foo way of doing this to change the return value of IsAuthenticated mid test, but I'm just /// a 2nd level half-dwarf when it comes to such things.... /// </summary> private class TestIdentity : IIdentity { public string Name { get { return "Bob"; } } public string AuthenticationType { get { return "Manual"; } } public bool IsAuthenticated { get; set; } } private TestIdentity identity; private TextWriter writer; private ControllerContext controllerContext; private string Out { get { return writer.ToString(); } } [Test] public void MenuLinkPrintsCorrectTag() { MenuItem link = Menu.Link("Url", "Title"); link.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Url\">Title</a></li>", Out); } [Test] public void MenuLinkIconPrintsCorrectTag() { MenuItem link = Menu.Link("Url", "Title", "Icon"); link.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Url\"><img alt=\"Title\" border=\"0\" src=\"Icon\" />Title</a></li>", Out); } [Test] public void MenuLinkIconWithNoTitlePrintsCorrectTag() { MenuItem link = Menu.Link("Url", null, "Icon"); link.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Url\"><img border=\"0\" src=\"Icon\" /></a></li>", Out); } [Test] public void MenuItem_Fluent_Tests() { MenuItem item = new MenuItem(); item.SetTitle("Title").SetIcon("Icon").SetHelpText("Help").SetActionUrl("Action").SetAnchorClass("AnchorClass"). SetIconClass("IconClass").SetItemClass("ItemClass"); Assert.AreEqual("Title", item.Title); Assert.AreEqual("Icon", item.Icon); Assert.AreEqual("Help", item.HelpText); Assert.AreEqual("Action", item.ActionUrl); Assert.AreEqual("AnchorClass", item.AnchorClass); Assert.AreEqual("IconClass", item.IconClass); Assert.AreEqual("ItemClass", item.ItemClass); MenuList list = new MenuList(); list.SetListClass("ListClass"); Assert.AreEqual("ListClass", list.ListClass); ActionMenuItem<HomeController> ai = new ActionMenuItem<HomeController>(); ai.SetMenuAction(p => p.Index()); Assert.AreEqual("p.Index()", ai.MenuAction.Body.ToString()); } [Test] public void ActionMenuItemRendersLink() { MenuItem action = Menu.Action<HomeController>(p => p.Index()); action.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Home/Index/\">Index</a></li>", Out); } [Test] public void ActionMenuItemRendersLinkWithIcon() { MenuItem action = Menu.Action<HomeController>(p => p.Index(), "Title", "Icon"); action.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Home/Index/\"><img alt=\"Title\" border=\"0\" src=\"Icon\" />Title</a></li>", Out); } [Test] public void ActionMenuItemRendersLinkWithIconAndNoTitle() { MenuItem action = Menu.Action<HomeController>(p => p.Index(), null, "Icon"); action.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Home/Index/\"><img border=\"0\" src=\"Icon\" /></a></li>", Out); } [Test] public void MenuTitleAndMenuHelpAttributesSetValues() { MenuItem action = Menu.Action<HomeController>(p => p.Index2()); action.Prepare(controllerContext); Assert.AreEqual("Title", action.Title); Assert.AreEqual("Help Text", action.HelpText); } [Test] public void SecureMenuItemDisplaysNothingWhenNotAuthenticated() { MenuItem action = Menu.Secure<HomeController>(p => p.Index()); action.RenderHtml(controllerContext, writer); Assert.AreEqual("", Out); identity.IsAuthenticated = true; action.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Home/Index/\">Index</a></li>", Out); } [Test] public void CanCreateMenuLists() { MenuList list = Menu.Items("ListItems", Menu.Link("Url1", "Title1"), Menu.Link("Url2", "Title2")); Assert.AreEqual(2, list.Count); Assert.AreEqual("Title1", list[0].Title); Assert.AreEqual("Title2", list[1].Title); list.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a>ListItems</a><ul><li><a href=\"Url1\">Title1</a></li><li><a href=\"Url2\">Title2</a></li></ul></li>", Out); } [Test] public void CanCreateMenuListsWithIcon() { MenuList list = Menu.Items("ListItems", "Icon", Menu.Link("Url1", "Title1"), Menu.Link("Url2", "Title2")); Assert.AreEqual(2, list.Count); Assert.AreEqual("Title1", list[0].Title); Assert.AreEqual("Title2", list[1].Title); list.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a><img alt=\"ListItems\" border=\"0\" src=\"Icon\" />ListItems</a><ul><li><a href=\"Url1\">Title1</a></li><li><a href=\"Url2\">Title2</a></li></ul></li>", Out); } [Test] public void CanCreateMenuListsWithIconOnly() { MenuList list = Menu.Items(null, "Icon", Menu.Link("Url1", "Title1"), Menu.Link("Url2", "Title2")); Assert.AreEqual(2, list.Count); Assert.AreEqual("Title1", list[0].Title); Assert.AreEqual("Title2", list[1].Title); list.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a><img border=\"0\" src=\"Icon\" /></a><ul><li><a href=\"Url1\">Title1</a></li><li><a href=\"Url2\">Title2</a></li></ul></li>", Out); } [Test] public void SecureItemsAreRemovedFromMenuList() { MenuList list = Menu.Items("ListItems", Menu.Link("Url1", "Title1"), Menu.Link("Url2", "Title2"), Menu.Secure<HomeController>(p => p.Index())); list.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a>ListItems</a><ul><li><a href=\"Url1\">Title1</a></li><li><a href=\"Url2\">Title2</a></li></ul></li>", Out); } [Test] public void ListsWithSingleItemsCollapsedIntoNonList() { MenuList list = Menu.Items("ListItems", Menu.Link("Url1", "Title1"), Menu.Secure<HomeController>(p => p.Index())); list.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a href=\"Url1\">Title1</a></li>", Out); } [Test, ExpectedException(typeof(InvalidOperationException))] public void CallingRenderOnListWithoutPrepareThrows() { MenuList list = Menu.Items("ListItems", Menu.Link("Url1", "Title1"), Menu.Secure<HomeController>(p => p.Index())); string html = list.RenderHtml(); } [Test, ExpectedException(typeof(InvalidOperationException))] public void CallingRenderOnItemWithoutPrepareThrows() { MenuItem link = Menu.Link("Url1", "Title1"); string html = link.RenderHtml(); } [Test] public void TestICollectionMembersOnMenuList() { MenuList list = new MenuList(); var item = new MenuItem(); list.Add(item); Assert.IsTrue(list.Contains(item)); list.Remove(item); Assert.IsFalse(list.Contains(item)); list.Add(item); Assert.AreEqual(1, list.Count); list.Clear(); Assert.AreEqual(0, list.Count); MenuItem[] array = new MenuItem[1]; list.Add(item); list.CopyTo(array, 0); Assert.AreEqual(item, array[0]); Assert.IsFalse(list.IsReadOnly); foreach (var menuItem in list) { Assert.AreEqual(item, menuItem); } } [Test] public void RenderingListWithNoItemsIsEmpty() { MenuList list = new MenuList(); list.RenderHtml(controllerContext, writer); Assert.AreEqual("", Out); } [Test, ExpectedException(typeof(InvalidOperationException))] public void CannotSecureActionMenuItemWithNoAction() { var item = new SecureActionMenuItem<HomeController>(); item.Prepare(controllerContext); } [Test, ExpectedException(typeof(InvalidOperationException))] public void CannotActionMenuItemWithNoAction() { var item = new ActionMenuItem<HomeController>(); item.Prepare(controllerContext); } [Test] public void CanAssignTitleViaFluentMenu() { var item = Menu.Action<HomeController>(p => p.Index(), "A Title"); var secureItem = Menu.Secure<HomeController>(p => p.Index2(), "A Different Title"); Assert.AreEqual("A Title", item.Title); Assert.AreEqual("A Different Title", secureItem.Title); } [Test] public void MenuBeginCreatesMenuWithNoTitle() { var item = Menu.Begin( Menu.Link("Url1", "Title1"), Menu.Link("Url2", "Title2")); Assert.AreEqual(null, item.Title); item.RenderHtml(controllerContext, writer); Assert.AreEqual("<ul><li><a href=\"Url1\">Title1</a></li><li><a href=\"Url2\">Title2</a></li></ul>", Out); } [Test] public void CanSetDefaultIconDirectory() { string originalIconDirectory = Menu.DefaultIconDirectory; try { Menu.DefaultIconDirectory = "/content/"; var item = Menu.Link("Url", "Title", "Icon.jpg"); item.RenderHtml(controllerContext, writer); Assert.AreEqual( "<li><a href=\"Url\"><img alt=\"Title\" border=\"0\" src=\"/content/Icon.jpg\" />Title</a></li>", Out); } finally { //need to set the static field back otherwise it affects other tests Menu.DefaultIconDirectory = originalIconDirectory; } } [Test] public void DisabledItemsRenderWithDisabledClass() { MenuItem secure = Menu.Secure<HomeController>(p => p.Index()); secure.SetShowWhenDisabled(true).SetDisabledMenuItemClass("DisabledClass"); secure.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a class=\"DisabledClass\">Index</a></li>", Out); } [Test] public void SelectedItemsShouldRenderAsSuch() { MenuItem link = Menu.Action<HomeController>(p => p.Index()); link.SetSelectedClass("selected"); link.RenderHtml(controllerContext, writer); Assert.AreEqual("<li><a class=\"selected\" href=\"Home/Index/\">Index</a></li>", Out); } public class HomeController : Controller { [Authorize] public ActionResult Index() { return null; } [MenuTitle("Title")] [MenuHelpText("Help Text")] public ActionResult Index2() { return null; } public int NonMethodCall { 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 Fixtures.AcceptanceTestsRequiredOptional { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for ExplicitModel. /// </summary> public static partial class ExplicitModelExtensions { /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredIntegerParameter(this IExplicitModel operations, int bodyParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredIntegerParameterAsync(this IExplicitModel operations, int bodyParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalIntegerParameter(this IExplicitModel operations, int? bodyParameter = default(int?)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalIntegerParameterAsync(this IExplicitModel operations, int? bodyParameter = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalIntegerParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredIntegerProperty(this IExplicitModel operations, int value) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a valid int-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredIntegerPropertyAsync(this IExplicitModel operations, int value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalIntegerProperty(this IExplicitModel operations, int? value = default(int?)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid int-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalIntegerPropertyAsync(this IExplicitModel operations, int? value = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalIntegerPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredIntegerHeader(this IExplicitModel operations, int headerParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredIntegerHeaderAsync(headerParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required integer. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredIntegerHeaderAsync(this IExplicitModel operations, int headerParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalIntegerHeader(this IExplicitModel operations, int? headerParameter = default(int?)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalIntegerHeaderAsync(headerParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalIntegerHeaderAsync(this IExplicitModel operations, int? headerParameter = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalIntegerHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredStringParameter(this IExplicitModel operations, string bodyParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredStringParameterAsync(this IExplicitModel operations, string bodyParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringParameter(this IExplicitModel operations, string bodyParameter = default(string)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalStringParameterAsync(this IExplicitModel operations, string bodyParameter = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalStringParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredStringProperty(this IExplicitModel operations, string value) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a valid string-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredStringPropertyAsync(this IExplicitModel operations, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalStringProperty(this IExplicitModel operations, string value = default(string)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a valid string-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalStringPropertyAsync(this IExplicitModel operations, string value = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalStringPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredStringHeader(this IExplicitModel operations, string headerParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredStringHeaderAsync(headerParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required string. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredStringHeaderAsync(this IExplicitModel operations, string headerParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredStringHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalStringHeader(this IExplicitModel operations, string bodyParameter = default(string)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalStringHeaderAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional string. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalStringHeaderAsync(this IExplicitModel operations, string bodyParameter = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalStringHeaderWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredClassParameter(this IExplicitModel operations, Product bodyParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put null and the client /// library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredClassParameterAsync(this IExplicitModel operations, Product bodyParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalClassParameter(this IExplicitModel operations, Product bodyParameter = default(Product)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalClassParameterAsync(this IExplicitModel operations, Product bodyParameter = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalClassParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredClassProperty(this IExplicitModel operations, Product value) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredClassPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required complex object. Please put a valid class-wrapper /// with 'value' = null and the client library should throw before the /// request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredClassPropertyAsync(this IExplicitModel operations, Product value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalClassProperty(this IExplicitModel operations, Product value = default(Product)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalClassPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional complex object. Please put a valid class-wrapper /// with 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalClassPropertyAsync(this IExplicitModel operations, Product value = default(Product), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalClassPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static Error PostRequiredArrayParameter(this IExplicitModel operations, System.Collections.Generic.IList<string> bodyParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put null and the client library /// should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredArrayParameterAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> bodyParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PostOptionalArrayParameter(this IExplicitModel operations, System.Collections.Generic.IList<string> bodyParameter = default(System.Collections.Generic.IList<string>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayParameterAsync(bodyParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalArrayParameterAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> bodyParameter = default(System.Collections.Generic.IList<string>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalArrayParameterWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static Error PostRequiredArrayProperty(this IExplicitModel operations, System.Collections.Generic.IList<string> value) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a valid array-wrapper with /// 'value' = null and the client library should throw before the request is /// sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredArrayPropertyAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> public static void PostOptionalArrayProperty(this IExplicitModel operations, System.Collections.Generic.IList<string> value = default(System.Collections.Generic.IList<string>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayPropertyAsync(value), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional array. Please put a valid array-wrapper with /// 'value' = null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='value'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalArrayPropertyAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> value = default(System.Collections.Generic.IList<string>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalArrayPropertyWithHttpMessagesAsync(value, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static Error PostRequiredArrayHeader(this IExplicitModel operations, System.Collections.Generic.IList<string> headerParameter) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostRequiredArrayHeaderAsync(headerParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly required array. Please put a header 'headerParameter' /// =&gt; null and the client library should throw before the request is sent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> PostRequiredArrayHeaderAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> headerParameter, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PostRequiredArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> public static void PostOptionalArrayHeader(this IExplicitModel operations, System.Collections.Generic.IList<string> headerParameter = default(System.Collections.Generic.IList<string>)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IExplicitModel)s).PostOptionalArrayHeaderAsync(headerParameter), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test explicitly optional integer. Please put a header 'headerParameter' /// =&gt; null. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='headerParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task PostOptionalArrayHeaderAsync(this IExplicitModel operations, System.Collections.Generic.IList<string> headerParameter = default(System.Collections.Generic.IList<string>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.PostOptionalArrayHeaderWithHttpMessagesAsync(headerParameter, null, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using osu.Framework.Logging; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; namespace osu.Framework.Testing { public class DynamicClassCompiler<T> : IDisposable where T : IDynamicallyCompile { public Action CompilationStarted; public Action<Type> CompilationFinished; public Action<Exception> CompilationFailed; private readonly List<FileSystemWatcher> watchers = new List<FileSystemWatcher>(); private string lastTouchedFile; private T checkpointObject; public void Checkpoint(T obj) { checkpointObject = obj; } private readonly List<string> requiredFiles = new List<string>(); private List<string> requiredTypeNames = new List<string>(); private HashSet<string> assemblies; private readonly List<string> validDirectories = new List<string>(); public void Start() { var di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory); Task.Run(() => { var basePath = di.Parent?.Parent?.Parent?.Parent?.FullName; if (!Directory.Exists(basePath)) return; foreach (var dir in Directory.GetDirectories(basePath)) { // only watch directories which house a csproj. this avoids submodules and directories like .git which can contain many files. if (!Directory.GetFiles(dir, "*.csproj").Any()) continue; validDirectories.Add(dir); var fsw = new FileSystemWatcher(dir, @"*.cs") { EnableRaisingEvents = true, IncludeSubdirectories = true, NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime, }; fsw.Changed += onChange; fsw.Created += onChange; watchers.Add(fsw); } }); } private void onChange(object sender, FileSystemEventArgs e) { lock (compileLock) { if (checkpointObject == null || isCompiling) return; var checkpointName = checkpointObject.GetType().Name; var reqTypes = checkpointObject.RequiredTypes.Select(t => t.Name).ToList(); // add ourselves as a required type. reqTypes.Add(checkpointName); // if we are a TestCase, add the class we are testing automatically. reqTypes.Add(checkpointName.Replace("TestCase", "")); if (!reqTypes.Contains(Path.GetFileNameWithoutExtension(e.Name))) return; if (!reqTypes.SequenceEqual(requiredTypeNames)) { requiredTypeNames = reqTypes; requiredFiles.Clear(); foreach (var d in validDirectories) requiredFiles.AddRange(Directory .EnumerateFiles(d, "*.cs", SearchOption.AllDirectories) .Where(fw => requiredTypeNames.Contains(Path.GetFileNameWithoutExtension(fw)))); } lastTouchedFile = e.FullPath; isCompiling = true; Task.Run((Action)recompile) .ContinueWith(_ => isCompiling = false); } } private int currentVersion; private bool isCompiling; private readonly object compileLock = new object(); private void recompile() { if (assemblies == null) { assemblies = new HashSet<string>(); foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic)) assemblies.Add(ass.Location); } var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var references = assemblies.Select(a => MetadataReference.CreateFromFile(a)); while (!checkFileReady(lastTouchedFile)) Thread.Sleep(10); Logger.Log($@"Recompiling {Path.GetFileName(checkpointObject.GetType().Name)}...", LoggingTarget.Runtime, LogLevel.Important); CompilationStarted?.Invoke(); // ensure we don't duplicate the dynamic suffix. string assemblyNamespace = checkpointObject.GetType().Assembly.GetName().Name.Replace(".Dynamic", ""); string assemblyVersion = $"{++currentVersion}.0.*"; string dynamicNamespace = $"{assemblyNamespace}.Dynamic"; var compilation = CSharpCompilation.Create( dynamicNamespace, requiredFiles.Select(file => CSharpSyntaxTree.ParseText(File.ReadAllText(file), null, file)) // Compile the assembly with a new version so that it replaces the existing one .Append(CSharpSyntaxTree.ParseText($"using System.Reflection; [assembly: AssemblyVersion(\"{assemblyVersion}\")]")) , references, options ); using (var ms = new MemoryStream()) { var compilationResult = compilation.Emit(ms); if (compilationResult.Success) { ms.Seek(0, SeekOrigin.Begin); CompilationFinished?.Invoke( Assembly.Load(ms.ToArray()).GetModules()[0]?.GetTypes().LastOrDefault(t => t.FullName == checkpointObject.GetType().FullName) ); } else { foreach (var diagnostic in compilationResult.Diagnostics) { if (diagnostic.Severity < DiagnosticSeverity.Error) continue; CompilationFailed?.Invoke(new Exception(diagnostic.ToString())); } } } } /// <summary> /// Check whether a file has finished being written to. /// </summary> private static bool checkFileReady(string filename) { try { using (FileStream inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None)) return inputStream.Length > 0; } catch (Exception) { return false; } } #region IDisposable Support private bool isDisposed; protected virtual void Dispose(bool disposing) { if (!isDisposed) { isDisposed = true; watchers.ForEach(w => w.Dispose()); } } ~DynamicClassCompiler() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Matching; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.AspNetCore.Routing.TestObjects; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.Builder { public class EndpointRoutingApplicationBuilderExtensionsTest { [Fact] public void UseRouting_ServicesNotRegistered_Throws() { // Arrange var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); // Act var ex = Assert.Throws<InvalidOperationException>(() => app.UseRouting()); // Assert Assert.Equal( "Unable to find the required services. " + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + "inside the call to 'ConfigureServices(...)' in the application startup code.", ex.Message); } [Fact] public void UseEndpoint_ServicesNotRegistered_Throws() { // Arrange var app = new ApplicationBuilder(Mock.Of<IServiceProvider>()); // Act var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); // Assert Assert.Equal( "Unable to find the required services. " + "Please add all the required services by calling 'IServiceCollection.AddRouting' " + "inside the call to 'ConfigureServices(...)' in the application startup code.", ex.Message); } [Fact] public async Task UseRouting_ServicesRegistered_NoMatch_DoesNotSetFeature() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); app.UseRouting(); var appFunc = app.Build(); var httpContext = new DefaultHttpContext(); // Act await appFunc(httpContext); // Assert Assert.Null(httpContext.Features.Get<IEndpointFeature>()); } [Fact] public async Task UseRouting_ServicesRegistered_Match_DoesNotSetsFeature() { // Arrange var endpoint = new RouteEndpoint( TestConstants.EmptyRequestDelegate, RoutePatternFactory.Parse("{*p}"), 0, EndpointMetadataCollection.Empty, "Test"); var services = CreateServices(); var app = new ApplicationBuilder(services); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.DataSources.Add(new DefaultEndpointDataSource(endpoint)); }); var appFunc = app.Build(); var httpContext = new DefaultHttpContext(); // Act await appFunc(httpContext); // Assert var feature = httpContext.Features.Get<IEndpointFeature>(); Assert.NotNull(feature); Assert.Same(endpoint, httpContext.GetEndpoint()); } [Fact] public void UseEndpoint_WithoutEndpointRoutingMiddleware_Throws() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); // Act var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); // Assert Assert.Equal( "EndpointRoutingMiddleware matches endpoints setup by EndpointMiddleware and so must be added to the request " + "execution pipeline before EndpointMiddleware. " + "Please add EndpointRoutingMiddleware by calling 'IApplicationBuilder.UseRouting' " + "inside the call to 'Configure(...)' in the application startup code.", ex.Message); } [Fact] public void UseEndpoint_WithApplicationBuilderMismatch_Throws() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); app.UseRouting(); // Act var ex = Assert.Throws<InvalidOperationException>(() => app.Map("/Test", b => b.UseEndpoints(endpoints => { }))); // Assert Assert.Equal( "The EndpointRoutingMiddleware and EndpointMiddleware must be added to the same IApplicationBuilder instance. " + "To use Endpoint Routing with 'Map(...)', make sure to call 'IApplicationBuilder.UseRouting' before " + "'IApplicationBuilder.UseEndpoints' for each branch of the middleware pipeline.", ex.Message); } [Fact] public async Task UseEndpoint_ServicesRegisteredAndEndpointRoutingRegistered_NoMatch_DoesNotSetFeature() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); app.UseRouting(); app.UseEndpoints(endpoints => { }); var appFunc = app.Build(); var httpContext = new DefaultHttpContext(); // Act await appFunc(httpContext); // Assert Assert.Null(httpContext.Features.Get<IEndpointFeature>()); } [Fact] public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource() { // Arrange var matcherEndpointDataSources = new List<EndpointDataSource>(); var matcherFactoryMock = new Mock<MatcherFactory>(); matcherFactoryMock .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) .Callback((EndpointDataSource arg) => { matcherEndpointDataSources.Add(arg); }) .Returns(new TestMatcher(false)); var services = CreateServices(matcherFactoryMock.Object); var app = new ApplicationBuilder(services); // Act app.UseRouting(); app.UseEndpoints(builder => { builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); }); app.UseRouting(); app.UseEndpoints(builder => { builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); }); // This triggers the middleware to be created and the matcher factory to be called // with the datasource we want to test var requestDelegate = app.Build(); requestDelegate(new DefaultHttpContext()); // Assert Assert.Equal(2, matcherEndpointDataSources.Count); // each UseRouter has its own data source collection Assert.Collection(matcherEndpointDataSources[0].Endpoints, e => Assert.Equal("Test endpoint 1", e.DisplayName), e => Assert.Equal("Test endpoint 2", e.DisplayName)); Assert.Collection(matcherEndpointDataSources[1].Endpoints, e => Assert.Equal("Test endpoint 3", e.DisplayName), e => Assert.Equal("Test endpoint 4", e.DisplayName)); var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); // Global collection has all endpoints Assert.Collection(compositeEndpointBuilder.Endpoints, e => Assert.Equal("Test endpoint 1", e.DisplayName), e => Assert.Equal("Test endpoint 2", e.DisplayName), e => Assert.Equal("Test endpoint 3", e.DisplayName), e => Assert.Equal("Test endpoint 4", e.DisplayName)); } // Verifies that it's possible to use endpoints and map together. [Fact] public void UseEndpoints_CallWithBuilder_SetsEndpointDataSource_WithMap() { // Arrange var matcherEndpointDataSources = new List<EndpointDataSource>(); var matcherFactoryMock = new Mock<MatcherFactory>(); matcherFactoryMock .Setup(m => m.CreateMatcher(It.IsAny<EndpointDataSource>())) .Callback((EndpointDataSource arg) => { matcherEndpointDataSources.Add(arg); }) .Returns(new TestMatcher(false)); var services = CreateServices(matcherFactoryMock.Object); var app = new ApplicationBuilder(services); // Act app.UseRouting(); app.Map("/foo", b => { b.UseRouting(); b.UseEndpoints(builder => { builder.Map("/1", d => null).WithDisplayName("Test endpoint 1"); builder.Map("/2", d => null).WithDisplayName("Test endpoint 2"); }); }); app.UseEndpoints(builder => { builder.Map("/3", d => null).WithDisplayName("Test endpoint 3"); builder.Map("/4", d => null).WithDisplayName("Test endpoint 4"); }); // This triggers the middleware to be created and the matcher factory to be called // with the datasource we want to test var requestDelegate = app.Build(); requestDelegate(new DefaultHttpContext()); requestDelegate(new DefaultHttpContext() { Request = { Path = "/Foo", }, }); // Assert Assert.Equal(2, matcherEndpointDataSources.Count); // Each UseRouter has its own data source Assert.Collection(matcherEndpointDataSources[1].Endpoints, // app.UseRouter e => Assert.Equal("Test endpoint 1", e.DisplayName), e => Assert.Equal("Test endpoint 2", e.DisplayName)); Assert.Collection(matcherEndpointDataSources[0].Endpoints, // b.UseRouter e => Assert.Equal("Test endpoint 3", e.DisplayName), e => Assert.Equal("Test endpoint 4", e.DisplayName)); var compositeEndpointBuilder = services.GetRequiredService<EndpointDataSource>(); // Global middleware has all endpoints Assert.Collection(compositeEndpointBuilder.Endpoints, e => Assert.Equal("Test endpoint 1", e.DisplayName), e => Assert.Equal("Test endpoint 2", e.DisplayName), e => Assert.Equal("Test endpoint 3", e.DisplayName), e => Assert.Equal("Test endpoint 4", e.DisplayName)); } [Fact] public void UseEndpoints_WithGlobalEndpointRouteBuilderHasRoutes() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); var mockRouteBuilder = new Mock<IEndpointRouteBuilder>(); mockRouteBuilder.Setup(m => m.DataSources).Returns(new List<EndpointDataSource>()); var routeBuilder = mockRouteBuilder.Object; app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.Map("/1", d => Task.CompletedTask).WithDisplayName("Test endpoint 1"); }); var requestDelegate = app.Build(); var endpointDataSource = Assert.Single(mockRouteBuilder.Object.DataSources); Assert.Collection(endpointDataSource.Endpoints, e => Assert.Equal("Test endpoint 1", e.DisplayName)); var routeOptions = app.ApplicationServices.GetRequiredService<IOptions<RouteOptions>>(); Assert.Equal(mockRouteBuilder.Object.DataSources, routeOptions.Value.EndpointDataSources); } [Fact] public void UseRouting_SetsEndpointRouteBuilder_IfGlobalOneExists() { // Arrange var services = CreateServices(); var app = new ApplicationBuilder(services); var routeBuilder = new Mock<IEndpointRouteBuilder>().Object; app.Properties.Add("__GlobalEndpointRouteBuilder", routeBuilder); app.UseRouting(); Assert.True(app.Properties.TryGetValue("__EndpointRouteBuilder", out var local)); Assert.True(app.Properties.TryGetValue("__GlobalEndpointRouteBuilder", out var global)); Assert.Same(local, global); } private IServiceProvider CreateServices() { return CreateServices(matcherFactory: null); } private IServiceProvider CreateServices(MatcherFactory matcherFactory) { var services = new ServiceCollection(); if (matcherFactory != null) { services.AddSingleton<MatcherFactory>(matcherFactory); } services.AddLogging(); services.AddOptions(); services.AddRouting(); var listener = new DiagnosticListener("Microsoft.AspNetCore"); services.AddSingleton(listener); services.AddSingleton<DiagnosticSource>(listener); var serviceProvder = services.BuildServiceProvider(); return serviceProvder; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using NUnit.Framework; using Newtonsoft.Json; using GlmSharp; // ReSharper disable InconsistentNaming namespace GlmSharpTest.Generated.Swizzle { [TestFixture] public class DoubleSwizzleVec2Test { [Test] public void XYZW() { { var ov = new dvec2(-7.5d, -8d); var v = ov.swizzle.xx; Assert.AreEqual(-7.5d, v.x); Assert.AreEqual(-7.5d, v.y); } { var ov = new dvec2(8d, 9d); var v = ov.swizzle.xxx; Assert.AreEqual(8d, v.x); Assert.AreEqual(8d, v.y); Assert.AreEqual(8d, v.z); } { var ov = new dvec2(-0.5d, 4d); var v = ov.swizzle.xxxx; Assert.AreEqual(-0.5d, v.x); Assert.AreEqual(-0.5d, v.y); Assert.AreEqual(-0.5d, v.z); Assert.AreEqual(-0.5d, v.w); } { var ov = new dvec2(7.5d, -2.5d); var v = ov.swizzle.xxxy; Assert.AreEqual(7.5d, v.x); Assert.AreEqual(7.5d, v.y); Assert.AreEqual(7.5d, v.z); Assert.AreEqual(-2.5d, v.w); } { var ov = new dvec2(1.5d, 6.5d); var v = ov.swizzle.xxy; Assert.AreEqual(1.5d, v.x); Assert.AreEqual(1.5d, v.y); Assert.AreEqual(6.5d, v.z); } { var ov = new dvec2(-9d, -5.5d); var v = ov.swizzle.xxyx; Assert.AreEqual(-9d, v.x); Assert.AreEqual(-9d, v.y); Assert.AreEqual(-5.5d, v.z); Assert.AreEqual(-9d, v.w); } { var ov = new dvec2(-7.5d, -9.5d); var v = ov.swizzle.xxyy; Assert.AreEqual(-7.5d, v.x); Assert.AreEqual(-7.5d, v.y); Assert.AreEqual(-9.5d, v.z); Assert.AreEqual(-9.5d, v.w); } { var ov = new dvec2(5d, -8d); var v = ov.swizzle.xy; Assert.AreEqual(5d, v.x); Assert.AreEqual(-8d, v.y); } { var ov = new dvec2(7.5d, -8.5d); var v = ov.swizzle.xyx; Assert.AreEqual(7.5d, v.x); Assert.AreEqual(-8.5d, v.y); Assert.AreEqual(7.5d, v.z); } { var ov = new dvec2(-8d, -9.5d); var v = ov.swizzle.xyxx; Assert.AreEqual(-8d, v.x); Assert.AreEqual(-9.5d, v.y); Assert.AreEqual(-8d, v.z); Assert.AreEqual(-8d, v.w); } { var ov = new dvec2(5.5d, -8.5d); var v = ov.swizzle.xyxy; Assert.AreEqual(5.5d, v.x); Assert.AreEqual(-8.5d, v.y); Assert.AreEqual(5.5d, v.z); Assert.AreEqual(-8.5d, v.w); } { var ov = new dvec2(-3d, 0.0); var v = ov.swizzle.xyy; Assert.AreEqual(-3d, v.x); Assert.AreEqual(0.0, v.y); Assert.AreEqual(0.0, v.z); } { var ov = new dvec2(9.5d, 3.5d); var v = ov.swizzle.xyyx; Assert.AreEqual(9.5d, v.x); Assert.AreEqual(3.5d, v.y); Assert.AreEqual(3.5d, v.z); Assert.AreEqual(9.5d, v.w); } { var ov = new dvec2(4.5d, 9d); var v = ov.swizzle.xyyy; Assert.AreEqual(4.5d, v.x); Assert.AreEqual(9d, v.y); Assert.AreEqual(9d, v.z); Assert.AreEqual(9d, v.w); } { var ov = new dvec2(1.0, -2.5d); var v = ov.swizzle.yx; Assert.AreEqual(-2.5d, v.x); Assert.AreEqual(1.0, v.y); } { var ov = new dvec2(6d, -7d); var v = ov.swizzle.yxx; Assert.AreEqual(-7d, v.x); Assert.AreEqual(6d, v.y); Assert.AreEqual(6d, v.z); } { var ov = new dvec2(-7.5d, -9.5d); var v = ov.swizzle.yxxx; Assert.AreEqual(-9.5d, v.x); Assert.AreEqual(-7.5d, v.y); Assert.AreEqual(-7.5d, v.z); Assert.AreEqual(-7.5d, v.w); } { var ov = new dvec2(-8d, -6.5d); var v = ov.swizzle.yxxy; Assert.AreEqual(-6.5d, v.x); Assert.AreEqual(-8d, v.y); Assert.AreEqual(-8d, v.z); Assert.AreEqual(-6.5d, v.w); } { var ov = new dvec2(3.5d, -4.5d); var v = ov.swizzle.yxy; Assert.AreEqual(-4.5d, v.x); Assert.AreEqual(3.5d, v.y); Assert.AreEqual(-4.5d, v.z); } { var ov = new dvec2(6.5d, 7d); var v = ov.swizzle.yxyx; Assert.AreEqual(7d, v.x); Assert.AreEqual(6.5d, v.y); Assert.AreEqual(7d, v.z); Assert.AreEqual(6.5d, v.w); } { var ov = new dvec2(-2d, 8d); var v = ov.swizzle.yxyy; Assert.AreEqual(8d, v.x); Assert.AreEqual(-2d, v.y); Assert.AreEqual(8d, v.z); Assert.AreEqual(8d, v.w); } { var ov = new dvec2(9.5d, 4d); var v = ov.swizzle.yy; Assert.AreEqual(4d, v.x); Assert.AreEqual(4d, v.y); } { var ov = new dvec2(-5.5d, 6.5d); var v = ov.swizzle.yyx; Assert.AreEqual(6.5d, v.x); Assert.AreEqual(6.5d, v.y); Assert.AreEqual(-5.5d, v.z); } { var ov = new dvec2(-6.5d, -2.5d); var v = ov.swizzle.yyxx; Assert.AreEqual(-2.5d, v.x); Assert.AreEqual(-2.5d, v.y); Assert.AreEqual(-6.5d, v.z); Assert.AreEqual(-6.5d, v.w); } { var ov = new dvec2(-6d, 1.5d); var v = ov.swizzle.yyxy; Assert.AreEqual(1.5d, v.x); Assert.AreEqual(1.5d, v.y); Assert.AreEqual(-6d, v.z); Assert.AreEqual(1.5d, v.w); } { var ov = new dvec2(-4d, -9.5d); var v = ov.swizzle.yyy; Assert.AreEqual(-9.5d, v.x); Assert.AreEqual(-9.5d, v.y); Assert.AreEqual(-9.5d, v.z); } { var ov = new dvec2(-4.5d, 4d); var v = ov.swizzle.yyyx; Assert.AreEqual(4d, v.x); Assert.AreEqual(4d, v.y); Assert.AreEqual(4d, v.z); Assert.AreEqual(-4.5d, v.w); } { var ov = new dvec2(-4.5d, 0.0); var v = ov.swizzle.yyyy; Assert.AreEqual(0.0, v.x); Assert.AreEqual(0.0, v.y); Assert.AreEqual(0.0, v.z); Assert.AreEqual(0.0, v.w); } } [Test] public void RGBA() { { var ov = new dvec2(-7.5d, -9.5d); var v = ov.swizzle.rr; Assert.AreEqual(-7.5d, v.x); Assert.AreEqual(-7.5d, v.y); } { var ov = new dvec2(-7d, 7.5d); var v = ov.swizzle.rrr; Assert.AreEqual(-7d, v.x); Assert.AreEqual(-7d, v.y); Assert.AreEqual(-7d, v.z); } { var ov = new dvec2(8d, -7d); var v = ov.swizzle.rrrr; Assert.AreEqual(8d, v.x); Assert.AreEqual(8d, v.y); Assert.AreEqual(8d, v.z); Assert.AreEqual(8d, v.w); } { var ov = new dvec2(-4d, 9.5d); var v = ov.swizzle.rrrg; Assert.AreEqual(-4d, v.x); Assert.AreEqual(-4d, v.y); Assert.AreEqual(-4d, v.z); Assert.AreEqual(9.5d, v.w); } { var ov = new dvec2(6d, 9.5d); var v = ov.swizzle.rrg; Assert.AreEqual(6d, v.x); Assert.AreEqual(6d, v.y); Assert.AreEqual(9.5d, v.z); } { var ov = new dvec2(6.5d, 1.5d); var v = ov.swizzle.rrgr; Assert.AreEqual(6.5d, v.x); Assert.AreEqual(6.5d, v.y); Assert.AreEqual(1.5d, v.z); Assert.AreEqual(6.5d, v.w); } { var ov = new dvec2(0.0, -8.5d); var v = ov.swizzle.rrgg; Assert.AreEqual(0.0, v.x); Assert.AreEqual(0.0, v.y); Assert.AreEqual(-8.5d, v.z); Assert.AreEqual(-8.5d, v.w); } { var ov = new dvec2(-6.5d, 5d); var v = ov.swizzle.rg; Assert.AreEqual(-6.5d, v.x); Assert.AreEqual(5d, v.y); } { var ov = new dvec2(3d, -1.5d); var v = ov.swizzle.rgr; Assert.AreEqual(3d, v.x); Assert.AreEqual(-1.5d, v.y); Assert.AreEqual(3d, v.z); } { var ov = new dvec2(1.5d, 5d); var v = ov.swizzle.rgrr; Assert.AreEqual(1.5d, v.x); Assert.AreEqual(5d, v.y); Assert.AreEqual(1.5d, v.z); Assert.AreEqual(1.5d, v.w); } { var ov = new dvec2(1.5d, 2.5d); var v = ov.swizzle.rgrg; Assert.AreEqual(1.5d, v.x); Assert.AreEqual(2.5d, v.y); Assert.AreEqual(1.5d, v.z); Assert.AreEqual(2.5d, v.w); } { var ov = new dvec2(-9.5d, 5d); var v = ov.swizzle.rgg; Assert.AreEqual(-9.5d, v.x); Assert.AreEqual(5d, v.y); Assert.AreEqual(5d, v.z); } { var ov = new dvec2(8d, -4d); var v = ov.swizzle.rggr; Assert.AreEqual(8d, v.x); Assert.AreEqual(-4d, v.y); Assert.AreEqual(-4d, v.z); Assert.AreEqual(8d, v.w); } { var ov = new dvec2(6d, 7d); var v = ov.swizzle.rggg; Assert.AreEqual(6d, v.x); Assert.AreEqual(7d, v.y); Assert.AreEqual(7d, v.z); Assert.AreEqual(7d, v.w); } { var ov = new dvec2(-5.5d, -4.5d); var v = ov.swizzle.gr; Assert.AreEqual(-4.5d, v.x); Assert.AreEqual(-5.5d, v.y); } { var ov = new dvec2(-6d, -4d); var v = ov.swizzle.grr; Assert.AreEqual(-4d, v.x); Assert.AreEqual(-6d, v.y); Assert.AreEqual(-6d, v.z); } { var ov = new dvec2(5.5d, 9d); var v = ov.swizzle.grrr; Assert.AreEqual(9d, v.x); Assert.AreEqual(5.5d, v.y); Assert.AreEqual(5.5d, v.z); Assert.AreEqual(5.5d, v.w); } { var ov = new dvec2(-5d, 4.5d); var v = ov.swizzle.grrg; Assert.AreEqual(4.5d, v.x); Assert.AreEqual(-5d, v.y); Assert.AreEqual(-5d, v.z); Assert.AreEqual(4.5d, v.w); } { var ov = new dvec2(-9d, -2.5d); var v = ov.swizzle.grg; Assert.AreEqual(-2.5d, v.x); Assert.AreEqual(-9d, v.y); Assert.AreEqual(-2.5d, v.z); } { var ov = new dvec2(4.5d, 0.5d); var v = ov.swizzle.grgr; Assert.AreEqual(0.5d, v.x); Assert.AreEqual(4.5d, v.y); Assert.AreEqual(0.5d, v.z); Assert.AreEqual(4.5d, v.w); } { var ov = new dvec2(-2d, 3.5d); var v = ov.swizzle.grgg; Assert.AreEqual(3.5d, v.x); Assert.AreEqual(-2d, v.y); Assert.AreEqual(3.5d, v.z); Assert.AreEqual(3.5d, v.w); } { var ov = new dvec2(-7.5d, 5.5d); var v = ov.swizzle.gg; Assert.AreEqual(5.5d, v.x); Assert.AreEqual(5.5d, v.y); } { var ov = new dvec2(3d, -7d); var v = ov.swizzle.ggr; Assert.AreEqual(-7d, v.x); Assert.AreEqual(-7d, v.y); Assert.AreEqual(3d, v.z); } { var ov = new dvec2(3.5d, -1.5d); var v = ov.swizzle.ggrr; Assert.AreEqual(-1.5d, v.x); Assert.AreEqual(-1.5d, v.y); Assert.AreEqual(3.5d, v.z); Assert.AreEqual(3.5d, v.w); } { var ov = new dvec2(3.5d, 8.5d); var v = ov.swizzle.ggrg; Assert.AreEqual(8.5d, v.x); Assert.AreEqual(8.5d, v.y); Assert.AreEqual(3.5d, v.z); Assert.AreEqual(8.5d, v.w); } { var ov = new dvec2(8.5d, -9.5d); var v = ov.swizzle.ggg; Assert.AreEqual(-9.5d, v.x); Assert.AreEqual(-9.5d, v.y); Assert.AreEqual(-9.5d, v.z); } { var ov = new dvec2(8d, 7d); var v = ov.swizzle.gggr; Assert.AreEqual(7d, v.x); Assert.AreEqual(7d, v.y); Assert.AreEqual(7d, v.z); Assert.AreEqual(8d, v.w); } { var ov = new dvec2(2d, 0.5d); var v = ov.swizzle.gggg; Assert.AreEqual(0.5d, v.x); Assert.AreEqual(0.5d, v.y); Assert.AreEqual(0.5d, v.z); Assert.AreEqual(0.5d, v.w); } } [Test] public void InlineXYZW() { { var v0 = new dvec2(5.5d, 8d); var v1 = new dvec2(-4.5d, 5.5d); var v2 = v0.xy; v0.xy = v1; var v3 = v0.xy; Assert.AreEqual(v1, v3); Assert.AreEqual(-4.5d, v0.x); Assert.AreEqual(5.5d, v0.y); Assert.AreEqual(5.5d, v2.x); Assert.AreEqual(8d, v2.y); } } [Test] public void InlineRGBA() { { var v0 = new dvec2(-4d, 2.5d); var v1 = 1.5d; var v2 = v0.r; v0.r = v1; var v3 = v0.r; Assert.AreEqual(v1, v3); Assert.AreEqual(1.5d, v0.x); Assert.AreEqual(2.5d, v0.y); Assert.AreEqual(-4d, v2); } { var v0 = new dvec2(9.5d, 2.5d); var v1 = 9d; var v2 = v0.g; v0.g = v1; var v3 = v0.g; Assert.AreEqual(v1, v3); Assert.AreEqual(9.5d, v0.x); Assert.AreEqual(9d, v0.y); Assert.AreEqual(2.5d, v2); } { var v0 = new dvec2(-7d, 3.5d); var v1 = new dvec2(-8.5d, 4.5d); var v2 = v0.rg; v0.rg = v1; var v3 = v0.rg; Assert.AreEqual(v1, v3); Assert.AreEqual(-8.5d, v0.x); Assert.AreEqual(4.5d, v0.y); Assert.AreEqual(-7d, v2.x); Assert.AreEqual(3.5d, v2.y); } } } }
#if UNITY_EDITOR using System.Collections.Generic; using UnityEditor; using UnityEngine; using UMA.Integrations; namespace UMA.Editors { /// <summary> /// Recipe editor. /// Class is marked partial so developers can add their own functionality to edit new properties added to /// UMATextRecipe without changing code delivered with UMA. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(UMARecipeBase), true)] public partial class RecipeEditor : CharacterBaseEditor { List<GameObject> draggedObjs; GameObject generatedContext; EditorWindow inspectorWindow; //for showing a warning if any of the compatible races are missing or not assigned to bundles or the index protected Texture warningIcon; protected GUIStyle warningStyle; public virtual void OnSceneDrag(SceneView view) { if (Event.current.type == EventType.DragUpdated) { if (Event.current.mousePosition.x < 0 || Event.current.mousePosition.x >= view.position.width || Event.current.mousePosition.y < 0 || Event.current.mousePosition.y >= view.position.height) return; DragAndDrop.visualMode = DragAndDropVisualMode.Copy; // show a drag-add icon on the mouse cursor Event.current.Use(); return; } if (Event.current.type == EventType.DragPerform) { if (Event.current.mousePosition.x < 0 || Event.current.mousePosition.x >= view.position.width || Event.current.mousePosition.y < 0 || Event.current.mousePosition.y >= view.position.height) return; Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hit; Vector3 position = Vector3.zero; if (Physics.Raycast(ray, out hit)) { position = hit.point; } var newSelection = new List<UnityEngine.Object>(DragAndDrop.objectReferences.Length); foreach (var reference in DragAndDrop.objectReferences) { if (reference is UMARecipeBase) { var avatarGO = CreateAvatar(reference as UMARecipeBase); avatarGO.GetComponent<Transform>().position = position; position.x = position.x + 1; newSelection.Add(avatarGO); } } Selection.objects = newSelection.ToArray(); DragAndDrop.visualMode = DragAndDropVisualMode.Copy; // show a drag-add icon on the mouse cursor Event.current.Use(); } } public virtual GameObject CreateAvatar(UMARecipeBase recipe) { var GO = new GameObject(recipe.name); var avatar = GO.AddComponent<UMADynamicAvatar>(); avatar.umaRecipe = recipe; avatar.loadOnStart = true; return GO; } public override void OnEnable() { base.OnEnable(); if (!NeedsReenable()) return; _errorMessage = null; _recipe = new UMAData.UMARecipe(); showBaseEditor = false; try { var umaRecipeBase = target as UMARecipeBase; if (umaRecipeBase != null) { var context = UMAContext.FindInstance(); //create a virtual UMAContext if we dont have one and we have DCS if (context == null || context.gameObject.name == "UMAEditorContext") { context = umaRecipeBase.CreateEditorContext();//will create or update an UMAEditorContext to the latest version generatedContext = context.gameObject.transform.parent.gameObject;//The UMAContext in a UMAEditorContext is that gameobject's child } //legacy checks for context if (context == null) { _errorMessage = "Editing a recipe requires a loaded scene with a valid UMAContext."; Debug.LogWarning(_errorMessage); //_recipe = null; //return; } else if (context.raceLibrary == null) { _errorMessage = "Editing a recipe requires a loaded scene with a valid UMAContext with RaceLibrary assigned."; Debug.LogWarning(_errorMessage); //_recipe = null; //return; } umaRecipeBase.Load(_recipe, context); _description = umaRecipeBase.GetInfo(); } } catch (UMAResourceNotFoundException e) { _errorMessage = e.Message; } dnaEditor = new DNAMasterEditor(_recipe); slotEditor = new SlotMasterEditor(_recipe); _rebuildOnLayout = true; } public void OnDestroy() { if (generatedContext != null) { //Ensure UMAContext.Instance is set to null UMAContext.Instance = null; DestroyImmediate(generatedContext); } } public override void OnInspectorGUI() { if (warningIcon == null) { warningIcon = EditorGUIUtility.FindTexture("console.warnicon.sml"); warningStyle = new GUIStyle(EditorStyles.label); warningStyle.fixedHeight = warningIcon.height + 4f; warningStyle.contentOffset = new Vector2(0, -2f); } if (_recipe == null) return; PowerToolsGUI(); base.OnInspectorGUI(); } protected override void DoUpdate() { var recipeBase = (UMARecipeBase)target; recipeBase.Save(_recipe, UMAContext.FindInstance()); EditorUtility.SetDirty(recipeBase); AssetDatabase.SaveAssets(); // AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(recipeBase)); _rebuildOnLayout = true; _needsUpdate = false; if (PowerToolsIntegration.HasPreview(recipeBase)) { PowerToolsIntegration.Refresh(recipeBase); } //else //{ // PowerToolsIntegration.Show(recipeBase); //} } protected override void Rebuild() { base.Rebuild(); var recipeBase = target as UMARecipeBase; if (PowerToolsIntegration.HasPowerTools() && PowerToolsIntegration.HasPreview(recipeBase)) { _needsUpdate = true; } } private void PowerToolsGUI() { if (PowerToolsIntegration.HasPowerTools()) { GUILayout.BeginHorizontal(); var recipeBase = target as UMARecipeBase; if (PowerToolsIntegration.HasPreview(recipeBase)) { if (GUILayout.Button("Hide")) { PowerToolsIntegration.Hide(recipeBase); } if (GUILayout.Button("Create Prefab")) { //PowerToolsIntegration.CreatePrefab(recipeBase); } if (GUILayout.Button("Hide All")) { PowerToolsIntegration.HideAll(); } } else { if (GUILayout.Button("Show")) { PowerToolsIntegration.Show(recipeBase); } if (GUILayout.Button("Create Prefab")) { //PowerToolsIntegration.CreatePrefab(recipeBase); } if (GUILayout.Button("Hide All")) { PowerToolsIntegration.HideAll(); } } GUILayout.EndHorizontal(); } } /// <summary> /// Checks if the given RaceData is in the globalLibrary or an assetBundle /// </summary> /// <param name="_raceData"></param> /// <returns></returns> protected bool RaceInIndex(RaceData _raceData) { if (UMAContext.Instance != null) { if (UMAContext.Instance.HasRace(_raceData.raceName) != null) return true; } AssetItem ai = UMAAssetIndexer.Instance.GetAssetItem<RaceData>(_raceData.raceName); if (ai != null) { return true; } string path = AssetDatabase.GetAssetPath(_raceData); if (UMAAssetIndexer.Instance.InAssetBundle(path)) { return true; } return false; } } /*public class ShowGatheringNotification : EditorWindow { string notification = "UMA is gathering Data"; void OnGUI() { this.ShowNotification(new GUIContent(notification)); } }*/ } #endif
// *********************************************************************** // Copyright (c) 2011 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. // *********************************************************************** using System; using System.IO; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using System.Reflection; using NUnit.Common; using NUnit.Engine.Internal; namespace NUnit.Engine.Services { /// <summary> /// Enumeration used to report AgentStatus /// </summary> public enum AgentStatus { Unknown, Starting, Ready, Busy, Stopping } /// <summary> /// The TestAgency class provides RemoteTestAgents /// on request and tracks their status. Agents /// are wrapped in an instance of the TestAgent /// class. Multiple agent types are supported /// but only one, ProcessAgent is implemented /// at this time. /// </summary> public class TestAgency : ServerBase, ITestAgency, IService { static Logger log = InternalTrace.GetLogger(typeof(TestAgency)); #region Private Fields private AgentDataBase _agentData = new AgentDataBase(); private IRuntimeFrameworkService _runtimeService; #endregion #region Constructors public TestAgency() : this( "TestAgency", 0 ) { } public TestAgency( string uri, int port ) : base( uri, port ) { } #endregion #region ServerBase Overrides //public override void Stop() //{ // foreach( KeyValuePair<Guid,AgentRecord> pair in agentData ) // { // AgentRecord r = pair.Value; // if ( !r.Process.HasExited ) // { // if ( r.Agent != null ) // { // r.Agent.Stop(); // r.Process.WaitForExit(10000); // } // if ( !r.Process.HasExited ) // r.Process.Kill(); // } // } // agentData.Clear(); // base.Stop (); //} #endregion #region Public Methods - Called by Agents public void Register( ITestAgent agent ) { AgentRecord r = _agentData[agent.Id]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agent.Id), "agentId"); r.Agent = agent; } public void ReportStatus( Guid agentId, AgentStatus status ) { AgentRecord r = _agentData[agentId]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agentId), "agentId" ); r.Status = status; } #endregion #region Public Methods - Called by Clients public ITestAgent GetAgent(TestPackage package, int waitTime) { // TODO: Decide if we should reuse agents //AgentRecord r = FindAvailableRemoteAgent(type); //if ( r == null ) // r = CreateRemoteAgent(type, framework, waitTime); return CreateRemoteAgent(package, waitTime); } public void ReleaseAgent( ITestAgent agent ) { AgentRecord r = _agentData[agent.Id]; if (r == null) log.Error(string.Format("Unable to release agent {0} - not in database", agent.Id)); else { r.Status = AgentStatus.Ready; log.Debug("Releasing agent " + agent.Id.ToString()); } } //public void DestroyAgent( ITestAgent agent ) //{ // AgentRecord r = agentData[agent.Id]; // if ( r != null ) // { // if( !r.Process.HasExited ) // r.Agent.Stop(); // agentData[r.Id] = null; // } //} #endregion #region Helper Methods private Guid LaunchAgentProcess(TestPackage package) { string runtimeSetting = package.GetSetting(PackageSettings.RuntimeFramework, ""); RuntimeFramework targetRuntime = RuntimeFramework.Parse( runtimeSetting != "" ? runtimeSetting : _runtimeService.SelectRuntimeFramework(package)); if (targetRuntime.Runtime == RuntimeType.Any) targetRuntime = new RuntimeFramework(RuntimeFramework.CurrentFramework.Runtime, targetRuntime.ClrVersion); bool useX86Agent = package.GetSetting(PackageSettings.RunAsX86, false); bool debugTests = package.GetSetting(PackageSettings.DebugTests, false); bool debugAgent = package.GetSetting(PackageSettings.DebugAgent, false); bool verbose = package.GetSetting("Verbose", false); string agentArgs = string.Empty; if (debugAgent) agentArgs += " --debug-agent"; if (verbose) agentArgs += " --verbose"; log.Info("Getting {0} agent for use under {1}", useX86Agent ? "x86" : "standard", targetRuntime); if (!targetRuntime.IsAvailable) throw new ArgumentException( string.Format("The {0} framework is not available", targetRuntime), "framework"); string agentExePath = GetTestAgentExePath(targetRuntime.ClrVersion, useX86Agent); if (agentExePath == null) throw new ArgumentException( string.Format("NUnit components for version {0} of the CLR are not installed", targetRuntime.ClrVersion.ToString()), "targetRuntime"); log.Debug("Using nunit-agent at " + agentExePath); Process p = new Process(); p.StartInfo.UseShellExecute = false; Guid agentId = Guid.NewGuid(); string arglist = agentId.ToString() + " " + ServerUrl + " " + agentArgs; switch( targetRuntime.Runtime ) { case RuntimeType.Mono: p.StartInfo.FileName = NUnitConfiguration.MonoExePath; string monoOptions = "--runtime=v" + targetRuntime.ClrVersion.ToString(3); if (debugTests || debugAgent) monoOptions += " --debug"; p.StartInfo.Arguments = string.Format("{0} \"{1}\" {2}", monoOptions, agentExePath, arglist); break; case RuntimeType.Net: p.StartInfo.FileName = agentExePath; if (targetRuntime.ClrVersion.Build < 0) targetRuntime = RuntimeFramework.GetBestAvailableFramework(targetRuntime); string envVar = "v" + targetRuntime.ClrVersion.ToString(3); p.StartInfo.EnvironmentVariables["COMPLUS_Version"] = envVar; p.StartInfo.Arguments = arglist; break; default: p.StartInfo.FileName = agentExePath; p.StartInfo.Arguments = arglist; break; } //p.Exited += new EventHandler(OnProcessExit); p.Start(); log.Info("Launched Agent process {0} - see nunit-agent_{0}.log", p.Id); log.Info("Command line: \"{0}\" {1}", p.StartInfo.FileName, p.StartInfo.Arguments); _agentData.Add( new AgentRecord( agentId, p, null, AgentStatus.Starting ) ); return agentId; } //private void OnProcessExit(object sender, EventArgs e) //{ // Process p = sender as Process; // if (p != null) // agentData.Remove(p.Id); //} //private AgentRecord FindAvailableAgent() //{ // foreach( AgentRecord r in agentData ) // if ( r.Status == AgentStatus.Ready) // { // log.Debug( "Reusing agent {0}", r.Id ); // r.Status = AgentStatus.Busy; // return r; // } // return null; //} private ITestAgent CreateRemoteAgent(TestPackage package, int waitTime) { Guid agentId = LaunchAgentProcess(package); log.Debug( "Waiting for agent {0} to register", agentId.ToString("B") ); int pollTime = 200; bool infinite = waitTime == Timeout.Infinite; while( infinite || waitTime > 0 ) { Thread.Sleep( pollTime ); if ( !infinite ) waitTime -= pollTime; ITestAgent agent = _agentData[agentId].Agent; if ( agent != null ) { log.Debug( "Returning new agent {0}", agentId.ToString("B") ); return agent; } } return null; } /// <summary> /// Return the NUnit Bin Directory for a particular /// runtime version, or null if it's not installed. /// For normal installations, there are only 1.1 and /// 2.0 directories. However, this method accommodates /// 3.5 and 4.0 directories for the benefit of NUnit /// developers using those runtimes. /// </summary> private static string GetNUnitBinDirectory(Version v) { // Get current bin directory string dir = NUnitConfiguration.NUnitBinDirectory; // Return current directory if current and requested // versions are both >= 2 or both 1 if ((Environment.Version.Major >= 2) == (v.Major >= 2)) return dir; // Check whether special support for version 1 is installed if (v.Major == 1) { string altDir = Path.Combine(dir, "net-1.1"); if (Directory.Exists(altDir)) return altDir; // The following is only applicable to the dev environment, // which uses parallel build directories. We try to substitute // one version number for another in the path. string[] search = new string[] { "2.0", "3.0", "3.5", "4.0" }; string[] replace = v.Minor == 0 ? new string[] { "1.0", "1.1" } : new string[] { "1.1", "1.0" }; // Look for current value in path so it can be replaced string current = null; foreach (string s in search) if (dir.IndexOf(s) >= 0) { current = s; break; } // Try the substitution if (current != null) { foreach (string target in replace) { altDir = dir.Replace(current, target); if (Directory.Exists(altDir)) return altDir; } } } return null; } private static string GetTestAgentExePath(Version v, bool requires32Bit) { string binDir = NUnitConfiguration.NUnitBinDirectory; if (binDir == null) return null; string agentName = v.Major > 1 && requires32Bit ? "nunit-agent-x86.exe" : "nunit-agent.exe"; string agentExePath = Path.Combine(binDir, agentName); return File.Exists(agentExePath) ? agentExePath : null; } #endregion #region IService Members public ServiceContext ServiceContext { get; set; } public ServiceStatus Status { get; private set; } public void StopService() { try { Stop(); } finally { Status = ServiceStatus.Stopped; } } public void StartService() { try { // TestAgency requires on the RuntimeFrameworkService. _runtimeService = ServiceContext.GetService<IRuntimeFrameworkService>(); // Any object returned from ServiceContext is an IService if (_runtimeService != null && ((IService)_runtimeService).Status == ServiceStatus.Started) { try { Start(); Status = ServiceStatus.Started; } catch { Status = ServiceStatus.Error; throw; } } else { Status = ServiceStatus.Error; } } catch { Status = ServiceStatus.Error; throw; } } #endregion #region Nested Class - AgentRecord private class AgentRecord { public Guid Id; public Process Process; public ITestAgent Agent; public AgentStatus Status; public AgentRecord( Guid id, Process p, ITestAgent a, AgentStatus s ) { this.Id = id; this.Process = p; this.Agent = a; this.Status = s; } } #endregion #region Nested Class - AgentDataBase /// <summary> /// A simple class that tracks data about this /// agencies active and available agents /// </summary> private class AgentDataBase { private Dictionary<Guid, AgentRecord> agentData = new Dictionary<Guid, AgentRecord>(); public AgentRecord this[Guid id] { get { return agentData[id]; } set { if ( value == null ) agentData.Remove( id ); else agentData[id] = value; } } public AgentRecord this[ITestAgent agent] { get { foreach( KeyValuePair<Guid, AgentRecord> entry in agentData) { AgentRecord r = entry.Value; if ( r.Agent == agent ) return r; } return null; } } public void Add( AgentRecord r ) { agentData[r.Id] = r; } public void Remove(Guid agentId) { agentData.Remove(agentId); } public void Clear() { agentData.Clear(); } //#region IEnumerable Members //public IEnumerator<KeyValuePair<Guid,AgentRecord>> GetEnumerator() //{ // return agentData.GetEnumerator(); //} //#endregion } #endregion } }
namespace AngleSharp.Core.Tests.Html { using AngleSharp.Dom; using AngleSharp.Html.Dom; using NUnit.Framework; /// <summary> /// Tests generated according to the W3C-Test.org page: /// http://www.w3c-test.org/html/semantics/forms/constraints/form-validation-checkValidity.html /// </summary> [TestFixture] public class ValidityCheckTests { [Test] public void GetSubmissionReturnsNullWithInvalidForm() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.SetAttribute("maxLength", "4"); element.Value = "abcde"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; Assert.IsNotNull(fm); fm.AppendChild(element); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); Assert.IsNull(fm.GetSubmission(element)); } [Test] public void TestCheckvalidityInputText1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputText4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "text"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("text", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputSearch4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "search"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("search", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTel4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "tel"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("tel", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "4"); element.Value = "abcdef"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "[A-Z]"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputPassword4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "password"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("password", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "20"); element.Value = "http://www.example.com"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "http://www.example.com"); element.Value = "http://www.example.net"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputUrl5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "url"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("url", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("maxLength", "10"); element.Value = "test@example.com"; element.IsDirty = true; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true) as HtmlInputElement; fm.AppendChild(element2); document.Body.AppendChild(fm); element2.IsDirty = true; Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("pattern", "test@example.com"); element.Value = "test@example.net"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.Value = "abc"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputEmail5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "email"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("email", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01T12:00:00Z"); element.Value = "2001-01-01T12:00:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01-01T12:00:00Z"); element.Value = "2000-01-01T12:00:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "2001-01-01T12:03:00Z"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDatetime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "datetime"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("datetime", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01-01"); element.Value = "2001-01-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01-01"); element.Value = "2000-01-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "172800000"); element.Value = "2001-01-03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputDate5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "date"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("date", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-01"); element.Value = "2001-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-01"); element.Value = "2000-01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "3"); element.Value = "2001-03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputMonth5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "month"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("month", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "2000-W01"); element.Value = "2001-W01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "2001-W01"); element.Value = "2000-W01"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "1209600000"); element.Value = "2001-W03"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputWeek5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "week"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("week", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "12:00:00"); element.Value = "13:00:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "12:00:00"); element.Value = "11:00:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "120000"); element.Value = "12:03:00"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputTime5() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "time"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("time", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("max", "5"); element.Value = "6"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("min", "5"); element.Value = "4"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber3() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("step", "2"); element.Value = "3"; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputNumber4() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "number"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("number", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputCheckbox1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "checkbox"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("checkbox", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputCheckbox2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "checkbox"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("checked", null); element.SetAttribute("name", "test1"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("checkbox", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputRadio1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "radio"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("radio", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputRadio2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "radio"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("checked", null); element.SetAttribute("name", "test1"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("radio", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputFile1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "file"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("file", element.Type); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityInputFile2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("input") as HtmlInputElement; Assert.IsNotNull(element); element.Type = "file"; element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.SetAttribute("files", "null"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual("file", element.Type); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvaliditySelect1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("select") as HtmlSelectElement; Assert.IsNotNull(element); var option1 = document.CreateElement<IHtmlOptionElement>(); option1.Text = "test1"; option1.Value = ""; var option2 = document.CreateElement<IHtmlOptionElement>(); option2.Text = "test1"; option2.Value = "1"; element.AddOption(option1); element.AddOption(option2); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvaliditySelect2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("select") as HtmlSelectElement; Assert.IsNotNull(element); var option1 = document.CreateElement<IHtmlOptionElement>(); option1.Text = "test1"; option1.Value = ""; var option2 = document.CreateElement<IHtmlOptionElement>(); option2.Text = "test1"; option2.Value = "1"; element.AddOption(option1); element.AddOption(option2); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } [Test] public void TestCheckvalidityTextarea1() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("textarea") as HtmlTextAreaElement; Assert.IsNotNull(element); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(true, element.CheckValidity()); Assert.AreEqual(true, fm.CheckValidity()); } [Test] public void TestCheckvalidityTextarea2() { var document = ("").ToHtmlDocument(); var element = document.CreateElement("textarea") as HtmlTextAreaElement; Assert.IsNotNull(element); element.RemoveAttribute("required"); element.RemoveAttribute("pattern"); element.RemoveAttribute("step"); element.RemoveAttribute("max"); element.RemoveAttribute("min"); element.RemoveAttribute("maxlength"); element.RemoveAttribute("value"); element.RemoveAttribute("multiple"); element.RemoveAttribute("checked"); element.RemoveAttribute("selected"); element.SetAttribute("required", "required"); element.Value = ""; var fm = document.CreateElement("form") as IHtmlFormElement; var element2 = element.Clone(true); fm.AppendChild(element2); document.Body.AppendChild(fm); Assert.AreEqual(false, element.CheckValidity()); Assert.AreEqual(false, fm.CheckValidity()); } } }
/* Copyright (c) 2004-2006 Tomas Matousek and Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Web; //using System.Web.SessionState; using System.Text; using System.Threading; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections; //using System.Collections.Specialized; using System.Collections.Generic; using System.Reflection.Emit; using System.Runtime.InteropServices; using System.Runtime.Remoting.Messaging; using System.ComponentModel; using PHP.Core.Emit; using PHP.Core.Reflection; using System.Configuration; namespace PHP.Core { /// <summary> /// The context of an executing script. Contains data associated with a request. /// </summary> [DebuggerTypeProxy(typeof(ScriptContext.DebugView))] public sealed partial class ScriptContext : ILogicalThreadAffinative { #region Initialization of requests and applications /// <summary> /// Initializes the script context for a web request. /// </summary> /// <param name="appContext">Application context.</param> /// <param name="context">HTTP context of the request.</param> /// <returns>A instance of <see cref="ScriptContext"/> to be used by the request.</returns> /// <exception cref="System.Configuration.ConfigurationErrorsException"> /// Web configuration is invalid. The context is not initialized then. /// </exception> internal static ScriptContext/*!*/ InitWebRequest(ApplicationContext/*!*/ appContext, HttpContext/*!*/ context) { Debug.Assert(appContext != null && context != null); // reloads configuration of the current thread from ASP.NET caches or web.config files; // cached configuration is reused; Configuration.Reload(appContext, false); // takes a writable copy of a global configuration (may throw ConfigurationErrorsException): LocalConfiguration config = (LocalConfiguration)Configuration.DefaultLocal.DeepCopy(); // following initialization statements shouldn't throw an exception: // can throw on Integrated Pipeline, events must be attached within HttpApplication.Init() ScriptContext result = new ScriptContext(appContext, config, context.Response.Output, context.Response.OutputStream); result.IsOutputBuffered = config.OutputControl.OutputBuffering; result.ThrowExceptionOnError = true; result.WorkingDirectory = Path.GetDirectoryName(context.Request.PhysicalPath); if (config.OutputControl.ContentType != null) context.Response.ContentType = config.OutputControl.ContentType; if (config.OutputControl.CharSet != null) context.Response.Charset = config.OutputControl.CharSet; result.AutoGlobals.Initialize(config, context); ScriptContext.CurrentContext = result; return result; } /// <summary> /// Creates a new script context and runs the application in it. For internal use only. /// </summary> /// <param name="mainRoutine">The script's main helper routine.</param> /// <param name="relativeSourcePath">A path to the main script source file.</param> /// <param name="sourceRoot">A source root within which an application has been compiler.</param> [Emitted, EditorBrowsable(EditorBrowsableState.Never)] public static void RunApplication(Delegate/*!*/ mainRoutine, string relativeSourcePath, string sourceRoot) { bool is_pure = mainRoutine is RoutineDelegate; ApplicationContext app_context = ApplicationContext.Default; // default culture: Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; // try to preload configuration (to prevent exceptions during InitApplication: try { Configuration.Load(app_context); } catch (ConfigurationErrorsException e) { Console.WriteLine(e.Message); return; } ApplicationConfiguration app_config = Configuration.Application; if (is_pure && !app_config.Compiler.LanguageFeaturesSet) app_config.Compiler.LanguageFeatures = LanguageFeatures.PureModeDefault; Type main_script; if (is_pure) { // loads the calling assembly: app_context.AssemblyLoader.Load(mainRoutine.Method.Module.Assembly, null); main_script = null; } else { main_script = mainRoutine.Method.DeclaringType; app_context.AssemblyLoader.LoadScriptLibrary(System.Reflection.Assembly.GetEntryAssembly(), "."); } using (ScriptContext context = InitApplication(app_context, main_script, relativeSourcePath, sourceRoot)) { context.GuardedCall<object, object>(context.GuardedMain, mainRoutine, true); } } /// <summary> /// Initializes the script context for a PHP console application. /// </summary> /// <param name="appContext">Application context.</param> /// <param name="mainScript">The main script's type or a <B>null</B> reference for a pure application.</param> /// <param name="relativeSourcePath">A path to the main script source file.</param> /// <param name="sourceRoot">A source root within which an application has been compiler.</param> /// <returns> /// A new instance of <see cref="ScriptContext"/> with its own copy of local configuration /// to be used by the application. /// </returns> /// <exception cref="System.Configuration.ConfigurationErrorsException"> /// Web configuration is invalid. The context is not initialized then. /// </exception> /// <remarks> /// Use this method if you want to initialize application in the same way the PHP console/Windows /// application is initialized. The returned script context is initialized as follows: /// <list type="bullet"> /// <term>The application's source root is set.</term> /// <term>The main script of the application is defined.</term> /// <term>Output and input streams are set to standard output and input, respectively.</term> /// <term>Current culture it set to <see cref="CultureInfo.InvariantCulture"/>.</term> /// <term>Auto-global variables ($_GET, $_SET, etc.) are initialized.</term> /// <term>Working directory is set tothe current working directory.</term> /// </list> /// </remarks> public static ScriptContext/*!*/ InitApplication(ApplicationContext/*!*/ appContext, Type mainScript, string relativeSourcePath, string sourceRoot) { // loads configuration into the given application context // (applies only if the config has not been loaded yet by the current thread): Configuration.Load(appContext); ApplicationConfiguration app_config = Configuration.Application; if (mainScript != null) { if (relativeSourcePath == null) throw new ArgumentNullException("relativeSourcePath"); if (sourceRoot == null) throw new ArgumentNullException("sourceRoot"); // overrides source root configuration if not explicitly specified in config file: if (!app_config.Compiler.SourceRootSet) app_config.Compiler.SourceRoot = new FullPath(sourceRoot); } // takes a writable copy of a global configuration: LocalConfiguration config = (LocalConfiguration)Configuration.DefaultLocal.DeepCopy(); // sets invariant culture as a default one: Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; ScriptContext result = new ScriptContext(appContext, config, Console.Out, Console.OpenStandardOutput()); result.IsOutputBuffered = result.config.OutputControl.OutputBuffering; result.AutoGlobals.Initialize(config, null); result.WorkingDirectory = Directory.GetCurrentDirectory(); result.ThrowExceptionOnError = true; result.config.ErrorControl.HtmlMessages = false; if (mainScript != null) { // converts relative path of the script source to full canonical path using source root from the configuration: PhpSourceFile main_source_file = new PhpSourceFile( app_config.Compiler.SourceRoot, new FullPath(relativeSourcePath, app_config.Compiler.SourceRoot) ); result.DefineMainScript(new ScriptInfo(mainScript), main_source_file); } ScriptContext.CurrentContext = result; // return result; } #region InitContext /// <summary> /// Initializes <see cref="ScriptContext"/> for the C#/PHP interoperability. /// </summary> /// <param name="appContext">Application context.</param> /// <returns>New <see cref="ScriptContext"/></returns> /// <remarks> /// Use this method if you want to initialize application in the same way the PHP console/Windows /// application is initialized. CurrentContext is set, and initialized to simulate request begin and end. /// </remarks> public static ScriptContext/*!*/InitContext(ApplicationContext appContext) { if (appContext == null) appContext = ApplicationContext.Default; var context = InitApplication(appContext, null, null, null); // simulate request lifecycle RequestContext.InvokeRequestBegin(); context.FinallyDispose += RequestContext.InvokeRequestEnd; // return context; } /// <summary> /// Initializes <see cref="ScriptContext"/> for the C#/PHP interoperability. /// </summary> /// <param name="appContext">Application context.</param> /// <param name="output">Output stream.</param> /// <returns>New <see cref="ScriptContext"/></returns> /// <remarks> /// Use this method if you want to initialize application in the same way the PHP console/Windows /// application is initialized. CurrentContext is set, and initialized to simulate request begin and end. /// </remarks> public static ScriptContext/*!*/InitContext(ApplicationContext appContext, Stream output) { var context = InitContext(appContext); // setups output if (output == null) output = Stream.Null; context.OutputStream = output; context.Output = new StreamWriter(output); return context; } #endregion #endregion #region Constants private void InitConstants(DualDictionary<string, object> _constants) { // Thease constants are here, because they are environment dependent // When the code is compiled and assembly is run on another platforms they could be different _constants.Add("PHALANGER", PhalangerVersion.Current, false); _constants.Add("PHP_VERSION", PhpVersion.Current, false); _constants.Add("PHP_MAJOR_VERSION", PhpVersion.Major, false); _constants.Add("PHP_MINOR_VERSION", PhpVersion.Minor, false); _constants.Add("PHP_RELEASE_VERSION", PhpVersion.Release, false); _constants.Add("PHP_VERSION_ID", PhpVersion.Major * 10000 + PhpVersion.Minor * 100 + PhpVersion.Release, false); _constants.Add("PHP_EXTRA_VERSION", PhpVersion.Extra, false); _constants.Add("PHP_OS", Environment.OSVersion.Platform == PlatformID.Win32NT ? "WINNT" : "WIN32", false); // TODO: GENERICS (Unix) _constants.Add("PHP_SAPI", (System.Web.HttpContext.Current == null) ? "cli" : "isapi", false); _constants.Add("DIRECTORY_SEPARATOR", FullPath.DirectorySeparatorString, false); _constants.Add("PATH_SEPARATOR", Path.PathSeparator.ToString(), false); //TODO: should be specified elsewhere (app context??) _constants.Add("PHP_EOL", System.Environment.NewLine, false); //TODO: this is a bit pesimistic, as this value is a bit higher on Vista and on other filesystems and OSes // sadly .NET does not specify value of MAXPATH constant _constants.Add("PHP_MAXPATHLEN", 255, false); if (HttpContext.Current == null) { _constants.Add("STDIN", InputOutputStreamWrapper.In, false); _constants.Add("STDOUT", InputOutputStreamWrapper.Out, false); _constants.Add("STDERR", InputOutputStreamWrapper.Error, false); } } #endregion #region Current Context /// <summary> /// Call context name for the current <see cref="ScriptContext"/>. /// </summary> private const string callContextSlotName = "PhpNet:ScriptContext"; /// <summary> /// The instance of <see cref="ScriptContext"/> associated with the current logical thread. /// </summary> /// <remarks> /// If no instance is associated with the current logical thread /// a new one is created, added to call context and returned. /// The slot allocated by some instance is freed /// by setting this property to a <B>null</B> reference. /// </remarks> [DebuggerNonUserCode] public static ScriptContext CurrentContext { [Emitted] get { // try to get script context from call context: // ScriptContext is ILogicalThreadAffinative, LogicalCallContext is used. try { return ((ScriptContext)CallContext.GetData(callContextSlotName)) ?? CreateDefaultScriptContext(); // on Mono, .GetData must be used (GetLogicalData is not implemented) } catch (InvalidCastException) { throw new InvalidCallContextDataException(callContextSlotName); } //return result.AttachToHttpApplication(); } set { if (value == null) CallContext.FreeNamedDataSlot(callContextSlotName); else CallContext.SetData(callContextSlotName, value); // on Mono, .SetData must be used (SetLogicalData is not implemented) } } /// <summary> /// Initialize new ScriptContext and store it into the LogicalCallContext. /// </summary> /// <returns>Newly created ScriptContext.</returns> private static ScriptContext CreateDefaultScriptContext() { ScriptContext result; HttpContext context; if ((context = HttpContext.Current) != null) result = RequestContext.Initialize(ApplicationContext.Default, context).ScriptContext; else result = new ScriptContext(ApplicationContext.Default); ScriptContext.CurrentContext = result; return result; } #endregion #region Variables public PhpArray/*!*/ SessionVariables { get { PhpArray result = AutoGlobals.Session.Value as PhpArray; if (result == null) AutoGlobals.Session.Value = result = new PhpArray(); return result; } } #endregion #region Inclusions /// <summary> /// Includes a specific script using current configuration. /// </summary> /// <param name="relativeSourcePath">Source root relative path to the script.</param> /// <param name="once">Specifies whether script should be included only once.</param> /// <returns>The value returned by the global code of the target script.</returns> public object Include(string/*!*/ relativeSourcePath, bool once) { ApplicationConfiguration app_config = Configuration.Application; // searches for file: FullPath included_full_path = SearchForIncludedFile(PhpError.Error, relativeSourcePath, FullPath.Empty); if (included_full_path.IsEmpty) return false; ScriptInfo info; bool already_included = scripts.TryGetValue(included_full_path.ToString(), out info); // skips inclusion if script has already been included and inclusion's type is "once": if (already_included) { if(once) return ScriptModule.SkippedIncludeReturnValue; // script type loaded, info cannot be null } else { PhpSourceFile included_source_file = new PhpSourceFile(app_config.Compiler.SourceRoot, included_full_path); // loads script type: info = LoadDynamicScriptType(included_source_file); // script not found: if (info == null) return false; if (MainScriptFile == null) // the first script becomes the main one: DefineMainScript(info, included_source_file); else // adds included file into the script list scripts.Add(included_full_path.ToString(), info); } Debug.Assert(info != null); return GuardedCall((ScriptInfo scriptInfo) => { //return PhpScript.InvokeMainHelper( // (Type)scriptType, return scriptInfo.Main( this, null, // no local variables null, // no object context null, // no class context true); }, info, true); } /// <summary> /// Performs PHP inclusion on a specified script. /// </summary> /// <param name="relativeSourcePath"> /// Path to the target script source file relative to the application source root /// (see <c>Configuration.Application.Compiler.SourceRoot</c>. /// </param> /// <param name="script"> /// Script type (i.e. type called <c>Default</c> representing the target script) or any type from /// the assembly where the target script is contained (useful for multi-script assemblies, where script types are /// not directly available from C# as they have mangled names). In the latter case, the script type is searched in the /// assembly using value of <paramref name="relativeSourcePath"/>. /// </param> /// <returns>The value returned by the global code of the target script.</returns> /// <remarks> /// <para> /// The inclusion inheres in adding the target to the list of included scripts on the current script context /// (see <c>ScriptContext.Scripts</c> and in a call to the global code of the target script. /// </para> /// </remarks> /// <exception cref="InvalidOperationException">Request context has been disposed.</exception> /// <exception cref="ArgumentNullException"><paramref name="relativeSourcePath"/> or <paramref name="script"/> are <B>null</B> references.</exception> /// <exception cref="ArgumentException">Script type cannot be resolved.</exception> /// <exception cref="InvalidScriptAssemblyException">The target assembly is not a valid Phalanger compiled assembly.</exception> internal object IncludeScript(string/*!*/ relativeSourcePath, ScriptInfo/*!*/ script) { //if (type == null) // throw new ArgumentNullException("type"); if (relativeSourcePath == null) throw new ArgumentNullException("relativeSourcePath"); if (script == null) throw new ArgumentException("script"); FullPath source_root = Configuration.Application.Compiler.SourceRoot; PhpSourceFile source_file = new PhpSourceFile( new FullPath(source_root), new FullPath(Path.Combine(source_root, relativeSourcePath))); // the first script becomes the main one: if (MainScriptFile == null) DefineMainScript(script, source_file); return GuardedCall((ScriptInfo scriptInfo) => { //return PhpScript.InvokeMainHelper( // (Type)scriptType, return scriptInfo.Main( this, null, // no local variables null, // no object context null, // no class context true); }, script, true); } ///// <summary> ///// Resolves the script type using the given <see cref="ApplicationContext"/>. ///// </summary> //private static Type ResolveScriptType(ApplicationContext/*!*/ applicationContext, PhpSourceFile/*!*/ sourceFile, Type/*!*/ type) //{ // if (PhpScript.IsScriptType(type)) // return type; // ScriptAssembly sa = ScriptAssembly.LoadFromAssembly(applicationContext, type.Assembly); // return sa.GetScriptType(sourceFile); //} /// <summary> /// Called in place where a script is statically included. For internal purposes only. /// </summary> /// <param name="level">RelativePath.level; <paramref name="relativeSourcePath"/>.</param> /// <param name="relativeSourcePath">RelativePath.path; A path to the included script's source file relative to source root.</param> /// <param name="includee">A type handle of the included script.</param> /// <param name="inclusionType">A type of an inclusion.</param> /// <returns>Whether to process inclusion. If <B>false</B>, inclusion should be ignored.</returns> [Emitted, EditorBrowsable(EditorBrowsableState.Never)] public bool StaticInclude(int level, string relativeSourcePath, RuntimeTypeHandle includee, InclusionTypes inclusionType) { ApplicationConfiguration app_config = Configuration.Application; var included_full_path = //PhpSourceFile source_file = new PhpSourceFile( // app_config.Compiler.SourceRoot, new FullPath(app_config.Compiler.SourceRoot, new RelativePath((sbyte)level, relativeSourcePath)); //); if (scripts.ContainsKey(included_full_path.ToString())) { // the script has been included => returns whether it should be included again: return !InclusionTypesEnum.IsOnceInclusion(inclusionType); } else { // the script has not been included yet: scripts.Add(included_full_path.ToString(), new ScriptInfo(Type.GetTypeFromHandle(includee))); // the script should be included: return true; } } /// <summary> /// Called in place where a script is dynamically included. For internal purposes only. /// </summary> /// <param name="includedFilePath">A source path to the included script.</param> /// <param name="includerFileRelPath">A source path to the script issuing the inclusion relative to the source root.</param> /// <param name="variables">A run-time variables table.</param> /// <param name="self">A current object in which method an include is called (if applicable).</param> /// <param name="includer">A current class type desc in which method an include is called (if applicable).</param> /// <param name="inclusionType">A type of an inclusion.</param> /// <returns>A result of the Main() method call.</returns> [Emitted, EditorBrowsable(EditorBrowsableState.Never)] public object DynamicInclude( string includedFilePath, string includerFileRelPath, Dictionary<string, object> variables, DObject self, DTypeDesc includer, InclusionTypes inclusionType) { ApplicationConfiguration app_config = Configuration.Application; // determines inclusion behavior: FullPath includer_full_path = new FullPath(includerFileRelPath, app_config.Compiler.SourceRoot); // searches for file: FullPath included_full_path = SearchForIncludedFile( InclusionTypesEnum.IsMustInclusion(inclusionType) ? PhpError.Error : PhpError.Warning, includedFilePath, includer_full_path); if (included_full_path.IsEmpty) return false; ScriptInfo info; bool already_included = scripts.TryGetValue(included_full_path.ToString(), out info); // skips inclusion if script has already been included and inclusion's type is "once": if (already_included && InclusionTypesEnum.IsOnceInclusion(inclusionType)) return ScriptModule.SkippedIncludeReturnValue; if (!already_included) { // loads script type: info = LoadDynamicScriptType(new PhpSourceFile(app_config.Compiler.SourceRoot, included_full_path)); // script not found: if (info == null) return false; // adds included file into the script list scripts.Add(included_full_path.ToString(), info/* = new ScriptInfo(script)*/); } return info.Main(this, variables, self, includer, false); } /// <summary> /// Searches for a file in the script library, current directory, included paths, and web application root respectively. /// </summary> /// <param name="errorSeverity">A severity of an error (if occures).</param> /// <param name="includedPath">A source path to the included script.</param> /// <param name="includerFullPath">Full source path to the including script.</param> /// <returns>Full path to the file or <B>null</B> path if not found.</returns> private FullPath SearchForIncludedFile(PhpError errorSeverity, string includedPath, FullPath includerFullPath) { FullPath result; string message; // // construct the delegate checking the script existance // var file_exists = applicationContext.BuildFileExistsDelegate(); // // try to find the script // if (file_exists != null) { string includer_directory = includerFullPath.IsEmpty ? WorkingDirectory : Path.GetDirectoryName(includerFullPath); // searches for file in the following order: // - incomplete absolute path => combines with RootOf(WorkingDirectory) // - relative path => searches in FileSystem.IncludePaths then in the includer source directory result = PhpScript.FindInclusionTargetPath( new InclusionResolutionContext( applicationContext, includer_directory, WorkingDirectory, config.FileSystem.IncludePaths ), includedPath, file_exists, out message); } else { message = "Script cannot be included with current configuration."; // there is no precompiled MSA available on non-web application result = FullPath.Empty; } // failure: if (result.IsEmpty) { PhpException.Throw(errorSeverity, CoreResources.GetString("script_inclusion_failed", includedPath, message, config.FileSystem.IncludePaths, WorkingDirectory)); } return result; } /// <summary> /// Loads a script type dynamically. /// </summary> /// <param name="sourceFile">Script's source file.</param> private ScriptInfo LoadDynamicScriptType(PhpSourceFile/*!*/ sourceFile) { Debug.WriteLine("SC", "LoadDynamicScriptType: '{0}'", sourceFile); // runtime compiler manages: // - 1. script library // - 2. optionally bin/WebPages.dll // - 3. compiles file from file system if allowed return this.ApplicationContext.RuntimeCompilerManager.GetCompiledScript(sourceFile, RequestContext.CurrentContext); } #endregion #region Platform Dependent /// <summary> /// Stores HttpHeaders locally so PHP apps can change them (by default you can't change value /// of already set http header, but this is possible in PHP) /// </summary> private HttpHeaders httpHeaders; public HttpHeaders Headers { get { return httpHeaders; } } void InitPlatformSpecific() { // HTTP headers implementation this.httpHeaders = HttpHeaders.Create(); } #endregion #region Session Handling /// <summary> /// Adds session variables aliases to global variables. /// </summary> public void RegisterSessionGlobals() { PhpArray globals, session; // do not create session variables table if not exists: if ((session = PhpReference.AsPhpArray(AutoGlobals.Session)) == null) return; // creates globals array if it doesn't exists: globals = GlobalVariables; // iterates using unbreakable enumerator: foreach (KeyValuePair<IntStringKey, object> entry in session) { PhpReference php_ref = entry.Value as PhpReference; // converts the session variable to a reference if it is not one ("no duplicate pointers" rule preserved): if (php_ref == null) session[entry.Key] = php_ref = new PhpReference(entry.Value); // adds alias to the globals: globals[entry.Key] = php_ref; } } #endregion } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Flag Types. /// </summary> [RoutePrefix("api/v1.0/config/flag-type")] public class FlagTypeController : FrapidApiController { /// <summary> /// The FlagType repository. /// </summary> private readonly IFlagTypeRepository FlagTypeRepository; public FlagTypeController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.FlagTypeRepository = new Frapid.Config.DataAccess.FlagType { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public FlagTypeController(IFlagTypeRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.FlagTypeRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Creates meta information of "flag type" entity. /// </summary> /// <returns>Returns the "flag type" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/flag-type/meta")] [Authorize] public EntityView GetEntityView() { if (this._LoginId == 0) { return new EntityView(); } return new EntityView { PrimaryKey = "flag_type_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "flag_type_id", PropertyName = "FlagTypeId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = true, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "flag_type_name", PropertyName = "FlagTypeName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 24 }, new EntityColumn { ColumnName = "background_color", PropertyName = "BackgroundColor", DataType = "string", DbDataType = "color", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "foreground_color", PropertyName = "ForegroundColor", DataType = "string", DbDataType = "color", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_user_id", PropertyName = "AuditUserId", DataType = "int", DbDataType = "int4", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "audit_ts", PropertyName = "AuditTs", DataType = "DateTime", DbDataType = "timestamptz", IsNullable = true, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 0 } } }; } /// <summary> /// Counts the number of flag types. /// </summary> /// <returns>Returns the count of the flag types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/flag-type/count")] [Authorize] public long Count() { try { return this.FlagTypeRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of flag type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/flag-type/all")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> GetAll() { try { return this.FlagTypeRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of flag type for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/flag-type/export")] [Authorize] public IEnumerable<dynamic> Export() { try { return this.FlagTypeRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of flag type. /// </summary> /// <param name="flagTypeId">Enter FlagTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{flagTypeId}")] [Route("~/api/config/flag-type/{flagTypeId}")] [Authorize] public Frapid.Config.Entities.FlagType Get(int flagTypeId) { try { return this.FlagTypeRepository.Get(flagTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/flag-type/get")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> Get([FromUri] int[] flagTypeIds) { try { return this.FlagTypeRepository.Get(flagTypeIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of flag type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/flag-type/first")] [Authorize] public Frapid.Config.Entities.FlagType GetFirst() { try { return this.FlagTypeRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of flag type. /// </summary> /// <param name="flagTypeId">Enter FlagTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{flagTypeId}")] [Route("~/api/config/flag-type/previous/{flagTypeId}")] [Authorize] public Frapid.Config.Entities.FlagType GetPrevious(int flagTypeId) { try { return this.FlagTypeRepository.GetPrevious(flagTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of flag type. /// </summary> /// <param name="flagTypeId">Enter FlagTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{flagTypeId}")] [Route("~/api/config/flag-type/next/{flagTypeId}")] [Authorize] public Frapid.Config.Entities.FlagType GetNext(int flagTypeId) { try { return this.FlagTypeRepository.GetNext(flagTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of flag type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/flag-type/last")] [Authorize] public Frapid.Config.Entities.FlagType GetLast() { try { return this.FlagTypeRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flag types on each page, sorted by the property FlagTypeId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/flag-type")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> GetPaginatedResult() { try { return this.FlagTypeRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flag types on each page, sorted by the property FlagTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/flag-type/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> GetPaginatedResult(long pageNumber) { try { return this.FlagTypeRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flag types using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered flag types.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/flag-type/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagTypeRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flag types on each page, sorted by the property FlagTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/flag-type/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagTypeRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flag types using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered flag types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/flag-type/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.FlagTypeRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flag types on each page, sorted by the property FlagTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/flag-type/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.Config.Entities.FlagType> GetFiltered(long pageNumber, string filterName) { try { return this.FlagTypeRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of flag types. /// </summary> /// <returns>Returns an enumerable key/value collection of flag types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/flag-type/display-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.FlagTypeRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for flag types. /// </summary> /// <returns>Returns an enumerable custom field collection of flag types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/flag-type/custom-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.FlagTypeRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for flag types. /// </summary> /// <returns>Returns an enumerable custom field collection of flag types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/flag-type/custom-fields/{resourceId}")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.FlagTypeRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of FlagType class. /// </summary> /// <param name="flagType">Your instance of flag types class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/flag-type/add-or-edit")] [Authorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic flagType = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (flagType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.FlagTypeRepository.AddOrEdit(flagType, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of FlagType class. /// </summary> /// <param name="flagType">Your instance of flag types class to add.</param> [AcceptVerbs("POST")] [Route("add/{flagType}")] [Route("~/api/config/flag-type/add/{flagType}")] [Authorize] public void Add(Frapid.Config.Entities.FlagType flagType) { if (flagType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.FlagTypeRepository.Add(flagType); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of FlagType class. /// </summary> /// <param name="flagType">Your instance of FlagType class to edit.</param> /// <param name="flagTypeId">Enter the value for FlagTypeId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{flagTypeId}")] [Route("~/api/config/flag-type/edit/{flagTypeId}")] [Authorize] public void Edit(int flagTypeId, [FromBody] Frapid.Config.Entities.FlagType flagType) { if (flagType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.FlagTypeRepository.Update(flagType, flagTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of FlagType class. /// </summary> /// <param name="collection">Your collection of FlagType class to bulk import.</param> /// <returns>Returns list of imported flagTypeIds.</returns> /// <exception cref="DataAccessException">Thrown when your any FlagType class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/flag-type/bulk-import")] [Authorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> flagTypeCollection = this.ParseCollection(collection); if (flagTypeCollection == null || flagTypeCollection.Count.Equals(0)) { return null; } try { return this.FlagTypeRepository.BulkImport(flagTypeCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of FlagType class via FlagTypeId. /// </summary> /// <param name="flagTypeId">Enter the value for FlagTypeId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{flagTypeId}")] [Route("~/api/config/flag-type/delete/{flagTypeId}")] [Authorize] public void Delete(int flagTypeId) { try { this.FlagTypeRepository.Delete(flagTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_UpdateTests { [Fact] public static async Task UpdateReadNormal() { ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")), ZipTest.zfolder("normal"), ZipArchiveMode.Update, false, false); ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("fake64.zip")), ZipTest.zfolder("small"), ZipArchiveMode.Update, false, false); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("unicode.zip")), ZipTest.zfolder("unicode"), ZipArchiveMode.Update, false, false); } ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("empty.zip")), ZipTest.zfolder("empty"), ZipArchiveMode.Update, false, false); ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("appended.zip")), ZipTest.zfolder("small"), ZipArchiveMode.Update, false, false); ZipTest.IsZipSameAsDir( await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("prepended.zip")), ZipTest.zfolder("small"), ZipArchiveMode.Update, false, false); } [Fact] public static async Task UpdateReadTwice() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("small.zip")), ZipArchiveMode.Update)) { ZipArchiveEntry entry = archive.Entries[0]; String contents1, contents2; using (StreamReader s = new StreamReader(entry.Open())) { contents1 = s.ReadToEnd(); } using (StreamReader s = new StreamReader(entry.Open())) { contents2 = s.ReadToEnd(); } Assert.Equal(contents1, contents2); } } [Fact] public static async Task UpdateCreate() { await testFolder("normal"); await testFolder("empty"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { await testFolder("unicode"); } } public static async Task testFolder(String s) { var zs = new LocalMemoryStream(); await ZipTest.CreateFromDir(ZipTest.zfolder(s), zs, ZipArchiveMode.Update); ZipTest.IsZipSameAsDir(zs.Clone(), ZipTest.zfolder(s), ZipArchiveMode.Read, false, false); } [Fact] public static void UpdateEmptyEntry() { ZipTest.EmptyEntryTest(ZipArchiveMode.Update); } [Fact] public static async Task UpdateModifications() { //delete and move var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { ZipArchiveEntry toBeDeleted = archive.GetEntry("binary.wmv"); toBeDeleted.Delete(); toBeDeleted.Delete(); //delete twice should be okay ZipArchiveEntry moved = archive.CreateEntry("notempty/secondnewname.txt"); ZipArchiveEntry orig = archive.GetEntry("notempty/second.txt"); using (Stream origMoved = orig.Open(), movedStream = moved.Open()) { origMoved.CopyTo(movedStream); } moved.LastWriteTime = orig.LastWriteTime; orig.Delete(); } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("deleteMove"), ZipArchiveMode.Read, false, false); //append testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { ZipArchiveEntry e = archive.GetEntry("first.txt"); using (StreamWriter s = new StreamWriter(e.Open())) { s.BaseStream.Seek(0, SeekOrigin.End); s.Write("\r\n\r\nThe answer my friend, is blowin' in the wind."); } e.LastWriteTime = new DateTimeOffset(2010, 7, 7, 11, 57, 18, new TimeSpan(-7, 0, 0)); } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("append"), ZipArchiveMode.Read, false, false); //Overwrite file testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { String fileName = ZipTest.zmodified(Path.Combine("overwrite", "first.txt")); ZipArchiveEntry e = archive.GetEntry("first.txt"); var file = FileData.GetFile(fileName); e.LastWriteTime = file.LastModifiedDate; using (var stream = await StreamHelpers.CreateTempCopyStream(fileName)) { using (Stream es = e.Open()) { es.SetLength(0); stream.CopyTo(es); } } } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("overwrite"), ZipArchiveMode.Read, false, false); } [Fact] public static async Task UpdateAddFile() { //add file var testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt"); } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified ("addFile"), ZipArchiveMode.Read, false, false); //add file and read entries before testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { var x = archive.Entries; await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt"); } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false); //add file and read entries after testArchive = await StreamHelpers.CreateTempCopyStream(ZipTest.zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(testArchive, ZipArchiveMode.Update, true)) { await updateArchive(archive, ZipTest.zmodified(Path.Combine("addFile", "added.txt")), "added.txt"); var x = archive.Entries; } ZipTest.IsZipSameAsDir(testArchive, ZipTest.zmodified("addFile"), ZipArchiveMode.Read, false, false); } private static async Task updateArchive(ZipArchive archive, String installFile, String entryName) { String fileName = installFile; ZipArchiveEntry e = archive.CreateEntry(entryName); var file = FileData.GetFile(fileName); e.LastWriteTime = file.LastModifiedDate; using (var stream = await StreamHelpers.CreateTempCopyStream(fileName)) { using (Stream es = e.Open()) { es.SetLength(0); stream.CopyTo(es); } } } [Fact] public static async Task UpdateModeInvalidOperations() { using (LocalMemoryStream ms = await LocalMemoryStream.readAppFileAsync(ZipTest.zfile("normal.zip"))) { ZipArchive target = new ZipArchive(ms, ZipArchiveMode.Update, true); ZipArchiveEntry edeleted = target.GetEntry("first.txt"); Stream s = edeleted.Open(); //invalid ops while entry open Assert.Throws<IOException>(() => edeleted.Open()); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; }); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; }); Assert.Throws<IOException>(() => edeleted.Delete()); s.Dispose(); //invalid ops on stream after entry closed Assert.Throws<ObjectDisposedException>(() => s.ReadByte()); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.Length; }); Assert.Throws<InvalidOperationException>(() => { var x = edeleted.CompressedLength; }); edeleted.Delete(); //invalid ops while entry deleted Assert.Throws<InvalidOperationException>(() => edeleted.Open()); Assert.Throws<InvalidOperationException>(() => { edeleted.LastWriteTime = new DateTimeOffset(); }); ZipArchiveEntry e = target.GetEntry("notempty/second.txt"); target.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = target.Entries; }); Assert.Throws<ObjectDisposedException>(() => target.CreateEntry("dirka")); Assert.Throws<ObjectDisposedException>(() => e.Open()); Assert.Throws<ObjectDisposedException>(() => e.Delete()); Assert.Throws<ObjectDisposedException>(() => { e.LastWriteTime = new DateTimeOffset(); }); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Internal; using System.Text.Unicode; #if NETCOREAPP using System.Numerics; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; #endif namespace System.Text.Encodings.Web { internal sealed class DefaultJavaScriptEncoderBasicLatin : JavaScriptEncoder { internal static readonly DefaultJavaScriptEncoderBasicLatin s_singleton = new DefaultJavaScriptEncoderBasicLatin(); private DefaultJavaScriptEncoderBasicLatin() { var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin); AllowedCharactersBitmap allowedCharacters = filter.GetAllowedCharacters(); // Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed // (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp) allowedCharacters.ForbidUndefinedCharacters(); // Forbid characters that are special in HTML. // Even though this is a not HTML encoder, // it's unfortunately common for developers to // forget to HTML-encode a string once it has been JS-encoded, // so this offers extra protection. DefaultHtmlEncoder.ForbidHtmlCharacters(allowedCharacters); // '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON. // '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped. allowedCharacters.ForbidCharacter('\\'); // '`' (U+0060 GRAVE ACCENT) is ECMAScript-sensitive (see ECMA-262). allowedCharacters.ForbidCharacter('`'); #if DEBUG // Verify and ensure that the AllowList bit map matches the set of allowed characters using AllowedCharactersBitmap for (int i = 0; i < AllowList.Length; i++) { char ch = (char)i; Debug.Assert((allowedCharacters.IsCharacterAllowed(ch) ? 1 : 0) == AllowList[ch]); Debug.Assert(allowedCharacters.IsCharacterAllowed(ch) == !NeedsEscaping(ch)); } for (int i = AllowList.Length; i <= char.MaxValue; i++) { char ch = (char)i; Debug.Assert(!allowedCharacters.IsCharacterAllowed(ch)); Debug.Assert(NeedsEscaping(ch)); } #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { return true; } Debug.Assert(unicodeScalar >= char.MinValue && unicodeScalar <= char.MaxValue); return NeedsEscaping((char)unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override unsafe int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException(nameof(text)); } int idx = 0; #if NETCOREAPP if (Sse2.IsSupported) { short* startingAddress = (short*)text; while (textLength - 8 >= idx) { Debug.Assert(startingAddress >= text && startingAddress <= (text + textLength - 8)); // Load the next 8 characters. Vector128<short> sourceValue = Sse2.LoadVector128(startingAddress); // Check if any of the 8 characters need to be escaped. Vector128<short> mask = Sse2Helper.CreateEscapingMask_DefaultJavaScriptEncoderBasicLatin(sourceValue); int index = Sse2.MoveMask(mask.AsByte()); // If index == 0, that means none of the 8 characters needed to be escaped. // TrailingZeroCount is relatively expensive, avoid it if possible. if (index != 0) { // Found at least one character that needs to be escaped, figure out the index of // the first one found that needed to be escaped within the 8 characters. Debug.Assert(index > 0 && index <= 65_535); int tzc = BitOperations.TrailingZeroCount(index); Debug.Assert(tzc % 2 == 0 && tzc >= 0 && tzc <= 16); idx += tzc >> 1; goto Return; } idx += 8; startingAddress += 8; } // Process the remaining characters. Debug.Assert(textLength - idx < 8); } #endif for (; idx < textLength; idx++) { Debug.Assert((text + idx) <= (text + textLength)); if (NeedsEscaping(*(text + idx))) { goto Return; } } idx = -1; // All characters are allowed. Return: return idx; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override unsafe int FindFirstCharacterToEncodeUtf8(ReadOnlySpan<byte> utf8Text) { fixed (byte* ptr = utf8Text) { int idx = 0; #if NETCOREAPP if (Sse2.IsSupported) { sbyte* startingAddress = (sbyte*)ptr; while (utf8Text.Length - 16 >= idx) { Debug.Assert(startingAddress >= ptr && startingAddress <= (ptr + utf8Text.Length - 16)); // Load the next 16 bytes. Vector128<sbyte> sourceValue = Sse2.LoadVector128(startingAddress); // Check if any of the 16 bytes need to be escaped. Vector128<sbyte> mask = Sse2Helper.CreateEscapingMask_DefaultJavaScriptEncoderBasicLatin(sourceValue); int index = Sse2.MoveMask(mask); // If index == 0, that means none of the 16 bytes needed to be escaped. // TrailingZeroCount is relatively expensive, avoid it if possible. if (index != 0) { // Found at least one byte that needs to be escaped, figure out the index of // the first one found that needed to be escaped within the 16 bytes. int tzc = BitOperations.TrailingZeroCount(index); Debug.Assert(tzc >= 0 && tzc <= 16); idx += tzc; goto Return; } idx += 16; startingAddress += 16; } // Process the remaining bytes. Debug.Assert(utf8Text.Length - idx < 16); } #endif for (; idx < utf8Text.Length; idx++) { Debug.Assert((ptr + idx) <= (ptr + utf8Text.Length)); if (NeedsEscaping(*(ptr + idx))) { goto Return; } } idx = -1; // All bytes are allowed. Return: return idx; } } // The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF" // We don't need to worry about astral code points since they're represented as encoded // surrogate pairs in the output. public override int MaxOutputCharactersPerInputCharacter => 12; // "\uFFFF\uFFFF" is the longest encoded form private static readonly char[] s_b = new char[] { '\\', 'b' }; private static readonly char[] s_t = new char[] { '\\', 't' }; private static readonly char[] s_n = new char[] { '\\', 'n' }; private static readonly char[] s_f = new char[] { '\\', 'f' }; private static readonly char[] s_r = new char[] { '\\', 'r' }; private static readonly char[] s_back = new char[] { '\\', '\\' }; // Writes a scalar value as a JavaScript-escaped character (or sequence of characters). // See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9 // http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 // http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf public override unsafe bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not. // Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/" // (in ECMA-262 this character is a NonEscape character); however, we // don't encode SOLIDUS by default unless the caller has provided an // explicit bitmap which does not contain it. In this case we'll assume // that the caller didn't want a SOLIDUS written to the output at all, // so it should be written using "\u002F" encoding. // HTML-specific characters (including apostrophe and quotes) will // be written out as numeric entities for defense-in-depth. // See UnicodeEncoderBase ctor comments for more info. if (!WillEncode(unicodeScalar)) { return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] toCopy; switch (unicodeScalar) { case '\b': toCopy = s_b; break; case '\t': toCopy = s_t; break; case '\n': toCopy = s_n; break; case '\f': toCopy = s_f; break; case '\r': toCopy = s_r; break; case '\\': toCopy = s_back; break; default: return JavaScriptEncoderHelper.TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten); } private static ReadOnlySpan<byte> AllowList => new byte[byte.MaxValue + 1] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U+0000..U+000F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U+0010..U+001F 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, // U+0020..U+002F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, // U+0030..U+003F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // U+0040..U+004F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // U+0050..U+005F 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // U+0060..U+006F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // U+0070..U+007F // Also include the ranges from U+0080 to U+00FF for performance to avoid UTF8 code from checking boundary. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // U+00F0..U+00FF }; public const int LastAsciiCharacter = 0x7F; private static bool NeedsEscaping(byte value) => AllowList[value] == 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool NeedsEscaping(char value) => value > LastAsciiCharacter || AllowList[value] == 0; } }
using System; using AppUtil; using Vim25Api; namespace CreateStorageDRS { ///<summary> ///This sample demonstrates how to create Storage DRSgroup ///</summary> ///<param name="dcname">Required: Datacenter name</param> ///<param name="sdrsname">Required: Name for the new storage pod</param> ///<param name="behavior">Optional: Storage DRS behavior, true if automated. It is manual by default.</param> ///<param name="iolatencythreshold">Optional: IO Latency threshold</param> ///<param name="spacethreshold">Optional :Space threshold</param> ///<param name="utilizationdiff">Optional: Storage DRS considers making storage migration /// recommendations if the difference in space utilization between the source and /// destination datastores is higher than the specified threshold.</param> ///<param name="ioloadimbalancethreshold">Optional : IO Load Imbalance threshold</param> ///<param name="loadbalinterval">Optional :Interval that storage DRS run to load balance</param> ///<param name="datastore">Optional :Name of datastore</param> ///Create Storage DRS ///--url [webserviceurl] ///--username [username] --password [password] ///--dcname [dcname] --sdrsname [sdrsname] --behavior [behavior] --iolatencythreshold [iolatencythreshold] /// --spacethreshold[spacethreshold] --utilizationdiff[utilizationdiff] /// --ioloadimbalancethreshold[ioloadimbalancethreshold] /// --loadbalinterval [loadbalinterval] --datastore[datastore] ///</remarks> public class CreateStorageDRS { private static AppUtil.AppUtil cb = null; static string ioLatencythreshold = null; static string spaceUtilizationThreshold = null; static string ioLoadImbalanceThreshold = null; static string minSpaceUtilizationDifference = null; /// <summary> /// Method to create Storage DRSgroup /// </summary> private void CreateSDRS() { string dcName = cb.get_option("dcname"); string drsname = cb.get_option("sdrsname"); string behavior = cb.get_option("behavior"); string loadBalanceInterval = cb.get_option("loadbalinterval"); string dsname = cb.get_option("datastore"); ManagedObjectReference storagePod = new ManagedObjectReference(); ManagedObjectReference storageResourceManager = cb._connection._sic.storageResourceManager; ManagedObjectReference dcmor = cb._svcUtil.getEntityByName("Datacenter",dcName); if (dcmor != null) { ManagedObjectReference datastoreFolder = cb.getServiceUtil().GetMoRefProp (dcmor, "datastoreFolder"); storagePod = cb.getConnection()._service.CreateStoragePod(datastoreFolder, drsname); Console.WriteLine("Success: Creating storagePod."); StorageDrsConfigSpec sdrsConfigSpec = GetStorageDrsConfigSpec(behavior, loadBalanceInterval); ManagedObjectReference taskmor = cb.getConnection()._service.ConfigureStorageDrsForPod_Task(storageResourceManager, storagePod, sdrsConfigSpec, true); if (taskmor != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("Sucessfully configured storage pod" + drsname); } else { Console.WriteLine("Failure: Configuring storagePod"); throw new Exception(status); } } if (dsname != null) { ManagedObjectReference dsMoref = cb._svcUtil.getEntityByName("Datastore", dsname); if (dsMoref != null) { ManagedObjectReference[] dslist = new ManagedObjectReference[] { dsMoref }; ManagedObjectReference task = cb.getConnection()._service. MoveIntoFolder_Task(storagePod, dslist); if (task != null) { String status = cb.getServiceUtil().WaitForTask( taskmor); if (status.Equals("sucess")) { Console.WriteLine("\nSuccess: Adding datastore to storagePod."); } else { Console.WriteLine("Failure: Adding datastore to storagePod."); throw new Exception(status); } } } else { throw new Exception("Datastore" + dsname + "not found"); } } } else { throw new Exception("datacenter" + dcName + "not found"); } } /// <summary> /// Create Object of StorageDrsConfigSpec /// </summary> /// <param name="behavior">string</param> /// <param name="loadBalanceInterval">string</param> /// <returns></returns> private StorageDrsConfigSpec GetStorageDrsConfigSpec(string behavior, string loadBalanceInterval) { StorageDrsConfigSpec sdrsConfigSpec = new StorageDrsConfigSpec(); StorageDrsPodConfigSpec podConfigSpec = new StorageDrsPodConfigSpec(); if (behavior.Equals("true")) { podConfigSpec.defaultVmBehavior = "automated"; } else { podConfigSpec.defaultVmBehavior = "manual"; } podConfigSpec.defaultIntraVmAffinity = true; podConfigSpec.defaultIntraVmAffinitySpecified = true; podConfigSpec.enabled = true; podConfigSpec.enabledSpecified = true; StorageDrsIoLoadBalanceConfig sdrsIoLoadBalanceConfig = new StorageDrsIoLoadBalanceConfig(); if (ioLatencythreshold != null) { sdrsIoLoadBalanceConfig.ioLatencyThreshold = int.Parse(ioLatencythreshold); sdrsIoLoadBalanceConfig.ioLatencyThresholdSpecified = true; } if (ioLoadImbalanceThreshold != null) { sdrsIoLoadBalanceConfig.ioLoadImbalanceThreshold = int.Parse(ioLoadImbalanceThreshold); sdrsIoLoadBalanceConfig.ioLoadImbalanceThresholdSpecified = true; } podConfigSpec.ioLoadBalanceConfig = sdrsIoLoadBalanceConfig; podConfigSpec.ioLoadBalanceEnabled = true; podConfigSpec.ioLoadBalanceEnabledSpecified = true; if (loadBalanceInterval != null) { podConfigSpec.loadBalanceInterval = int.Parse(loadBalanceInterval); podConfigSpec.loadBalanceIntervalSpecified = true; } StorageDrsSpaceLoadBalanceConfig sdrsSpaceLoadBalanceConfig = new StorageDrsSpaceLoadBalanceConfig(); if (spaceUtilizationThreshold != null) { sdrsSpaceLoadBalanceConfig.spaceUtilizationThreshold = int.Parse(spaceUtilizationThreshold); sdrsSpaceLoadBalanceConfig.spaceUtilizationThresholdSpecified = true; } if (minSpaceUtilizationDifference != null) { sdrsSpaceLoadBalanceConfig.minSpaceUtilizationDifference = int.Parse(minSpaceUtilizationDifference); sdrsSpaceLoadBalanceConfig.minSpaceUtilizationDifferenceSpecified = true; } podConfigSpec.spaceLoadBalanceConfig = sdrsSpaceLoadBalanceConfig; sdrsConfigSpec.podConfigSpec = podConfigSpec; return sdrsConfigSpec; } private Boolean customValidation() { Boolean flag = true; if (cb.option_is_set("behavior")) { String state = cb.get_option("behavior"); if (!state.Equals("true") && !state.Equals("false")) { Console.WriteLine("Must specify 'true'or 'false' as the enablenioc" + "value option\n"); flag = false; } } if (cb.option_is_set("iolatencythreshold")) { ioLatencythreshold = cb.get_option("iolatencythreshold"); if (int.Parse(ioLatencythreshold) < 5 || int.Parse(ioLatencythreshold) > 50) { Console.WriteLine("Expected valid --iolatencythreshold argument. Range is 5-50 ms."); flag = false; } } if (cb.option_is_set("spacethreshold")) { spaceUtilizationThreshold = cb.get_option("spacethreshold"); if (int.Parse(spaceUtilizationThreshold) < 50 || int.Parse(spaceUtilizationThreshold) > 100) { Console.WriteLine("Expected valid --spacethreshold argument. Range is 50-100%."); flag = false; } } if (cb.option_is_set("utilizationdiff")) { minSpaceUtilizationDifference = cb.get_option("utilizationdiff"); if (int.Parse(minSpaceUtilizationDifference) < 1 || int.Parse(minSpaceUtilizationDifference) > 50) { Console.WriteLine("Expected valid --utilizationdiff argument. Range is 1-50%."); flag = false; } } if (cb.option_is_set("ioloadimbalancethreshold")) { ioLoadImbalanceThreshold = cb.get_option("ioloadimbalancethreshold"); if (int.Parse(ioLoadImbalanceThreshold) < 1 || int.Parse(ioLoadImbalanceThreshold) > 100) { Console.WriteLine("Expected valid --ioloadimbalancethreshold argument. Range is 1-100."); flag = false; } } return flag; } private static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[9]; useroptions[0] = new OptionSpec("dcname", "String", 1 , "Datacenter name" , null); useroptions[1] = new OptionSpec("sdrsname", "String", 1, "Name for the new storage pod", null); useroptions[2] = new OptionSpec("behavior", "String", 0, "Storage DRS behavior, true if automated. It is manual by default.", null); useroptions[3] = new OptionSpec("iolatencythreshold", "String", 0, "Storage DRS makes storage migration" + "recommendations if I/O latency on one (or more)" + "of the datastores is higher than the specified" + "threshold. Range is 5-50 ms, default is 15ms", null); useroptions[4] = new OptionSpec("spacethreshold", "String", 0, "Storage DRS makes storage migration" + "recommendations if space utilization on one" + "(or more) of the datastores is higher than the" + " specified threshold. Range 50-100%, default is 80%,", null); useroptions[5] = new OptionSpec("utilizationdiff", "String", 0, "Storage DRS considers making storage migration" + "recommendations if the difference in space" + "utilization between the source and destination" + "datastores is higher than the specified threshold." + "Range 1-50%, default is 5%", null); useroptions[6] = new OptionSpec("ioloadimbalancethreshold", "String", 0, " Storage DRS makes storage migration" + "recommendations if I/O load imbalance" + "level is higher than the specified threshold." + "Range is 1-100, default is 5", null); useroptions[7] = new OptionSpec("loadbalinterval", "String", 0, " Specify the interval that storage DRS runs to" + "load balance among datastores within a storage" + "pod. it is 480 by default.", null); useroptions[8] = new OptionSpec("datastore", "String", 0, "Name of the datastore to be added in StoragePod.", null); return useroptions; } public static void Main(string[] args) { CreateStorageDRS app = new CreateStorageDRS(); cb = AppUtil.AppUtil.initialize("CreateStorageDRS", CreateStorageDRS.constructOptions(), args); Boolean valid = app.customValidation(); if (valid) { try { cb.connect(); app.CreateSDRS(); cb.disConnect(); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.WriteLine("Please enter to exit: "); Console.Read(); } } }
using System; using NSec.Experimental.Asn1; using Xunit; namespace NSec.Tests.Formatting { public static class Asn1WriterTests { [Theory] [InlineData(false, new byte[] { 0x01, 0x01, 0x00 })] [InlineData(true, new byte[] { 0x01, 0x01, 0xFF })] public static void Bool(bool value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.Bool(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(new byte[] { }, new byte[] { 0x03, 0x01, 0x00 })] [InlineData(new byte[] { 0x01 }, new byte[] { 0x03, 0x02, 0x00, 0x01 })] [InlineData(new byte[] { 0x01, 0x23 }, new byte[] { 0x03, 0x03, 0x00, 0x01, 0x23 })] [InlineData(new byte[] { 0x01, 0x23, 0x45 }, new byte[] { 0x03, 0x04, 0x00, 0x01, 0x23, 0x45 })] [InlineData(new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, new byte[] { 0x03, 0x09, 0x00, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] public static void BitString(byte[] value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.BitString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(0, new byte[] { 0x02, 0x01, 0x00 })] [InlineData(127, new byte[] { 0x02, 0x01, 0x7F })] [InlineData(128, new byte[] { 0x02, 0x02, 0x00, 0x80 })] [InlineData(256, new byte[] { 0x02, 0x02, 0x01, 0x00 })] [InlineData(32767, new byte[] { 0x02, 0x02, 0x7F, 0xFF })] [InlineData(32768, new byte[] { 0x02, 0x03, 0x00, 0x80, 0x00 })] [InlineData(-128, new byte[] { 0x02, 0x01, 0x80 })] [InlineData(-129, new byte[] { 0x02, 0x02, 0xFF, 0x7F })] [InlineData(-32768, new byte[] { 0x02, 0x02, 0x80, 0x00 })] public static void Integer32(int value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.Integer(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(0L, new byte[] { 0x02, 0x01, 0x00 })] [InlineData(127L, new byte[] { 0x02, 0x01, 0x7F })] [InlineData(128L, new byte[] { 0x02, 0x02, 0x00, 0x80 })] [InlineData(256L, new byte[] { 0x02, 0x02, 0x01, 0x00 })] [InlineData(32767L, new byte[] { 0x02, 0x02, 0x7F, 0xFF })] [InlineData(32768L, new byte[] { 0x02, 0x03, 0x00, 0x80, 0x00 })] [InlineData(-128L, new byte[] { 0x02, 0x01, 0x80 })] [InlineData(-129L, new byte[] { 0x02, 0x02, 0xFF, 0x7F })] [InlineData(-32768L, new byte[] { 0x02, 0x02, 0x80, 0x00 })] [InlineData(int.MinValue, new byte[] { 0x02, 0x04, 0x80, 0x00, 0x00, 0x00 })] [InlineData(long.MinValue, new byte[] { 0x02, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })] public static void Integer64(long value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.Integer(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void Null() { var expected = new byte[] { 0x05, 0x00 }; var writer = new Asn1Writer(new byte[expected.Length]); writer.Null(); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d }, new byte[] { 0x06, 0x06, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d })] public static void ObjectIdentifier(byte[] value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.ObjectIdentifier(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(new byte[] { }, new byte[] { 0x04, 0x00 })] [InlineData(new byte[] { 0x01 }, new byte[] { 0x04, 0x01, 0x01 })] [InlineData(new byte[] { 0x01, 0x23 }, new byte[] { 0x04, 0x02, 0x01, 0x23 })] [InlineData(new byte[] { 0x01, 0x23, 0x45 }, new byte[] { 0x04, 0x03, 0x01, 0x23, 0x45 })] [InlineData(new byte[] { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef }, new byte[] { 0x04, 0x08, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef })] public static void OctetString(byte[] value, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.OctetString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void SequenceStackOverflow() { Assert.Equal(6, Asn1Writer.MaxDepth); var writer = new Asn1Writer(new byte[2]); writer.End(); writer.End(); writer.End(); writer.End(); writer.End(); writer.End(); try { writer.End(); Assert.True(false); } catch (InvalidOperationException) { } // cannot use Assert.Throws } [Fact] public static void SequenceStackUnderflow() { var writer = new Asn1Writer(Span<byte>.Empty); try { writer.BeginSequence(); Assert.True(false); } catch (InvalidOperationException) { } // cannot use Assert.Throws } [Theory] [InlineData(1, new byte[] { 0x30, 0x00 })] [InlineData(2, new byte[] { 0x30, 0x02, 0x30, 0x00 })] [InlineData(3, new byte[] { 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 })] [InlineData(4, new byte[] { 0x30, 0x06, 0x30, 0x04, 0x30, 0x02, 0x30, 0x00 })] public static void Sequence(int depth, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); for (var i = 0; i < depth; i++) writer.End(); for (var i = 0; i < depth; i++) writer.BeginSequence(); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(new int[] { }, new byte[] { 0x30, 0x00 })] [InlineData(new int[] { 1 }, new byte[] { 0x30, 0x03, 0x02, 0x01, 0x01 })] [InlineData(new int[] { 1, 2 }, new byte[] { 0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02 })] [InlineData(new int[] { 1, 2, 3 }, new byte[] { 0x30, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03 })] public static void IntegerSequence(int[] values, byte[] expected) { var writer = new Asn1Writer(new byte[expected.Length]); writer.End(); for (var i = 0; i < values.Length; i++) writer.Integer(values[values.Length - i - 1]); writer.BeginSequence(); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void Length100() { var value = Utilities.FillArray(100, 0xCD); var expected = new byte[2 + value.Length]; expected[0] = 0x04; expected[1] = (byte)value.Length; value.CopyTo(expected, 2); var writer = new Asn1Writer(new byte[expected.Length]); writer.OctetString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void Length200() { var value = Utilities.FillArray(200, 0xCD); var expected = new byte[3 + value.Length]; expected[0] = 0x04; expected[1] = 0x81; expected[2] = (byte)value.Length; value.CopyTo(expected, 3); var writer = new Asn1Writer(new byte[expected.Length]); writer.OctetString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void Length400() { var value = Utilities.FillArray(400, 0xCD); var expected = new byte[4 + value.Length]; expected[0] = 0x04; expected[1] = 0x82; expected[2] = (byte)(value.Length >> 8); expected[3] = (byte)(value.Length & 0xFF); value.CopyTo(expected, 4); var writer = new Asn1Writer(new byte[expected.Length]); writer.OctetString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Fact] public static void Length100000() { const int length = 100000; var expected = new byte[5 + length]; expected[0] = 0x04; expected[1] = 0x83; expected[2] = length >> 16; expected[3] = (length >> 8) & 0xFF; expected[4] = length & 0xFF; var value = expected.AsSpan(5); value.Fill(0xCD); var writer = new Asn1Writer(new byte[expected.Length]); writer.OctetString(value); Assert.Equal(expected, writer.Bytes.ToArray()); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] public static void BufferOverflow(int capacity) { var value = new byte[5]; Utilities.RandomBytes.Slice(0, value.Length).CopyTo(value); var writer = new Asn1Writer(new byte[capacity]); try { writer.OctetString(value); Assert.True(false); } catch (InvalidOperationException) { } // cannot use Assert.Throws } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices; using System.Text; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal static class WinHttpResponseParser { private const string EncodingNameDeflate = "DEFLATE"; private const string EncodingNameGzip = "GZIP"; private const string HeaderNameContentEncoding = "Content-Encoding"; private const string HeaderNameContentLength = "Content-Length"; private const string HeaderNameSetCookie = "Set-Cookie"; private static readonly string[] s_HttpHeadersSeparator = { "\r\n" }; public static HttpResponseMessage CreateResponseMessage( WinHttpRequestState state, bool doManualDecompressionCheck) { HttpRequestMessage request = state.RequestMessage; SafeWinHttpHandle requestHandle = state.RequestHandle; CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy; CookieContainer cookieContainer = state.Handler.CookieContainer; var response = new HttpResponseMessage(); bool stripEncodingHeaders = false; // Get HTTP version, status code, reason phrase from the response headers. string version = GetResponseHeaderStringInfo(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION); if (string.Compare("HTTP/1.1", version, StringComparison.OrdinalIgnoreCase) == 0) { response.Version = HttpVersion.Version11; } else if (string.Compare("HTTP/1.0", version, StringComparison.OrdinalIgnoreCase) == 0) { response.Version = HttpVersion.Version10; } else { response.Version = HttpVersion.Unknown; } response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE); response.ReasonPhrase = GetResponseHeaderStringInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT); // Create response stream and wrap it in a StreamContent object. var responseStream = new WinHttpResponseStream(state); Stream decompressedStream = responseStream; if (doManualDecompressionCheck) { string contentEncoding = GetResponseHeaderStringInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING); if (!string.IsNullOrEmpty(contentEncoding)) { if (contentEncoding.IndexOf(EncodingNameDeflate, StringComparison.OrdinalIgnoreCase) > -1) { decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } else if (contentEncoding.IndexOf(EncodingNameGzip, StringComparison.OrdinalIgnoreCase) > -1) { decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } } } var content = new StreamContent(decompressedStream); response.Content = content; response.RequestMessage = request; // Parse raw response headers and place them into response message. ParseResponseHeaders(requestHandle, response, stripEncodingHeaders); // Store response header cookies into custom CookieContainer. if (cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { Debug.Assert(cookieContainer != null); if (response.Headers.Contains(HeaderNameSetCookie)) { IEnumerable<string> cookieHeaders = response.Headers.GetValues(HeaderNameSetCookie); foreach (var cookieHeader in cookieHeaders) { try { cookieContainer.SetCookies(request.RequestUri, cookieHeader); } catch (CookieException) { // We ignore malformed cookies in the response. } } } } return response; } public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel) { uint result = 0; uint resultSize = sizeof(uint); if (!Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, ref result, ref resultSize, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } return result; } private static string GetResponseHeaderStringInfo(SafeWinHttpHandle requestHandle, uint infoLevel) { uint bytesNeeded = 0; bool results = false; // Call WinHttpQueryHeaders once to obtain the size of the buffer needed. The size is returned in // bytes but the API actually returns Unicode characters. if (!Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, null, ref bytesNeeded, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { return null; } if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { throw WinHttpException.CreateExceptionUsingError(lastError); } } // Allocate space for the buffer. int charsNeeded = (int)bytesNeeded / 2; var buffer = new StringBuilder(charsNeeded, charsNeeded); results = Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, buffer, ref bytesNeeded, IntPtr.Zero); if (!results) { WinHttpException.ThrowExceptionUsingLastError(); } return buffer.ToString(); } private static void ParseResponseHeaders( SafeWinHttpHandle requestHandle, HttpResponseMessage response, bool stripEncodingHeaders) { string rawResponseHeaders = GetResponseHeaderStringInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF); string[] responseHeaderArray = rawResponseHeaders.Split( s_HttpHeadersSeparator, StringSplitOptions.RemoveEmptyEntries); // Parse the array of headers and split them between Content headers and Response headers. // Skip the first line which contains status code, etc. information that we already parsed. for (int i = 1; i < responseHeaderArray.Length; i++) { int colonIndex = responseHeaderArray[i].IndexOf(':'); // Skip malformed header lines that are missing the colon character. if (colonIndex > 0) { string headerName = responseHeaderArray[i].Substring(0, colonIndex); string headerValue = responseHeaderArray[i].SubstringTrim(colonIndex + 1); // Normalize header value by trimming white space. if (!response.Headers.TryAddWithoutValidation(headerName, headerValue)) { if (stripEncodingHeaders) { // Remove Content-Length and Content-Encoding headers if we are // decompressing the response stream in the handler (due to // WINHTTP not supporting it in a particular downlevel platform). // This matches the behavior of WINHTTP when it does decompression iself. if (string.Equals( HeaderNameContentLength, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } if (string.Equals( HeaderNameContentEncoding, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } } // TODO: Issue #2165. Should we log if there is an error here? response.Content.Headers.TryAddWithoutValidation(headerName, headerValue); } } } } } }
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Core.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Core\New-ModuleManifest command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class NewModuleManifest : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public NewModuleManifest() { this.DisplayName = "New-ModuleManifest"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\New-ModuleManifest"; } } // Arguments /// <summary> /// Provides access to the Path parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Path { get; set; } /// <summary> /// Provides access to the NestedModules parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object[]> NestedModules { get; set; } /// <summary> /// Provides access to the Guid parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Guid> Guid { get; set; } /// <summary> /// Provides access to the Author parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Author { get; set; } /// <summary> /// Provides access to the CompanyName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> CompanyName { get; set; } /// <summary> /// Provides access to the Copyright parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Copyright { get; set; } /// <summary> /// Provides access to the RootModule parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> RootModule { get; set; } /// <summary> /// Provides access to the ModuleVersion parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Version> ModuleVersion { get; set; } /// <summary> /// Provides access to the Description parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Description { get; set; } /// <summary> /// Provides access to the ProcessorArchitecture parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Reflection.ProcessorArchitecture> ProcessorArchitecture { get; set; } /// <summary> /// Provides access to the PowerShellVersion parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Version> PowerShellVersion { get; set; } /// <summary> /// Provides access to the ClrVersion parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Version> ClrVersion { get; set; } /// <summary> /// Provides access to the DotNetFrameworkVersion parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Version> DotNetFrameworkVersion { get; set; } /// <summary> /// Provides access to the PowerShellHostName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> PowerShellHostName { get; set; } /// <summary> /// Provides access to the PowerShellHostVersion parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Version> PowerShellHostVersion { get; set; } /// <summary> /// Provides access to the RequiredModules parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object[]> RequiredModules { get; set; } /// <summary> /// Provides access to the TypesToProcess parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> TypesToProcess { get; set; } /// <summary> /// Provides access to the FormatsToProcess parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> FormatsToProcess { get; set; } /// <summary> /// Provides access to the ScriptsToProcess parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> ScriptsToProcess { get; set; } /// <summary> /// Provides access to the RequiredAssemblies parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> RequiredAssemblies { get; set; } /// <summary> /// Provides access to the FileList parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> FileList { get; set; } /// <summary> /// Provides access to the ModuleList parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object[]> ModuleList { get; set; } /// <summary> /// Provides access to the FunctionsToExport parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> FunctionsToExport { get; set; } /// <summary> /// Provides access to the AliasesToExport parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> AliasesToExport { get; set; } /// <summary> /// Provides access to the VariablesToExport parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> VariablesToExport { get; set; } /// <summary> /// Provides access to the CmdletsToExport parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> CmdletsToExport { get; set; } /// <summary> /// Provides access to the DscResourcesToExport parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> DscResourcesToExport { get; set; } /// <summary> /// Provides access to the PrivateData parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Object> PrivateData { get; set; } /// <summary> /// Provides access to the Tags parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Tags { get; set; } /// <summary> /// Provides access to the ProjectUri parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Uri> ProjectUri { get; set; } /// <summary> /// Provides access to the LicenseUri parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Uri> LicenseUri { get; set; } /// <summary> /// Provides access to the IconUri parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Uri> IconUri { get; set; } /// <summary> /// Provides access to the ReleaseNotes parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> ReleaseNotes { get; set; } /// <summary> /// Provides access to the HelpInfoUri parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> HelpInfoUri { get; set; } /// <summary> /// Provides access to the PassThru parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> PassThru { get; set; } /// <summary> /// Provides access to the DefaultCommandPrefix parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> DefaultCommandPrefix { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(Path.Expression != null) { targetCommand.AddParameter("Path", Path.Get(context)); } if(NestedModules.Expression != null) { targetCommand.AddParameter("NestedModules", NestedModules.Get(context)); } if(Guid.Expression != null) { targetCommand.AddParameter("Guid", Guid.Get(context)); } if(Author.Expression != null) { targetCommand.AddParameter("Author", Author.Get(context)); } if(CompanyName.Expression != null) { targetCommand.AddParameter("CompanyName", CompanyName.Get(context)); } if(Copyright.Expression != null) { targetCommand.AddParameter("Copyright", Copyright.Get(context)); } if(RootModule.Expression != null) { targetCommand.AddParameter("RootModule", RootModule.Get(context)); } if(ModuleVersion.Expression != null) { targetCommand.AddParameter("ModuleVersion", ModuleVersion.Get(context)); } if(Description.Expression != null) { targetCommand.AddParameter("Description", Description.Get(context)); } if(ProcessorArchitecture.Expression != null) { targetCommand.AddParameter("ProcessorArchitecture", ProcessorArchitecture.Get(context)); } if(PowerShellVersion.Expression != null) { targetCommand.AddParameter("PowerShellVersion", PowerShellVersion.Get(context)); } if(ClrVersion.Expression != null) { targetCommand.AddParameter("ClrVersion", ClrVersion.Get(context)); } if(DotNetFrameworkVersion.Expression != null) { targetCommand.AddParameter("DotNetFrameworkVersion", DotNetFrameworkVersion.Get(context)); } if(PowerShellHostName.Expression != null) { targetCommand.AddParameter("PowerShellHostName", PowerShellHostName.Get(context)); } if(PowerShellHostVersion.Expression != null) { targetCommand.AddParameter("PowerShellHostVersion", PowerShellHostVersion.Get(context)); } if(RequiredModules.Expression != null) { targetCommand.AddParameter("RequiredModules", RequiredModules.Get(context)); } if(TypesToProcess.Expression != null) { targetCommand.AddParameter("TypesToProcess", TypesToProcess.Get(context)); } if(FormatsToProcess.Expression != null) { targetCommand.AddParameter("FormatsToProcess", FormatsToProcess.Get(context)); } if(ScriptsToProcess.Expression != null) { targetCommand.AddParameter("ScriptsToProcess", ScriptsToProcess.Get(context)); } if(RequiredAssemblies.Expression != null) { targetCommand.AddParameter("RequiredAssemblies", RequiredAssemblies.Get(context)); } if(FileList.Expression != null) { targetCommand.AddParameter("FileList", FileList.Get(context)); } if(ModuleList.Expression != null) { targetCommand.AddParameter("ModuleList", ModuleList.Get(context)); } if(FunctionsToExport.Expression != null) { targetCommand.AddParameter("FunctionsToExport", FunctionsToExport.Get(context)); } if(AliasesToExport.Expression != null) { targetCommand.AddParameter("AliasesToExport", AliasesToExport.Get(context)); } if(VariablesToExport.Expression != null) { targetCommand.AddParameter("VariablesToExport", VariablesToExport.Get(context)); } if(CmdletsToExport.Expression != null) { targetCommand.AddParameter("CmdletsToExport", CmdletsToExport.Get(context)); } if(DscResourcesToExport.Expression != null) { targetCommand.AddParameter("DscResourcesToExport", DscResourcesToExport.Get(context)); } if(PrivateData.Expression != null) { targetCommand.AddParameter("PrivateData", PrivateData.Get(context)); } if(Tags.Expression != null) { targetCommand.AddParameter("Tags", Tags.Get(context)); } if(ProjectUri.Expression != null) { targetCommand.AddParameter("ProjectUri", ProjectUri.Get(context)); } if(LicenseUri.Expression != null) { targetCommand.AddParameter("LicenseUri", LicenseUri.Get(context)); } if(IconUri.Expression != null) { targetCommand.AddParameter("IconUri", IconUri.Get(context)); } if(ReleaseNotes.Expression != null) { targetCommand.AddParameter("ReleaseNotes", ReleaseNotes.Get(context)); } if(HelpInfoUri.Expression != null) { targetCommand.AddParameter("HelpInfoUri", HelpInfoUri.Get(context)); } if(PassThru.Expression != null) { targetCommand.AddParameter("PassThru", PassThru.Get(context)); } if(DefaultCommandPrefix.Expression != null) { targetCommand.AddParameter("DefaultCommandPrefix", DefaultCommandPrefix.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.Live; using System.Runtime.InteropServices; namespace Microsoft.Live.Desktop.Samples.ApiExplorer { public partial class MainForm : Form, IRefreshTokenHandler { // Update the ClientID with your app client Id that you created from https://account.live.com/developers/applications. private const string ClientID = "%YourAppClientId%"; private LiveAuthForm authForm; private LiveAuthClient liveAuthClient; private LiveConnectClient liveConnectClient; private RefreshTokenInfo refreshTokenInfo; public MainForm() { if (ClientID.Contains('%')) { throw new ArgumentException("Update the ClientID with your app client Id that you created from https://account.live.com/developers/applications."); } InitializeComponent(); } private LiveAuthClient AuthClient { get { if (this.liveAuthClient == null) { this.AuthClient = new LiveAuthClient(ClientID, this); } return this.liveAuthClient; } set { if (this.liveAuthClient != null) { this.liveAuthClient.PropertyChanged -= this.liveAuthClient_PropertyChanged; } this.liveAuthClient = value; if (this.liveAuthClient != null) { this.liveAuthClient.PropertyChanged += this.liveAuthClient_PropertyChanged; } this.liveConnectClient = null; } } private LiveConnectSession AuthSession { get { return this.AuthClient.Session; } } private void liveAuthClient_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Session") { this.UpdateUIElements(); } } private void UpdateUIElements() { LiveConnectSession session = this.AuthSession; bool isSignedIn = session != null; this.signOutButton.Enabled = isSignedIn; this.connectGroupBox.Enabled = isSignedIn; this.currentScopeTextBox.Text = isSignedIn ? string.Join(" ", session.Scopes) : string.Empty; if (!isSignedIn) { this.meNameLabel.Text = string.Empty; this.mePictureBox.Image = null; } } private void SigninButton_Click(object sender, EventArgs e) { if (this.authForm == null) { string startUrl = this.AuthClient.GetLoginUrl(this.GetAuthScopes()); string endUrl = "https://login.live.com/oauth20_desktop.srf"; this.authForm = new LiveAuthForm( startUrl, endUrl, this.OnAuthCompleted); this.authForm.FormClosed += AuthForm_FormClosed; this.authForm.ShowDialog(this); } } private string[] GetAuthScopes() { string[] scopes = new string[this.scopeListBox.SelectedItems.Count]; this.scopeListBox.SelectedItems.CopyTo(scopes, 0); return scopes; } void AuthForm_FormClosed(object sender, FormClosedEventArgs e) { this.CleanupAuthForm(); } private void CleanupAuthForm() { if (this.authForm != null) { this.authForm.Dispose(); this.authForm = null; } } private void LogOutput(string text) { this.outputTextBox.Text += text + "\r\n"; } private async void OnAuthCompleted(AuthResult result) { this.CleanupAuthForm(); if (result.AuthorizeCode != null) { try { LiveConnectSession session = await this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode); this.liveConnectClient = new LiveConnectClient(session); LiveOperationResult meRs = await this.liveConnectClient.GetAsync("me"); dynamic meData = meRs.Result; this.meNameLabel.Text = meData.name; LiveDownloadOperationResult meImgResult = await this.liveConnectClient.DownloadAsync("me/picture"); this.mePictureBox.Image = Image.FromStream(meImgResult.Stream); } catch (LiveAuthException aex) { this.LogOutput("Failed to retrieve access token. Error: " + aex.Message); } catch (LiveConnectException cex) { this.LogOutput("Failed to retrieve the user's data. Error: " + cex.Message); } } else { this.LogOutput(string.Format("Error received. Error: {0} Detail: {1}", result.ErrorCode, result.ErrorDescription)); } } private void SignOutButton_Click(object sender, EventArgs e) { this.signOutWebBrowser.Navigate(this.AuthClient.GetLogoutUrl()); this.AuthClient = null; this.UpdateUIElements(); } private void ClearOutputButton_Click(object sender, EventArgs e) { this.outputTextBox.Text = string.Empty; } private void ScopeListBox_SelectedIndexChanged(object sender, EventArgs e) { this.signinButton.Enabled = this.scopeListBox.SelectedItems.Count > 0; } private async void ExecuteButton_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(this.pathTextBox.Text)) { this.LogOutput("Path cannot be empty."); return; } try { LiveOperationResult result = null; switch (this.methodComboBox.Text) { case "GET": result = await this.liveConnectClient.GetAsync(this.pathTextBox.Text); break; case "PUT": result = await this.liveConnectClient.PutAsync(this.pathTextBox.Text, this.requestBodyTextBox.Text); break; case "POST": result = await this.liveConnectClient.PostAsync(this.pathTextBox.Text, this.requestBodyTextBox.Text); break; case "DELETE": result = await this.liveConnectClient.DeleteAsync(this.pathTextBox.Text); break; case "MOVE": result = await this.liveConnectClient.MoveAsync(this.pathTextBox.Text, this.destPathTextBox.Text); break; case "COPY": result = await this.liveConnectClient.CopyAsync(this.pathTextBox.Text, this.destPathTextBox.Text); break; case "UPLOAD": result = await this.UploadFile(this.pathTextBox.Text); break; case "DOWNLOAD": await this.DownloadFile(this.pathTextBox.Text); this.LogOutput("The download operation is completed."); break; } if (result != null) { this.LogOutput(result.RawResult); } } catch (Exception ex) { this.LogOutput("Received an error. " + ex.Message); } } private async Task<LiveOperationResult> UploadFile(string path) { OpenFileDialog dialog = new OpenFileDialog(); Stream stream = null; dialog.RestoreDirectory = true; if (dialog.ShowDialog() != DialogResult.OK) { throw new InvalidOperationException("No file is picked to upload."); } try { if ((stream = dialog.OpenFile()) == null) { throw new Exception("Unable to open the file selected to upload."); } using (stream) { return await this.liveConnectClient.UploadAsync(path, dialog.SafeFileName, stream, OverwriteOption.DoNotOverwrite); } } catch (Exception ex) { throw ex; } } private async Task DownloadFile(string path) { SaveFileDialog dialog = new SaveFileDialog(); Stream stream = null; dialog.RestoreDirectory = true; if (dialog.ShowDialog() != DialogResult.OK) { throw new InvalidOperationException("No file is picked to upload."); } try { if ((stream = dialog.OpenFile()) == null) { throw new Exception("Unable to open the file selected to upload."); } using (stream) { LiveDownloadOperationResult result = await this.liveConnectClient.DownloadAsync(path); if (result.Stream != null) { using (result.Stream) { await result.Stream.CopyToAsync(stream); } } } } catch (Exception ex) { throw ex; } } private async void MainForm_Load(object sender, EventArgs e) { this.methodComboBox.SelectedIndex = 0; try { LiveLoginResult loginResult = await this.AuthClient.InitializeAsync(); if (loginResult.Session != null) { this.liveConnectClient = new LiveConnectClient(loginResult.Session); } } catch (Exception ex) { this.LogOutput("Received an error during initializing. " + ex.Message); } } Task IRefreshTokenHandler.SaveRefreshTokenAsync(RefreshTokenInfo tokenInfo) { // Note: // 1) In order to receive refresh token, wl.offline_access scope is needed. // 2) Alternatively, we can persist the refresh token. return Task.Factory.StartNew(() => { this.refreshTokenInfo = tokenInfo; }); } Task<RefreshTokenInfo> IRefreshTokenHandler.RetrieveRefreshTokenAsync() { return Task.Factory.StartNew<RefreshTokenInfo>(() => { return this.refreshTokenInfo; }); } } }
using UnityEngine; using System.Collections.Generic; // Beta modifier [AddComponentMenu("Modifiers/Deformable")] public class MegaDeformable : MegaModifier { public override string ModName() { return "Deformable"; } public override void ModStart(MegaModifiers mc) { Vector3 s = mc.mesh.bounds.size; sizeFactor = Mathf.Min(s.x, s.y, s.z); if ( mc.mesh.colors != null ) baseColors = mc.mesh.colors; LoadMap(mc); } public override bool ModLateUpdate(MegaModContext mc) { return Prepare(mc); } public override bool Prepare(MegaModContext mc) { if ( offsets == null || offsets.Length != mc.mod.verts.Length ) offsets = new Vector3[mc.mod.verts.Length]; return true; } public override MegaModChannel ChannelsReq() { return MegaModChannel.Verts | MegaModChannel.Col; } public override MegaModChannel ChannelsChanged() { return MegaModChannel.Verts | MegaModChannel.Col; } public float Hardness = 0.5f; // Impact resistance to calculate amount of deformation applied to the mesh public bool DeformMeshCollider = true; // Configure if the mesh at collider must also be deformed (only works if a MeshCollider is in use) public float UpdateFrequency = 0.0f; // Configure the mesh (and mesh collider) update frequency in times per second. 0 for real time (high CPU usage) public float MaxVertexMov = 0.0f; // Maximum movement allowed for a vertex from its original position (0 means no limit) public Color32 DeformedVertexColor = Color.gray; // Color to be applied at deformed vertices (only works for shaders that handle vertices colors) public Texture2D HardnessMap; // Texture to modulate maximum movement allowed (uses alpha channel) public bool usedecay = false; public float decay = 0.999f; public Color[] baseColors; // Backup of original mesh vertices colors public float sizeFactor; // Size factor of mesh public float[] map; public Vector3[] offsets; public float impactFactor = 0.1f; public float ColForce = 0.5f; private void LoadMesh() { } public void LoadMap() { MegaModifiers mc = GetComponent<MegaModifyObject>(); if ( mc ) { LoadMap(mc); } } private void LoadMap(MegaModifiers mc) { // Load hardness map if ( HardnessMap ) { Vector2[] uvs = mc.mesh.uv; map = new float[uvs.Length]; for ( int c = 0; c < uvs.Length; c++ ) { Vector2 uv = uvs[c]; map[c] = HardnessMap.GetPixelBilinear(uv.x, uv.y).a; } } else map = null; } public override void Modify(MegaModifiers mc) { // Calc collision force float colForce = ColForce;//Mathf.Min(1, collision.impactForceSum.sqrMagnitude / 1000); sizeFactor = mc.bbox.size.magnitude; // distFactor is the amount of deforming in local coordinates float distFactor = colForce * (sizeFactor * (impactFactor / Mathf.Max(impactFactor, Hardness))); // Deform process if ( colpoints != null ) { for ( int c = 0; c < colpoints.Length; c++ ) { ContactPoint contact = colpoints[c]; for ( int i = 0; i < verts.Length; i++ ) { // Apply deformation only on vertex inside "blast area" Vector3 vp = verts[i] + offsets[i]; Vector3 p = transform.InverseTransformPoint(contact.point); float d = (vp - p).sqrMagnitude; if ( d <= distFactor ) { // Deformation is the collision normal with local deforming ratio // Vertices near the impact point must also be more deformed Vector3 n = transform.InverseTransformDirection(contact.normal * (1.0f - (d / distFactor)) * distFactor); // Apply hardness map if any if ( map != null ) n *= 1.0f - map[i]; // Deform vertex //vertices[i] += n; offsets[i] += n; // Apply max vertex movement if configured // Here the deformed vertex position is just scaled down to keep the best deformation while respecting limits if ( MaxVertexMov > 0.0f ) { float max = MaxVertexMov; n = offsets[i]; //vertices[i] - baseVertices[i]; d = n.magnitude; if ( d > max ) offsets[i] = (n * (max / d)); // Apply vertex color deformation // Deform color is applied in proportional amount with vertex distance and max deform if ( baseColors.Length > 0 ) { d = (d / MaxVertexMov); mc.cols[i] = Color.Lerp(baseColors[i], DeformedVertexColor, d); } } else { if ( mc.cols.Length > 0 ) { // Apply vertex color deformation // Deform color is applied in proportional amount with vertex distance and mesh distance factor mc.cols[i] = Color.Lerp(baseColors[i], DeformedVertexColor, offsets[i].magnitude / (distFactor * 10.0f)); } } } } } } colpoints = null; if ( !usedecay ) { for ( int i = 0; i < verts.Length; i++ ) { sverts[i].x = verts[i].x + offsets[i].x; sverts[i].y = verts[i].y + offsets[i].y; sverts[i].z = verts[i].z + offsets[i].z; } } else { for ( int i = 0; i < verts.Length; i++ ) { offsets[i].x *= decay; offsets[i].y *= decay; offsets[i].z *= decay; sverts[i].x = verts[i].x + offsets[i].x; sverts[i].y = verts[i].y + offsets[i].y; sverts[i].z = verts[i].z + offsets[i].z; } } } // We could find the megamod comp public void Repair(float repair, MegaModifiers mc) { Repair(repair, Vector3.zero, 0.0f, mc); } public void Repair(float repair, Vector3 point, float radius, MegaModifiers mc) { // Check mesh assigned if ( (!mc.mesh) ) //|| (!meshFilter) ) return; // Transform world point to mesh local point = transform.InverseTransformPoint(point); // Repairing is done returning vertices position and color to original positions by requested amount //int i = 0; for ( int i = 0; i < mc.verts.Length; i++ ) { // Check for repair inside radius if ( radius > 0.0f ) { if ( (point - mc.sverts[i]).magnitude >= radius ) continue; } // Repair Vector3 n = offsets[i]; //vertices[i] - baseVertices[i]; offsets[i] = n * (1.0f - repair); if ( baseColors.Length > 0 ) mc.cols[i] = Color.Lerp(mc.cols[i], baseColors[i], repair); } } //public bool doDeform = false; public MegaModifyObject modobj; ContactPoint[] colpoints; void OnCollisionEnter(Collision collision) { if ( modobj == null ) modobj = GetComponent<MegaModifyObject>(); if ( modobj ) modobj.Enabled = true; colpoints = collision.contacts; //doDeform = true; } void OnCollisionStay(Collision collision) { colpoints = collision.contacts; //doDeform = true; } void OnCollisionExit(Collision collision) { if ( modobj ) { if ( !usedecay ) modobj.Enabled = false; } } }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Lucene.Net.Util.Fst { /* * 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 INPUT_TYPE = Lucene.Net.Util.Fst.FST.INPUT_TYPE; // javadoc using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; // TODO: could we somehow stream an FST to disk while we // build it? /// <summary> /// Builds a minimal FST (maps an <see cref="Int32sRef"/> term to an arbitrary /// output) from pre-sorted terms with outputs. The FST /// becomes an FSA if you use NoOutputs. The FST is written /// on-the-fly into a compact serialized format byte array, which can /// be saved to / loaded from a Directory or used directly /// for traversal. The FST is always finite (no cycles). /// /// <para/>NOTE: The algorithm is described at /// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.24.3698 /// /// <para/>The parameterized type <typeparam name="T"/> is the output type. See the /// subclasses of <see cref="Outputs{T}"/>. /// /// <para/>FSTs larger than 2.1GB are now possible (as of Lucene /// 4.2). FSTs containing more than 2.1B nodes are also now /// possible, however they cannot be packed. /// <para/> /// @lucene.experimental /// </summary> public class Builder<T> : Builder { private readonly NodeHash<T> dedupHash; private readonly FST<T> fst; private readonly T NO_OUTPUT; // private static final boolean DEBUG = true; // simplistic pruning: we prune node (and all following // nodes) if less than this number of terms go through it: private readonly int minSuffixCount1; // better pruning: we prune node (and all following // nodes) if the prior node has less than this number of // terms go through it: private readonly int minSuffixCount2; private readonly bool doShareNonSingletonNodes; private readonly int shareMaxTailLength; private readonly Int32sRef lastInput = new Int32sRef(); // for packing private readonly bool doPackFST; private readonly float acceptableOverheadRatio; // NOTE: cutting this over to ArrayList instead loses ~6% // in build performance on 9.8M Wikipedia terms; so we // left this as an array: // current "frontier" private UnCompiledNode<T>[] frontier; // LUCENENET specific - FreezeTail class moved to non-generic type Builder private readonly FreezeTail<T> freezeTail; // LUCENENET specific - allow external access through property internal FST<T> Fst => fst; internal T NoOutput => NO_OUTPUT; /// <summary> /// Instantiates an FST/FSA builder without any pruning. A shortcut /// to <see cref="Builder{T}.Builder(FST.INPUT_TYPE, int, int, bool, bool, int, Outputs{T}, FreezeTail{T}, bool, float, bool, int)"/> /// with pruning options turned off. /// </summary> public Builder(FST.INPUT_TYPE inputType, Outputs<T> outputs) : this(inputType, 0, 0, true, true, int.MaxValue, outputs, null, false, PackedInt32s.COMPACT, true, 15) { var x = new System.Text.StringBuilder(); } /// <summary> /// Instantiates an FST/FSA builder with all the possible tuning and construction /// tweaks. Read parameter documentation carefully. /// </summary> /// <param name="inputType"> /// The input type (transition labels). Can be anything from <see cref="Lucene.Net.Util.Fst.FST.INPUT_TYPE"/> /// enumeration. Shorter types will consume less memory. Strings (character sequences) are /// represented as <see cref="Lucene.Net.Util.Fst.FST.INPUT_TYPE.BYTE4"/> (full unicode codepoints). /// </param> /// <param name="minSuffixCount1"> /// If pruning the input graph during construction, this threshold is used for telling /// if a node is kept or pruned. If transition_count(node) &gt;= minSuffixCount1, the node /// is kept. /// </param> /// <param name="minSuffixCount2"> /// (Note: only Mike McCandless knows what this one is really doing...) /// </param> /// <param name="doShareSuffix"> /// If <c>true</c>, the shared suffixes will be compacted into unique paths. /// this requires an additional RAM-intensive hash map for lookups in memory. Setting this parameter to /// <c>false</c> creates a single suffix path for all input sequences. this will result in a larger /// FST, but requires substantially less memory and CPU during building. /// </param> /// <param name="doShareNonSingletonNodes"> /// Only used if <paramref name="doShareSuffix"/> is <c>true</c>. Set this to /// true to ensure FST is fully minimal, at cost of more /// CPU and more RAM during building. /// </param> /// <param name="shareMaxTailLength"> /// Only used if <paramref name="doShareSuffix"/> is <c>true</c>. Set this to /// <see cref="int.MaxValue"/> to ensure FST is fully minimal, at cost of more /// CPU and more RAM during building. /// </param> /// <param name="outputs"> The output type for each input sequence. Applies only if building an FST. For /// FSA, use <see cref="NoOutputs.Singleton"/> and <see cref="NoOutputs.NoOutput"/> as the /// singleton output object. /// </param> /// <param name="doPackFST"> Pass <c>true</c> to create a packed FST. /// </param> /// <param name="acceptableOverheadRatio"> How to trade speed for space when building the FST. this option /// is only relevant when doPackFST is true. <see cref="PackedInt32s.GetMutable(int, int, float)"/> /// </param> /// <param name="allowArrayArcs"> Pass false to disable the array arc optimization /// while building the FST; this will make the resulting /// FST smaller but slower to traverse. /// </param> /// <param name="bytesPageBits"> How many bits wide to make each /// <see cref="T:byte[]"/> block in the <see cref="BytesStore"/>; if you know the FST /// will be large then make this larger. For example 15 /// bits = 32768 byte pages. </param> public Builder(FST.INPUT_TYPE inputType, int minSuffixCount1, int minSuffixCount2, bool doShareSuffix, bool doShareNonSingletonNodes, int shareMaxTailLength, Outputs<T> outputs, FreezeTail<T> freezeTail, bool doPackFST, float acceptableOverheadRatio, bool allowArrayArcs, int bytesPageBits) { this.minSuffixCount1 = minSuffixCount1; this.minSuffixCount2 = minSuffixCount2; this.freezeTail = freezeTail; this.doShareNonSingletonNodes = doShareNonSingletonNodes; this.shareMaxTailLength = shareMaxTailLength; this.doPackFST = doPackFST; this.acceptableOverheadRatio = acceptableOverheadRatio; fst = new FST<T>(inputType, outputs, doPackFST, acceptableOverheadRatio, allowArrayArcs, bytesPageBits); if (doShareSuffix) { dedupHash = new NodeHash<T>(fst, fst.bytes.GetReverseReader(false)); } else { dedupHash = null; } NO_OUTPUT = outputs.NoOutput; UnCompiledNode<T>[] f = (UnCompiledNode<T>[])new UnCompiledNode<T>[10]; frontier = f; for (int idx = 0; idx < frontier.Length; idx++) { frontier[idx] = new UnCompiledNode<T>(this, idx); } } public virtual long TotStateCount => fst.nodeCount; public virtual long TermCount => frontier[0].InputCount; public virtual long MappedStateCount => dedupHash == null ? 0 : fst.nodeCount; private CompiledNode CompileNode(UnCompiledNode<T> nodeIn, int tailLength) { long node; if (dedupHash != null && (doShareNonSingletonNodes || nodeIn.NumArcs <= 1) && tailLength <= shareMaxTailLength) { if (nodeIn.NumArcs == 0) { node = fst.AddNode(nodeIn); } else { node = dedupHash.Add(nodeIn); } } else { node = fst.AddNode(nodeIn); } Debug.Assert(node != -2); nodeIn.Clear(); CompiledNode fn = new CompiledNode(); fn.Node = node; return fn; } private void DoFreezeTail(int prefixLenPlus1) { if (freezeTail != null) { // Custom plugin: freezeTail.Freeze(frontier, prefixLenPlus1, lastInput); } else { //System.out.println(" compileTail " + prefixLenPlus1); int downTo = Math.Max(1, prefixLenPlus1); for (int idx = lastInput.Length; idx >= downTo; idx--) { bool doPrune = false; bool doCompile = false; UnCompiledNode<T> node = frontier[idx]; UnCompiledNode<T> parent = frontier[idx - 1]; if (node.InputCount < minSuffixCount1) { doPrune = true; doCompile = true; } else if (idx > prefixLenPlus1) { // prune if parent's inputCount is less than suffixMinCount2 if (parent.InputCount < minSuffixCount2 || (minSuffixCount2 == 1 && parent.InputCount == 1 && idx > 1)) { // my parent, about to be compiled, doesn't make the cut, so // I'm definitely pruned // if minSuffixCount2 is 1, we keep only up // until the 'distinguished edge', ie we keep only the // 'divergent' part of the FST. if my parent, about to be // compiled, has inputCount 1 then we are already past the // distinguished edge. NOTE: this only works if // the FST outputs are not "compressible" (simple // ords ARE compressible). doPrune = true; } else { // my parent, about to be compiled, does make the cut, so // I'm definitely not pruned doPrune = false; } doCompile = true; } else { // if pruning is disabled (count is 0) we can always // compile current node doCompile = minSuffixCount2 == 0; } //System.out.println(" label=" + ((char) lastInput.ints[lastInput.offset+idx-1]) + " idx=" + idx + " inputCount=" + frontier[idx].inputCount + " doCompile=" + doCompile + " doPrune=" + doPrune); if (node.InputCount < minSuffixCount2 || (minSuffixCount2 == 1 && node.InputCount == 1 && idx > 1)) { // drop all arcs for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++) { UnCompiledNode<T> target = (UnCompiledNode<T>)node.Arcs[arcIdx].Target; target.Clear(); } node.NumArcs = 0; } if (doPrune) { // this node doesn't make it -- deref it node.Clear(); parent.DeleteLast(lastInput.Int32s[lastInput.Offset + idx - 1], node); } else { if (minSuffixCount2 != 0) { CompileAllTargets(node, lastInput.Length - idx); } T nextFinalOutput = node.Output; // We "fake" the node as being final if it has no // outgoing arcs; in theory we could leave it // as non-final (the FST can represent this), but // FSTEnum, Util, etc., have trouble w/ non-final // dead-end states: bool isFinal = node.IsFinal || node.NumArcs == 0; if (doCompile) { // this node makes it and we now compile it. first, // compile any targets that were previously // undecided: parent.ReplaceLast(lastInput.Int32s[lastInput.Offset + idx - 1], CompileNode(node, 1 + lastInput.Length - idx), nextFinalOutput, isFinal); } else { // replaceLast just to install // nextFinalOutput/isFinal onto the arc parent.ReplaceLast(lastInput.Int32s[lastInput.Offset + idx - 1], node, nextFinalOutput, isFinal); // this node will stay in play for now, since we are // undecided on whether to prune it. later, it // will be either compiled or pruned, so we must // allocate a new node: frontier[idx] = new UnCompiledNode<T>(this, idx); } } } } } // for debugging /* private String toString(BytesRef b) { try { return b.utf8ToString() + " " + b; } catch (Throwable t) { return b.toString(); } } */ /// <summary> /// It's OK to add the same input twice in a row with /// different outputs, as long as outputs impls the merge /// method. Note that input is fully consumed after this /// method is returned (so caller is free to reuse), but /// output is not. So if your outputs are changeable (eg /// <see cref="ByteSequenceOutputs"/> or /// <see cref="Int32SequenceOutputs"/>) then you cannot reuse across /// calls. /// </summary> public virtual void Add(Int32sRef input, T output) { /* if (DEBUG) { BytesRef b = new BytesRef(input.length); for(int x=0;x<input.length;x++) { b.bytes[x] = (byte) input.ints[x]; } b.length = input.length; if (output == NO_OUTPUT) { System.out.println("\nFST ADD: input=" + toString(b) + " " + b); } else { System.out.println("\nFST ADD: input=" + toString(b) + " " + b + " output=" + fst.outputs.outputToString(output)); } } */ // De-dup NO_OUTPUT since it must be a singleton: if (output.Equals(NO_OUTPUT)) { output = NO_OUTPUT; } Debug.Assert(lastInput.Length == 0 || input.CompareTo(lastInput) >= 0, "inputs are added out of order lastInput=" + lastInput + " vs input=" + input); Debug.Assert(ValidOutput(output)); //System.out.println("\nadd: " + input); if (input.Length == 0) { // empty input: only allowed as first input. we have // to special case this because the packed FST // format cannot represent the empty input since // 'finalness' is stored on the incoming arc, not on // the node frontier[0].InputCount++; frontier[0].IsFinal = true; fst.EmptyOutput = output; return; } // compare shared prefix length int pos1 = 0; int pos2 = input.Offset; int pos1Stop = Math.Min(lastInput.Length, input.Length); while (true) { frontier[pos1].InputCount++; //System.out.println(" incr " + pos1 + " ct=" + frontier[pos1].inputCount + " n=" + frontier[pos1]); if (pos1 >= pos1Stop || lastInput.Int32s[pos1] != input.Int32s[pos2]) { break; } pos1++; pos2++; } int prefixLenPlus1 = pos1 + 1; if (frontier.Length < input.Length + 1) { UnCompiledNode<T>[] next = new UnCompiledNode<T>[ArrayUtil.Oversize(input.Length + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(frontier, 0, next, 0, frontier.Length); for (int idx = frontier.Length; idx < next.Length; idx++) { next[idx] = new UnCompiledNode<T>(this, idx); } frontier = next; } // minimize/compile states from previous input's // orphan'd suffix DoFreezeTail(prefixLenPlus1); // init tail states for current input for (int idx = prefixLenPlus1; idx <= input.Length; idx++) { frontier[idx - 1].AddArc(input.Int32s[input.Offset + idx - 1], frontier[idx]); frontier[idx].InputCount++; } UnCompiledNode<T> lastNode = frontier[input.Length]; if (lastInput.Length != input.Length || prefixLenPlus1 != input.Length + 1) { lastNode.IsFinal = true; lastNode.Output = NO_OUTPUT; } // push conflicting outputs forward, only as far as // needed for (int idx = 1; idx < prefixLenPlus1; idx++) { UnCompiledNode<T> node = frontier[idx]; UnCompiledNode<T> parentNode = frontier[idx - 1]; T lastOutput = parentNode.GetLastOutput(input.Int32s[input.Offset + idx - 1]); Debug.Assert(ValidOutput(lastOutput)); T commonOutputPrefix; T wordSuffix; if (!lastOutput.Equals(NO_OUTPUT)) { commonOutputPrefix = fst.Outputs.Common(output, lastOutput); Debug.Assert(ValidOutput(commonOutputPrefix)); wordSuffix = fst.Outputs.Subtract(lastOutput, commonOutputPrefix); Debug.Assert(ValidOutput(wordSuffix)); parentNode.SetLastOutput(input.Int32s[input.Offset + idx - 1], commonOutputPrefix); node.PrependOutput(wordSuffix); } else { commonOutputPrefix = wordSuffix = NO_OUTPUT; } output = fst.Outputs.Subtract(output, commonOutputPrefix); Debug.Assert(ValidOutput(output)); } if (lastInput.Length == input.Length && prefixLenPlus1 == 1 + input.Length) { // same input more than 1 time in a row, mapping to // multiple outputs lastNode.Output = fst.Outputs.Merge(lastNode.Output, output); } else { // this new arc is private to this new input; set its // arc output to the leftover output: frontier[prefixLenPlus1 - 1].SetLastOutput(input.Int32s[input.Offset + prefixLenPlus1 - 1], output); } // save last input lastInput.CopyInt32s(input); //System.out.println(" count[0]=" + frontier[0].inputCount); } internal bool ValidOutput(T output) { return output.Equals(NO_OUTPUT) || !output.Equals(NO_OUTPUT); } /// <summary> /// Returns final FST. NOTE: this will return null if /// nothing is accepted by the FST. /// </summary> public virtual FST<T> Finish() { UnCompiledNode<T> root = frontier[0]; // minimize nodes in the last word's suffix DoFreezeTail(0); if (root.InputCount < minSuffixCount1 || root.InputCount < minSuffixCount2 || root.NumArcs == 0) { if (fst.emptyOutput == null) { return null; } else if (minSuffixCount1 > 0 || minSuffixCount2 > 0) { // empty string got pruned return null; } } else { if (minSuffixCount2 != 0) { CompileAllTargets(root, lastInput.Length); } } //if (DEBUG) System.out.println(" builder.finish root.isFinal=" + root.isFinal + " root.Output=" + root.Output); fst.Finish(CompileNode(root, lastInput.Length).Node); if (doPackFST) { return fst.Pack(3, Math.Max(10, (int)(fst.NodeCount / 4)), acceptableOverheadRatio); } else { return fst; } } private void CompileAllTargets(UnCompiledNode<T> node, int tailLength) { for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++) { Arc<T> arc = node.Arcs[arcIdx]; if (!arc.Target.IsCompiled) { // not yet compiled UnCompiledNode<T> n = (UnCompiledNode<T>)arc.Target; if (n.NumArcs == 0) { //System.out.println("seg=" + segment + " FORCE final arc=" + (char) arc.Label); arc.IsFinal = n.IsFinal = true; } arc.Target = CompileNode(n, tailLength - 1); } } } // LUCENENET specific: moved Arc<S> to Builder type // NOTE: not many instances of Node or CompiledNode are in // memory while the FST is being built; it's only the // current "frontier": // LUCENENET specific: moved INode to Builder type public virtual long GetFstSizeInBytes() { return fst.GetSizeInBytes(); } // LUCENENET specific: Moved CompiledNode and UncompiledNode to Builder class } /// <summary> /// LUCENENET specific type used to access nested types of <see cref="Builder{T}"/> /// without referring to its generic closing type. /// </summary> public abstract class Builder { internal Builder() { } // Disallow external creation /// <summary> /// Expert: this is invoked by Builder whenever a suffix /// is serialized. /// </summary> public abstract class FreezeTail<S> { public abstract void Freeze(UnCompiledNode<S>[] frontier, int prefixLenPlus1, Int32sRef prevInput); } public interface INode // LUCENENET NOTE: made public rather than internal because it is returned in public types { bool IsCompiled { get; } } /// <summary> /// Expert: holds a pending (seen but not yet serialized) arc. </summary> public class Arc<S> { public int Label { get; set; } // really an "unsigned" byte public INode Target { get; set; } public bool IsFinal { get; set; } public S Output { get; set; } public S NextFinalOutput { get; set; } } public sealed class CompiledNode : INode { public long Node { get; set; } public bool IsCompiled => true; } /// <summary> /// Expert: holds a pending (seen but not yet serialized) Node. </summary> public sealed class UnCompiledNode<S> : INode { internal Builder<S> Owner { get; private set; } public int NumArcs { get; set; } [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public Arc<S>[] Arcs { get; set; } // TODO: instead of recording isFinal/output on the // node, maybe we should use -1 arc to mean "end" (like // we do when reading the FST). Would simplify much // code here... public S Output { get; set; } public bool IsFinal { get; set; } public long InputCount { get; set; } /// <summary> /// this node's depth, starting from the automaton root. </summary> public int Depth { get; private set; } /// <param name="depth"> /// The node's depth starting from the automaton root. Needed for /// LUCENE-2934 (node expansion based on conditions other than the /// fanout size). </param> public UnCompiledNode(Builder<S> owner, int depth) { this.Owner = owner; Arcs = (Arc<S>[])new Arc<S>[1]; Arcs[0] = new Arc<S>(); Output = owner.NoOutput; this.Depth = depth; } public bool IsCompiled => false; public void Clear() { NumArcs = 0; IsFinal = false; Output = Owner.NoOutput; InputCount = 0; // We don't clear the depth here because it never changes // for nodes on the frontier (even when reused). } public S GetLastOutput(int labelToMatch) { Debug.Assert(NumArcs > 0); Debug.Assert(Arcs[NumArcs - 1].Label == labelToMatch); return Arcs[NumArcs - 1].Output; } public void AddArc(int label, INode target) { Debug.Assert(label >= 0); if (NumArcs != 0) { Debug.Assert(label > Arcs[NumArcs - 1].Label, "arc[-1].Label=" + Arcs[NumArcs - 1].Label + " new label=" + label + " numArcs=" + NumArcs); } if (NumArcs == Arcs.Length) { Arc<S>[] newArcs = new Arc<S>[ArrayUtil.Oversize(NumArcs + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(Arcs, 0, newArcs, 0, Arcs.Length); for (int arcIdx = NumArcs; arcIdx < newArcs.Length; arcIdx++) { newArcs[arcIdx] = new Arc<S>(); } Arcs = newArcs; } Arc<S> arc = Arcs[NumArcs++]; arc.Label = label; arc.Target = target; arc.Output = arc.NextFinalOutput = Owner.NoOutput; arc.IsFinal = false; } public void ReplaceLast(int labelToMatch, INode target, S nextFinalOutput, bool isFinal) { Debug.Assert(NumArcs > 0); Arc<S> arc = Arcs[NumArcs - 1]; Debug.Assert(arc.Label == labelToMatch, "arc.Label=" + arc.Label + " vs " + labelToMatch); arc.Target = target; //assert target.Node != -2; arc.NextFinalOutput = nextFinalOutput; arc.IsFinal = isFinal; } public void DeleteLast(int label, INode target) { Debug.Assert(NumArcs > 0); Debug.Assert(label == Arcs[NumArcs - 1].Label); Debug.Assert(target == Arcs[NumArcs - 1].Target); NumArcs--; } public void SetLastOutput(int labelToMatch, S newOutput) { Debug.Assert(Owner.ValidOutput(newOutput)); Debug.Assert(NumArcs > 0); Arc<S> arc = Arcs[NumArcs - 1]; Debug.Assert(arc.Label == labelToMatch); arc.Output = newOutput; } // pushes an output prefix forward onto all arcs public void PrependOutput(S outputPrefix) { Debug.Assert(Owner.ValidOutput(outputPrefix)); for (int arcIdx = 0; arcIdx < NumArcs; arcIdx++) { Arcs[arcIdx].Output = Owner.Fst.Outputs.Add(outputPrefix, Arcs[arcIdx].Output); Debug.Assert(Owner.ValidOutput(Arcs[arcIdx].Output)); } if (IsFinal) { Output = Owner.Fst.Outputs.Add(outputPrefix, Output); Debug.Assert(Owner.ValidOutput(Output)); } } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Notebooks.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedManagedNotebookServiceClientTest { [xunit::FactAttribute] public void GetRuntimeRequestObject() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntime(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime response = client.GetRuntime(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRuntimeRequestObjectAsync() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntimeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Runtime>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime responseCallSettings = await client.GetRuntimeAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Runtime responseCancellationToken = await client.GetRuntimeAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRuntime() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntime(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime response = client.GetRuntime(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRuntimeAsync() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntimeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Runtime>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime responseCallSettings = await client.GetRuntimeAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Runtime responseCancellationToken = await client.GetRuntimeAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetRuntimeResourceNames() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntime(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime response = client.GetRuntime(request.RuntimeName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRuntimeResourceNamesAsync() { moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient> mockGrpcClient = new moq::Mock<ManagedNotebookService.ManagedNotebookServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetRuntimeRequest request = new GetRuntimeRequest { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), }; Runtime expectedResponse = new Runtime { RuntimeName = RuntimeName.FromProjectLocationRuntime("[PROJECT]", "[LOCATION]", "[RUNTIME]"), VirtualMachine = new VirtualMachine(), State = Runtime.Types.State.Active, HealthState = Runtime.Types.HealthState.Healthy, AccessConfig = new RuntimeAccessConfig(), SoftwareConfig = new RuntimeSoftwareConfig(), Metrics = new RuntimeMetrics(), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), }; mockGrpcClient.Setup(x => x.GetRuntimeAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Runtime>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ManagedNotebookServiceClient client = new ManagedNotebookServiceClientImpl(mockGrpcClient.Object, null); Runtime responseCallSettings = await client.GetRuntimeAsync(request.RuntimeName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Runtime responseCancellationToken = await client.GetRuntimeAsync(request.RuntimeName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using Foundation; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using zsquared; using UIKit; namespace vitavol { public partial class VC_SCVolunteers : UIViewController { C_WorkItemsTableSourceSCVolunteers TableSource; C_Global Global; C_VitaUser LoggedInUser; C_VitaSite SelectedSite; C_YMD SelectedDate; C_WorkShift SelectedShift; C_YMD Now; public VC_SCVolunteers(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); SelectedSite = Global.GetSiteFromSlugNoFetch(Global.SelectedSiteSlug); SelectedDate = Global.SelectedDate; SelectedShift = Global.SelectedShift; Now = C_YMD.Now; #if DEBUG if ((SelectedSite == null) || (SelectedDate == null) || (LoggedInUser == null) || (SelectedShift == null)) throw new ApplicationException("missing values"); #endif // ----- button handlers ----- B_Back.TouchUpInside += async (sender, e) => { // see if any of the items were changed and not saved var ou1 = Global.WorkShiftSignUpsOnDate.Where(wssu => wssu.TheSignUp.Dirty); if (!ou1.Any()) { PerformSegue("Segue_SCVolunteersToSiteShifts", this); return; } C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Items Changed", "One or more items changed. Approved them?", C_MessageBox.E_MessageBoxButtons.YesNoCancel); if (mbres == C_MessageBox.E_MessageBoxResults.Cancel) return; else if (mbres == C_MessageBox.E_MessageBoxResults.No) { PerformSegue("Segue_SCVolunteersToSiteShifts", this); return; } AI_Busy.StartAnimating(); EnableUI(false); bool success = await SaveChangedItems(); AI_Busy.StopAnimating(); EnableUI(true); if (!success) { C_MessageBox.E_MessageBoxResults mbres1 = await C_MessageBox.MessageBox(this, "Error", "Unble to save the work item", C_MessageBox.E_MessageBoxButtons.Ok); return; } PerformSegue("Segue_SCVolunteersToSiteShifts", this); }; B_ApproveHours.TouchUpInside += async (sender, e) => { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Approve Items?", "Approve signups on this date?", C_MessageBox.E_MessageBoxButtons.YesNo); if (mbres != C_MessageBox.E_MessageBoxResults.Yes) return; AI_Busy.StartAnimating(); EnableUI(false); bool success = await SaveChangedItems(); AI_Busy.StopAnimating(); EnableUI(true); if (!success) { C_MessageBox.E_MessageBoxResults mbres1 = await C_MessageBox.MessageBox(this, "Error", "Unble to save the work item(s)", C_MessageBox.E_MessageBoxButtons.Ok); return; } }; L_SiteName.Text = SelectedSite.Name; L_Date.Text = SelectedDate.ToString("mmm dd, yyyy"); L_Shift.Text = SelectedShift.OpenTime.ToString("hh:mm p") + " - " + SelectedShift.CloseTime.ToString("hh:mm p"); AI_Busy.StartAnimating(); EnableUI(false); // ----- initialize the view ----- Task.Run(async () => { // get the list os signups for this shift Global.WorkShiftSignUpsOnDate = SelectedShift.SignUps; // compute the number needed vs have int numBasicHave = 0; int numAdvHave = 0; int numBasicNeeded = SelectedShift.NumBasicEFilers; int numAdvNeeded = SelectedShift.NumAdvEFilers; foreach (C_WorkShiftSignUp wi in Global.WorkShiftSignUpsOnDate) { if (wi.User.Certification == E_Certification.Basic) numBasicHave++; else if (wi.User.Certification == E_Certification.Advanced) numAdvHave++; } // get the actual signup for each one so we can modify the number of hours worked foreach(C_WorkShiftSignUp wssu in Global.WorkShiftSignUpsOnDate) { if (wssu.TheSignUp == null) { C_IOResult ior = await Global.FetchSignUpBySignUpId(LoggedInUser.Token, wssu.SignUpId); if (ior.Success) wssu.TheSignUp = ior.SignUp; } } UIApplication.SharedApplication.InvokeOnMainThread( new Action(() => { AI_Busy.StopAnimating(); EnableUI(true); // set up the view elements L_BasicVolunteers.Text = numBasicHave.ToString() + " of " + numBasicNeeded.ToString(); L_AdvancedVolunteers.Text = numAdvHave.ToString() + " of " + numAdvNeeded.ToString(); TableSource = new C_WorkItemsTableSourceSCVolunteers(Global, Global.WorkShiftSignUpsOnDate, this); TV_Volunteers.Source = TableSource; TV_Volunteers.ReloadData(); B_ApproveHours.Enabled = (Global.WorkShiftSignUpsOnDate.Count != 0) && (SelectedDate <= Now); })); }); } public override void ViewDidAppear(bool animated) { // set the standard background color View.BackgroundColor = C_Common.StandardBackground; } private async Task<bool> SaveChangedItems() { bool res = true; try { foreach (C_WorkShiftSignUp wi in Global.WorkShiftSignUpsOnDate) { wi.TheSignUp.Approved = true; C_IOResult ior = await Global.UpdateSignUp(wi.TheSignUp, LoggedInUser.Token); res &= ior.Success; wi.TheSignUp.Dirty = false; } } catch {} return res; } private void EnableUI(bool enable) { TV_Volunteers.UserInteractionEnabled = enable; B_Back.Enabled = enable; B_ApproveHours.Enabled = enable && (Global.WorkShiftSignUpsOnDate.Count != 0) && (SelectedDate <= Now); } public class C_WorkItemsTableSourceSCVolunteers : UITableViewSource { readonly C_Global Global; public List<C_WorkShiftSignUp> SignUps; const string CellIdentifier = "TableCell_SignUpsTableSourceSCVolunteers"; readonly VC_SCVolunteers OurVC; public C_WorkItemsTableSourceSCVolunteers(C_Global pac, List<C_WorkShiftSignUp> signups, VC_SCVolunteers ourvc) { Global = pac; SignUps = signups; OurVC = ourvc; } public override nint RowsInSection(UITableView tableview, nint section) { int count = SignUps.Count; return count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); //---- if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); C_WorkShiftSignUp signup = SignUps[indexPath.Row]; string s_cert = signup.User.Certification.ToString(); cell.TextLabel.Text = signup.User.UserName; cell.DetailTextLabel.Text = "[" + signup.User.Phone + "] " + signup.User.Certification.ToString() + " - " + signup.TheSignUp.Hours.ToString() + " hours"; return cell; } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { Global.VolunteerWorkShiftSignUp = SignUps[indexPath.Row]; OurVC.PerformSegue("Segue_SCVolunteersToSCVolunteerHours", OurVC); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for StorageAccountsOperations. /// </summary> public static partial class StorageAccountsOperationsExtensions { /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static CheckNameAvailabilityResult CheckNameAvailability(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName) { return operations.CheckNameAvailabilityAsync(accountName).GetAwaiter().GetResult(); } /// <summary> /// Checks that account name is valid and is not in use. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityAsync(this IStorageAccountsOperations operations, StorageAccountCheckNameAvailabilityParameters accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount Create(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> CreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static void Delete(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { operations.DeleteAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a storage account in Microsoft Azure. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> public static StorageAccount GetProperties(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.GetPropertiesAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties for the specified storage account including but not /// limited to name, account type, location, and account status. The ListKeys /// operation should be used to retrieve storage keys. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> GetPropertiesAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPropertiesWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> public static StorageAccount Update(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates the account type or tags for a storage account. It can also be used /// to add a custom domain (note that custom domains cannot be added via the /// Create operation). Only one custom domain is supported per storage account. /// In order to replace a custom domain, the old value must be cleared before a /// new value may be set. To clear a custom domain, simply update the custom /// domain with empty string. Then call update again with the new cutsom domain /// name. The update API can only be used to update one of tags, accountType, /// or customDomain per call. To update multiple of these properties, call the /// API multiple times with one change per call. This call does not change the /// storage keys for the account. If you want to change storage account keys, /// use the RegenerateKey operation. The location and name of the storage /// account cannot be changed after creation. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to update on the account. Note that only one property can be /// changed at a time using this API. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> UpdateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> public static StorageAccountKeys ListKeys(this IStorageAccountsOperations operations, string resourceGroupName, string accountName) { return operations.ListKeysAsync(resourceGroupName, accountName).GetAwaiter().GetResult(); } /// <summary> /// Lists the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='accountName'> /// The name of the storage account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> ListKeysAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, accountName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IEnumerable<StorageAccount> List(this IStorageAccountsOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the subscription. Note that /// storage keys are not returned; use the ListKeys operation for this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListAsync(this IStorageAccountsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> public static IEnumerable<StorageAccount> ListByResourceGroup(this IStorageAccountsOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Lists all the storage accounts available under the given resource group. /// Note that storage keys are not returned; use the ListKeys operation for /// this. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<StorageAccount>> ListByResourceGroupAsync(this IStorageAccountsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> public static StorageAccountKeys RegenerateKey(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey) { return operations.RegenerateKeyAsync(resourceGroupName, accountName, regenerateKey).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the access keys for the specified storage account. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='regenerateKey'> /// Specifies name of the key which should be regenerated. key1 or key2 for the /// default keys /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccountKeys> RegenerateKeyAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountRegenerateKeyParameters regenerateKey, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeyWithHttpMessagesAsync(resourceGroupName, accountName, regenerateKey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> public static StorageAccount BeginCreate(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters) { return operations.BeginCreateAsync(resourceGroupName, accountName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Asynchronously creates a new storage account with the specified parameters. /// Existing accounts cannot be updated with this API and should instead use /// the Update Storage Account API. If an account is already created and /// subsequent PUT request is issued with exact same set of properties, then /// HTTP 200 would be returned. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='accountName'> /// The name of the storage account within the specified resource group. /// Storage account names must be between 3 and 24 characters in length and use /// numbers and lower-case letters only. /// </param> /// <param name='parameters'> /// The parameters to provide for the created account. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StorageAccount> BeginCreateAsync(this IStorageAccountsOperations operations, string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, accountName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright 2014 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.Generic; using Gvr.Internal; /// The GvrViewer object communicates with the head-mounted display. /// Is is repsonsible for: /// - Querying the device for viewing parameters /// - Retrieving the latest head tracking data /// - Providing the rendered scene to the device for distortion correction (optional) /// /// There should only be one of these in a scene. An instance will be generated automatically /// by this script at runtime, or you can add one via the Editor if you wish to customize /// its starting properties. [AddComponentMenu("GoogleVR/GvrViewer")] public class GvrViewer : MonoBehaviour { public const string GVR_SDK_VERSION = "1.1"; /// The singleton instance of the GvrViewer class. public static GvrViewer Instance { get { #if UNITY_EDITOR if (instance == null && !Application.isPlaying) { instance = UnityEngine.Object.FindObjectOfType<GvrViewer>(); } #endif if (instance == null) { Debug.LogError("No GvrViewer instance found. Ensure one exists in the scene, or call " + "GvrViewer.Create() at startup to generate one.\n" + "If one does exist but hasn't called Awake() yet, " + "then this error is due to order-of-initialization.\n" + "In that case, consider moving " + "your first reference to GvrViewer.Instance to a later point in time.\n" + "If exiting the scene, this indicates that the GvrViewer object has already " + "been destroyed."); } return instance; } } private static GvrViewer instance = null; /// Generate a GvrViewer instance. Takes no action if one already exists. public static void Create() { if (instance == null && UnityEngine.Object.FindObjectOfType<GvrViewer>() == null) { Debug.Log("Creating GvrViewer object"); var go = new GameObject("GvrViewer", typeof(GvrViewer)); go.transform.localPosition = Vector3.zero; // sdk will be set by Awake(). } } /// The StereoController instance attached to the main camera, or null if there is none. /// @note Cached for performance. public static StereoController Controller { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR Camera camera = Camera.main; // Cache for performance, if possible. if (camera != currentMainCamera || currentController == null) { currentMainCamera = camera; currentController = camera.GetComponent<StereoController>(); } return currentController; #else return null; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } private static StereoController currentController; private static Camera currentMainCamera; /// Determine whether the scene renders in stereo or mono. /// Supported only for versions of Unity *without* the GVR integration. /// VRModeEnabled will be a no-op for versions of Unity with the GVR integration. /// _True_ means to render in stereo, and _false_ means to render in mono. public bool VRModeEnabled { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return vrModeEnabled; #else return UnityEngine.VR.VRSettings.enabled; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } set { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (value != vrModeEnabled && device != null) { device.SetVRModeEnabled(value); } vrModeEnabled = value; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } [SerializeField] private bool vrModeEnabled = true; /// Methods for performing lens distortion correction. public enum DistortionCorrectionMethod { None, ///< No distortion correction Native, ///< Use the native C++ plugin Unity, ///< Perform distortion correction in Unity (recommended) } /// Determines the distortion correction method used by the SDK to render the /// #StereoScreen texture on the phone. If _Native_ is selected but not supported /// by the device, the _Unity_ method will be used instead. public DistortionCorrectionMethod DistortionCorrection { get { return distortionCorrection; } set { if (device != null && device.RequiresNativeDistortionCorrection()) { value = DistortionCorrectionMethod.Native; } if (value != distortionCorrection && device != null) { device.SetDistortionCorrectionEnabled(value == DistortionCorrectionMethod.Native && NativeDistortionCorrectionSupported); device.UpdateScreenData(); } distortionCorrection = value; } } [SerializeField] #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR private DistortionCorrectionMethod distortionCorrection = DistortionCorrectionMethod.Native; #else private DistortionCorrectionMethod distortionCorrection = DistortionCorrectionMethod.Unity; #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR /// The native SDK will apply a neck offset to the head tracking, resulting in /// a more realistic model of a person's head position. This control determines /// the scale factor of the offset. To turn off the neck model, set it to 0, and /// to turn it all on, set to 1. Intermediate values can be used to animate from /// on to off or vice versa. public float NeckModelScale { get { return neckModelScale; } set { value = Mathf.Clamp01(value); if (!Mathf.Approximately(value, neckModelScale) && device != null) { device.SetNeckModelScale(value); } neckModelScale = value; } } [SerializeField] private float neckModelScale = 0.0f; #if UNITY_EDITOR /// Restores level head tilt in when playing in the Unity Editor after you /// release the Ctrl key. public bool autoUntiltHead = true; /// @cond /// Use unity remote as the input source. public bool UseUnityRemoteInput = false; /// @endcond /// The screen size to emulate when testing in the Unity Editor. public GvrProfile.ScreenSizes ScreenSize { get { return screenSize; } set { if (value != screenSize) { screenSize = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ScreenSizes screenSize = GvrProfile.ScreenSizes.Nexus5; /// The viewer type to emulate when testing in the Unity Editor. public GvrProfile.ViewerTypes ViewerType { get { return viewerType; } set { if (value != viewerType) { viewerType = value; if (device != null) { device.UpdateScreenData(); } } } } [SerializeField] private GvrProfile.ViewerTypes viewerType = GvrProfile.ViewerTypes.CardboardMay2015; #endif // The VR device that will be providing input data. private static BaseVRDevice device; /// Whether native distortion correction functionality is supported by the VR device. public bool NativeDistortionCorrectionSupported { get; private set; } /// Whether the VR device supports showing a native UI layer, for example for settings. public bool NativeUILayerSupported { get; private set; } /// Scales the resolution of the #StereoScreen. Set to less than 1.0 to increase /// rendering speed while decreasing sharpness, or greater than 1.0 to do the /// opposite. public float StereoScreenScale { get { return stereoScreenScale; } set { value = Mathf.Clamp(value, 0.1f, 10.0f); // Sanity. if (stereoScreenScale != value) { stereoScreenScale = value; StereoScreen = null; } } } [SerializeField] private float stereoScreenScale = 1; /// The texture that Unity renders the scene to. After the frame has been rendered, /// this texture is drawn to the screen with a lens distortion correction effect. /// The texture size is based on the size of the screen, the lens distortion /// parameters, and the #StereoScreenScale factor. public RenderTexture StereoScreen { get { // Don't need it except for distortion correction. if (distortionCorrection == DistortionCorrectionMethod.None || !VRModeEnabled) { return null; } if (stereoScreen == null) { // Create on demand. StereoScreen = device.CreateStereoScreen(); // Note: uses set{} } return stereoScreen; } set { if (value == stereoScreen) { return; } if (stereoScreen != null) { stereoScreen.Release(); } stereoScreen = value; if (OnStereoScreenChanged != null) { OnStereoScreenChanged(stereoScreen); } } } private static RenderTexture stereoScreen = null; /// A callback for notifications that the StereoScreen property has changed. public delegate void StereoScreenChangeDelegate(RenderTexture newStereoScreen); /// Emitted when the StereoScreen property has changed. public event StereoScreenChangeDelegate OnStereoScreenChanged; /// Describes the current device, including phone screen. public GvrProfile Profile { get { return device.Profile; } } /// Returns true if GoogleVR is NOT supported natively. /// That is, this version of Unity does not have native integration but supports /// the GVR SDK (5.2, 5.3), or the current VR player is the in-editor emulator. public static bool NoNativeGVRSupport { get { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR return true; #else return false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } } /// Distinguish the stereo eyes. public enum Eye { Left, ///< The left eye Right, ///< The right eye Center ///< The "center" eye (unused) } /// When retrieving the #Projection and #Viewport properties, specifies /// whether you want the values as seen through the viewer's lenses (`Distorted`) or /// as if no lenses were present (`Undistorted`). public enum Distortion { Distorted, ///< Viewing through the lenses Undistorted ///< No lenses } /// The transformation of head from origin in the tracking system. public Pose3D HeadPose { get { return device.GetHeadPose(); } } /// The transformation from head to eye. public Pose3D EyePose(Eye eye) { return device.GetEyePose(eye); } /// The projection matrix for a given eye. /// This matrix is an off-axis perspective projection with near and far /// clipping planes of 1m and 1000m, respectively. The GvrEye script /// takes care of adjusting the matrix for its particular camera. public Matrix4x4 Projection(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetProjection(eye, distortion); } /// The screen space viewport that the camera for the specified eye should render into. /// In the _Distorted_ case, this will be either the left or right half of the `StereoScreen` /// render texture. In the _Undistorted_ case, it refers to the actual rectangle on the /// screen that the eye can see. public Rect Viewport(Eye eye, Distortion distortion = Distortion.Distorted) { return device.GetViewport(eye, distortion); } /// The distance range from the viewer in user-space meters where objects may be viewed /// comfortably in stereo. If the center of interest falls outside this range, the stereo /// eye separation should be adjusted to keep the onscreen disparity within the limits set /// by this range. If native integration is not supported, or the current VR player is the /// in-editor emulator, StereoController will handle this if the _checkStereoComfort_ is /// enabled. public Vector2 ComfortableViewingRange { get { return defaultComfortableViewingRange; } } private readonly Vector2 defaultComfortableViewingRange = new Vector2(0.4f, 100000.0f); /// @cond // Optional. Set to a URI obtained from the Google Cardboard profile generator at // https://www.google.com/get/cardboard/viewerprofilegenerator/ // Example: Cardboard I/O 2015 viewer profile //public Uri DefaultDeviceProfile = new Uri("http://google.com/cardboard/cfg?p=CgZHb29nbGUSEkNhcmRib2FyZCBJL08gMjAxNR0J-SA9JQHegj0qEAAAcEIAAHBCAABwQgAAcEJYADUpXA89OghX8as-YrENP1AAYAM"); public Uri DefaultDeviceProfile = null; /// @endcond private void InitDevice() { if (device != null) { device.Destroy(); } device = BaseVRDevice.GetDevice(); device.Init(); List<string> diagnostics = new List<string>(); NativeDistortionCorrectionSupported = device.SupportsNativeDistortionCorrection(diagnostics); if (diagnostics.Count > 0) { Debug.LogWarning("Built-in distortion correction disabled. Causes: [" + String.Join("; ", diagnostics.ToArray()) + "]"); } diagnostics.Clear(); NativeUILayerSupported = device.SupportsNativeUILayer(diagnostics); if (diagnostics.Count > 0) { Debug.LogWarning("Built-in UI layer disabled. Causes: [" + String.Join("; ", diagnostics.ToArray()) + "]"); } if (DefaultDeviceProfile != null) { device.SetDefaultDeviceProfile(DefaultDeviceProfile); } device.SetDistortionCorrectionEnabled(distortionCorrection == DistortionCorrectionMethod.Native && NativeDistortionCorrectionSupported); device.SetNeckModelScale(neckModelScale); #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.SetVRModeEnabled(vrModeEnabled); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR device.UpdateScreenData(); } /// @note Each scene load causes an OnDestroy of the current SDK, followed /// by and Awake of a new one. That should not cause the underlying native /// code to hiccup. Exception: developer may call Application.DontDestroyOnLoad /// on the SDK if they want it to survive across scene loads. void Awake() { if (instance == null) { instance = this; } if (instance != this) { Debug.LogError("There must be only one GvrViewer object in a scene."); UnityEngine.Object.DestroyImmediate(this); return; } #if UNITY_IOS Application.targetFrameRate = 60; #endif // Prevent the screen from dimming / sleeping Screen.sleepTimeout = SleepTimeout.NeverSleep; InitDevice(); StereoScreen = null; // Set up stereo pre- and post-render stages only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddPrePostRenderStages(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } void Start() { // Set up stereo controller only for: // - Unity without the GVR native integration // - In-editor emulator when the current platform is Android or iOS. // Since GVR is the only valid VR SDK on Android or iOS, this prevents it from // interfering with VR SDKs on other platforms. #if !UNITY_HAS_GOOGLEVR || (UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)) AddStereoControllerToCameras(); #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void AddPrePostRenderStages() { var preRender = UnityEngine.Object.FindObjectOfType<GvrPreRender>(); if (preRender == null) { var go = new GameObject("PreRender", typeof(GvrPreRender)); go.SendMessage("Reset"); go.transform.parent = transform; } var postRender = UnityEngine.Object.FindObjectOfType<GvrPostRender>(); if (postRender == null) { var go = new GameObject("PostRender", typeof(GvrPostRender)); go.SendMessage("Reset"); go.transform.parent = transform; } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Whether the viewer's trigger was pulled. True for exactly one complete frame /// after each pull. public bool Triggered { get; private set; } /// Whether the viewer was tilted on its side. True for exactly one complete frame /// after each tilt. Whether and how to respond to this event is up to the app. public bool Tilted { get; private set; } /// Whether the viewer profile has possibly changed. This is meant to indicate /// that a new QR code has been scanned, although currently it is actually set any time the /// application is unpaused, whether it was due to a profile change or not. True for one /// frame. public bool ProfileChanged { get; private set; } /// Whether the user has pressed the "VR Back Button", which on Android should be treated the /// same as the normal system Back Button, although you can respond to either however you want /// in your app. public bool BackButtonPressed { get; private set; } // Only call device.UpdateState() once per frame. private int updatedToFrame = 0; /// Reads the latest tracking data from the phone. This must be /// called before accessing any of the poses and matrices above. /// /// Multiple invocations per frame are OK: Subsequent calls merely yield the /// cached results of the first call. To minimize latency, it should be first /// called later in the frame (for example, in `LateUpdate`) if possible. public void UpdateState() { if (updatedToFrame != Time.frameCount) { updatedToFrame = Time.frameCount; device.UpdateState(); if (device.profileChanged) { if (distortionCorrection != DistortionCorrectionMethod.Native && device.RequiresNativeDistortionCorrection()) { DistortionCorrection = DistortionCorrectionMethod.Native; } if (stereoScreen != null && device.ShouldRecreateStereoScreen(stereoScreen.width, stereoScreen.height)) { StereoScreen = null; } } DispatchEvents(); } } private void DispatchEvents() { // Update flags first by copying from device and other inputs. Triggered = Input.GetMouseButtonDown(0); #if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Triggered |= GvrController.ClickButtonDown; #endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR) Tilted = device.tilted; ProfileChanged = device.profileChanged; BackButtonPressed = device.backButtonPressed || Input.GetKeyDown(KeyCode.Escape); // Reset device flags. device.tilted = false; device.profileChanged = false; device.backButtonPressed = false; } /// Presents the #StereoScreen to the device for distortion correction and display. /// @note This function is only used if #DistortionCorrection is set to _Native_, /// and it only has an effect if the device supports it. public void PostRender(RenderTexture stereoScreen) { if (NativeDistortionCorrectionSupported && stereoScreen != null && stereoScreen.IsCreated()) { device.PostRender(stereoScreen); } } /// Resets the tracker so that the user's current direction becomes forward. public void Recenter() { device.Recenter(); } /// Launch the device pairing and setup dialog. public void ShowSettingsDialog() { device.ShowSettingsDialog(); } #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR /// Add a StereoController to any camera that does not have a Render Texture (meaning it is /// rendering to the screen). public static void AddStereoControllerToCameras() { for (int i = 0; i < Camera.allCameras.Length; i++) { Camera camera = Camera.allCameras[i]; if (camera.targetTexture == null && camera.cullingMask != 0 && camera.GetComponent<StereoController>() == null && camera.GetComponent<GvrEye>() == null && camera.GetComponent<GvrPreRender>() == null && camera.GetComponent<GvrPostRender>() == null) { camera.gameObject.AddComponent<StereoController>(); } } } #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR void OnEnable() { #if UNITY_EDITOR // This can happen if you edit code while the editor is in Play mode. if (device == null) { InitDevice(); } #endif device.OnPause(false); } void OnDisable() { device.OnPause(true); } void OnApplicationPause(bool pause) { device.OnPause(pause); } void OnApplicationFocus(bool focus) { device.OnFocus(focus); } void OnApplicationQuit() { device.OnApplicationQuit(); } void OnDestroy() { #if !UNITY_HAS_GOOGLEVR || UNITY_EDITOR VRModeEnabled = false; #endif // !UNITY_HAS_GOOGLEVR || UNITY_EDITOR if (device != null) { device.Destroy(); } if (instance == this) { instance = null; } } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// 5.2.2: angular velocity measured in radians per second out each of the entity's own coordinate axes. /// </summary> [Serializable] [XmlRoot] public partial class AngularVelocityVector { /// <summary> /// velocity about the x axis /// </summary> private float _x; /// <summary> /// velocity about the y axis /// </summary> private float _y; /// <summary> /// velocity about the zaxis /// </summary> private float _z; /// <summary> /// Initializes a new instance of the <see cref="AngularVelocityVector"/> class. /// </summary> public AngularVelocityVector() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(AngularVelocityVector left, AngularVelocityVector right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(AngularVelocityVector left, AngularVelocityVector right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 4; // this._x marshalSize += 4; // this._y marshalSize += 4; // this._z return marshalSize; } /// <summary> /// Gets or sets the velocity about the x axis /// </summary> [XmlElement(Type = typeof(float), ElementName = "x")] public float X { get { return this._x; } set { this._x = value; } } /// <summary> /// Gets or sets the velocity about the y axis /// </summary> [XmlElement(Type = typeof(float), ElementName = "y")] public float Y { get { return this._y; } set { this._y = value; } } /// <summary> /// Gets or sets the velocity about the zaxis /// </summary> [XmlElement(Type = typeof(float), ElementName = "z")] public float Z { get { return this._z; } set { this._z = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteFloat((float)this._x); dos.WriteFloat((float)this._y); dos.WriteFloat((float)this._z); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._x = dis.ReadFloat(); this._y = dis.ReadFloat(); this._z = dis.ReadFloat(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<AngularVelocityVector>"); try { sb.AppendLine("<x type=\"float\">" + this._x.ToString(CultureInfo.InvariantCulture) + "</x>"); sb.AppendLine("<y type=\"float\">" + this._y.ToString(CultureInfo.InvariantCulture) + "</y>"); sb.AppendLine("<z type=\"float\">" + this._z.ToString(CultureInfo.InvariantCulture) + "</z>"); sb.AppendLine("</AngularVelocityVector>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as AngularVelocityVector; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(AngularVelocityVector obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._x != obj._x) { ivarsEqual = false; } if (this._y != obj._y) { ivarsEqual = false; } if (this._z != obj._z) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._x.GetHashCode(); result = GenerateHash(result) ^ this._y.GetHashCode(); result = GenerateHash(result) ^ this._z.GetHashCode(); return result; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Networking.iSessionDatastorBinding", Namespace="urn:iControl")] public partial class NetworkingiSessionDatastor : iControlInterface { public NetworkingiSessionDatastor() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_description( ) { object [] results = this.Invoke("get_description", new object [0]); return ((string)(results[0])); } public System.IAsyncResult Beginget_description(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[0], callback, asyncState); } public string Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // get_disk_cache_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_disk_cache_size( ) { object [] results = this.Invoke("get_disk_cache_size", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_disk_cache_size(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_disk_cache_size", new object[0], callback, asyncState); } public long Endget_disk_cache_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_disk_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public CommonEnabledState get_disk_state( ) { object [] results = this.Invoke("get_disk_state", new object [0]); return ((CommonEnabledState)(results[0])); } public System.IAsyncResult Beginget_disk_state(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_disk_state", new object[0], callback, asyncState); } public CommonEnabledState Endget_disk_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((CommonEnabledState)(results[0])); } //----------------------------------------------------------------------- // get_memory_cache_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_memory_cache_size( ) { object [] results = this.Invoke("get_memory_cache_size", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_memory_cache_size(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_memory_cache_size", new object[0], callback, asyncState); } public long Endget_memory_cache_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_pruning_high_water_mark //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_pruning_high_water_mark( ) { object [] results = this.Invoke("get_pruning_high_water_mark", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_pruning_high_water_mark(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_pruning_high_water_mark", new object[0], callback, asyncState); } public long Endget_pruning_high_water_mark(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_pruning_low_water_mark //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long get_pruning_low_water_mark( ) { object [] results = this.Invoke("get_pruning_low_water_mark", new object [0]); return ((long)(results[0])); } public System.IAsyncResult Beginget_pruning_low_water_mark(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_pruning_low_water_mark", new object[0], callback, asyncState); } public long Endget_pruning_low_water_mark(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long)(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] public void set_description( string description ) { this.Invoke("set_description", new object [] { description}); } public System.IAsyncResult Beginset_description(string description, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { description}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_disk_state //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] public void set_disk_state( CommonEnabledState state ) { this.Invoke("set_disk_state", new object [] { state}); } public System.IAsyncResult Beginset_disk_state(CommonEnabledState state, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_disk_state", new object[] { state}, callback, asyncState); } public void Endset_disk_state(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_pruning_high_water_mark //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] public void set_pruning_high_water_mark( long value ) { this.Invoke("set_pruning_high_water_mark", new object [] { value}); } public System.IAsyncResult Beginset_pruning_high_water_mark(long value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_pruning_high_water_mark", new object[] { value}, callback, asyncState); } public void Endset_pruning_high_water_mark(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_pruning_low_water_mark //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/iSessionDatastor", RequestNamespace="urn:iControl:Networking/iSessionDatastor", ResponseNamespace="urn:iControl:Networking/iSessionDatastor")] public void set_pruning_low_water_mark( long value ) { this.Invoke("set_pruning_low_water_mark", new object [] { value}); } public System.IAsyncResult Beginset_pruning_low_water_mark(long value, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_pruning_low_water_mark", new object[] { value}, callback, asyncState); } public void Endset_pruning_low_water_mark(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
//------------------------------------------------------------------------------ // <copyright file="LiteralText.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Web; using System.Web.UI; using System.Web.UI.Design.WebControls; using System.Web.UI.HtmlControls; using System.Security.Permissions; namespace System.Web.UI.MobileControls { /* * Literal Text class. This is the control created for literal text in a form. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralText"]/*' /> [ ControlBuilderAttribute(typeof(LiteralTextControlBuilder)), ToolboxItem(false) ] [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class LiteralText : PagedControl { // Note that this value doesn't relate to device specific info // because this is simply a unit size to define how many characters // to be counted as an item for pagination. Depending on each // device's page weight, different numbers of items will be returned // for display. private static readonly int PagingUnitSize = ControlPager.DefaultWeight; // chars /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralText.Text"]/*' /> [ Bindable(false), Browsable(false), ] public String Text { // Override MobileControl default behavior for InnerText get { String s = (String)ViewState[MobileControl.InnerTextViewStateKey]; return s != null ? s : InnerText; } set { ViewState[MobileControl.InnerTextViewStateKey] = value; } } // this attempts to split on word, return or sentence boundaries. // use of '.' to indicate end of sentence assumes western languages // perhaps if we get rid of '.' logic, '\n' preference will be sufficient private int CalculateOffset(int itemIndex) { if (itemIndex == 0) { return 0; } int length = Text.Length; int itemSize = (length / InternalItemCount) + 1; int baseOffset = itemSize * itemIndex; if (baseOffset >= length) { return length; } // this code scans to find an optimal break location. String text = this.Text; int scanLength = itemSize / 2; int scanStop = baseOffset - scanLength; int foundSpace = -1; int foundReturn = -1; int lastChar = -1; for (int offset = baseOffset; offset > scanStop; offset--) { char c = text[offset]; if (c == '.' && Char.IsWhiteSpace((char)lastChar)) { // this may exceed baseOffset by 1, but will never exceed totalChars return offset + 1; } else if (foundReturn < 0 && c == '\n') { foundReturn = offset; } else if (foundSpace < 0 && Char.IsWhiteSpace(c)) // check performance of this { foundSpace = offset; } lastChar = c; } if (foundReturn > 0) { return foundReturn; } else if (foundSpace > 0) { return foundSpace; } return baseOffset; } /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralText.PagedText"]/*' /> public String PagedText { get { int index = FirstVisibleItemIndex; int count = VisibleItemCount; String text = Text; if (count > text.Length) { return text; } int start = CalculateOffset(index); int stop = CalculateOffset(index + count); // If not at the beginning or end, skip spaces. if (start > 0) { while (start < stop && Char.IsWhiteSpace(text[start]) ) { start++; } } if (stop < text.Length) { while (Char.IsWhiteSpace(text[stop - 1]) && stop > start) { stop--; } } return (stop > start) ? text.Substring(start, stop - start) : String.Empty; } } /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralText.InternalItemCount"]/*' /> protected override int InternalItemCount { get { return ((Text.Length / PagingUnitSize) + (((Text.Length % PagingUnitSize) > 0) ? 1 : 0)); } } /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralText.ItemWeight"]/*' /> protected override int ItemWeight { get { return PagingUnitSize; } } internal override bool TrimInnerText { get { return false; } } } /* * Control builder for literal text. * * Copyright (c) 2000 Microsoft Corporation */ /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralTextControlBuilder"]/*' /> [AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] public class LiteralTextControlBuilder : MobileControlBuilder { /// <include file='doc\LiteralText.uex' path='docs/doc[@for="LiteralTextControlBuilder.AllowWhitespaceLiterals"]/*' /> public override bool AllowWhitespaceLiterals() { return true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Gorge.Areas.HelpPage.ModelDescriptions; using Gorge.Areas.HelpPage.Models; namespace Gorge.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; using System.Threading; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.TestData; using NUnit.TestUtilities; namespace NUnit.Framework.Attributes { [Platform(Include = "Win, Mono")] [TestFixture] public class ApartmentAttributeTests : ThreadingTests { [Test] public void ApartmentStateUnknownIsNotRunnable() { var testSuite = TestBuilder.MakeFixture(typeof(ApartmentDataApartmentAttribute)); Assert.That(testSuite, Has.Property(nameof(TestSuite.RunState)).EqualTo(RunState.NotRunnable)); } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [Test, Apartment(ApartmentState.STA)] public void TestWithRequiresSTARunsInSTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); if (ParentThreadApartment == ApartmentState.STA) Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); } [Test] #if THREAD_ABORT [Timeout(10_000)] #endif #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] public void TestWithTimeoutAndSTARunsInSTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); } [TestFixture] #if THREAD_ABORT [Timeout(10_000)] #endif #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [Apartment(ApartmentState.STA)] public class FixtureWithTimeoutRequiresSTA { [Test] public void RequiresSTACanBeSetOnTestFixtureWithTimeout() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.STA)); } } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [TestFixture, Apartment(ApartmentState.STA)] public class FixtureRequiresSTA { [Test] public void RequiresSTACanBeSetOnTestFixture() { Assert.That( GetApartmentState( Thread.CurrentThread ), Is.EqualTo( ApartmentState.STA ) ); } } [TestFixture] public class ChildFixtureRequiresSTA : FixtureRequiresSTA { // Issue #36 - Make RequiresThread, RequiresSTA, RequiresMTA inheritable // https://github.com/nunit/nunit-framework/issues/36 [Test] public void RequiresSTAAttributeIsInheritable() { Attribute[] attributes = Attribute.GetCustomAttributes(GetType(), typeof(ApartmentAttribute), true); Assert.That(attributes, Has.Length.EqualTo(1), "RequiresSTAAttribute was not inherited from the base class"); } } [Test, Apartment(ApartmentState.MTA)] public void TestWithRequiresMTARunsInMTA() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.MTA)); if (ParentThreadApartment == ApartmentState.MTA) Assert.That(Thread.CurrentThread, Is.EqualTo(ParentThread)); } [TestFixture, Apartment(ApartmentState.MTA)] public class FixtureRequiresMTA { [Test] public void RequiresMTACanBeSetOnTestFixture() { Assert.That(GetApartmentState(Thread.CurrentThread), Is.EqualTo(ApartmentState.MTA)); } } [TestFixture] public class ChildFixtureRequiresMTA : FixtureRequiresMTA { // Issue #36 - Make RequiresThread, RequiresSTA, RequiresMTA inheritable // https://github.com/nunit/nunit-framework/issues/36 [Test] public void RequiresMTAAttributeIsInheritable() { Attribute[] attributes = Attribute.GetCustomAttributes(GetType(), typeof(ApartmentAttribute), true); Assert.That(attributes, Has.Length.EqualTo(1), "RequiresMTAAttribute was not inherited from the base class"); } } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] public class ParallelStaFixture { [Test] public void TestMethodsShouldInheritApartmentFromFixture() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } [TestCase(1)] [TestCase(2)] public void TestCasesShouldInheritApartmentFromFixture(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.Children)] public class ParallelStaFixtureWithMtaTests { [Test] [Apartment(ApartmentState.MTA)] public void TestMethodsShouldRespectTheirApartment() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } [TestCase(1)] [TestCase(2)] [Apartment(ApartmentState.MTA)] public void TestCasesShouldRespectTheirApartment(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] public class NonParallelStaFixture { [Test] public void TestMethodsShouldInheritApartmentFromFixture() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } [TestCase(1)] [TestCase(2)] public void TestCasesShouldInheritApartmentFromFixture(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA)); } } #if NETCOREAPP [Platform(Include = "Win, Mono")] #endif [TestFixture] [Apartment(ApartmentState.STA)] [Parallelizable(ParallelScope.None)] public class NonParallelStaFixtureWithMtaTests { [Test] [Apartment(ApartmentState.MTA)] public void TestMethodsShouldRespectTheirApartment() { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } [TestCase(1)] [TestCase(2)] [Apartment(ApartmentState.MTA)] public void TestCasesShouldRespectTheirApartment(int n) { Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA)); } } } }
#region Copyright // (C) Copyright 2003-2016 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. #endregion // Copyright #region Namespaces using System; using System.Collections.Generic; using System.Text; using System.Xml; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Electrical; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.DB.Plumbing; #endregion // Namespaces namespace TraverseAllSystems { /// <summary> /// TreeNode object representing a system element /// </summary> public class TreeNode { #region JSON Output Format Strings /// <summary> /// Format a tree node to JSON storing parent id /// in child node for bottom-up structure. /// </summary> const string _json_format_to_store_parent_in_child = "{{" + "\"id\" : {0}, " + "\"{1}\" : \"{2}\", " + "\"parent\" : {3}}}"; /// <summary> /// Format a tree node to JSON storing a /// hierarchical tree of children ids in parent /// for top-down structure. /// </summary> const string _json_format_to_store_children_in_parent = "{{" + "\"id\" : \"{0}\", " + "\"{1}\" : \"{2}\", " + "\"children\" : [{3}]}}"; /// <summary> /// Create a new JSON parent node for the top-down graph. /// </summary> public static string CreateJsonParentNode( string id, string label, string json_kids ) { return string.Format( _json_format_to_store_children_in_parent, id, Options.NodeLabelTag, label, json_kids ); } /// <summary> /// Create a new JSON parent node for the top-down graph. /// </summary> public static string CreateJsonParentNode( string id, string label, string[] json_kids ) { return CreateJsonParentNode( id, label, string.Join( ",", json_kids ) ); } #endregion // JSON Output Format Strings #region Member variables /// <summary> /// Id of the element /// </summary> private Autodesk.Revit.DB.ElementId m_Id; /// <summary> /// Flow direction of the node /// For the starting element of the traversal, the direction will be the same as the connector /// connected to its following element; Otherwise it will be the direction of the connector connected to /// its previous element /// </summary> private FlowDirectionType m_direction; /// <summary> /// The parent node of the current node. /// </summary> private TreeNode m_parent; /// <summary> /// The connector of the previous element to which current element is connected /// </summary> private Connector m_inputConnector; /// <summary> /// The first-level child nodes of the current node /// </summary> private List<TreeNode> m_childNodes; /// <summary> /// Active document of Revit /// </summary> private Document m_document; #endregion #region Properties /// <summary> /// Id of the element /// </summary> public ElementId Id { get { return m_Id; } } /// <summary> /// Flow direction of the node /// </summary> public FlowDirectionType Direction { get { return m_direction; } set { m_direction = value; } } /// <summary> /// Gets and sets the parent node of the current node. /// </summary> public TreeNode Parent { get { return m_parent; } set { m_parent = value; } } /// <summary> /// Gets and sets the first-level child nodes of the current node /// </summary> public List<TreeNode> ChildNodes { get { return m_childNodes; } set { m_childNodes = value; } } /// <summary> /// The connector of the previous element to which current element is connected /// </summary> public Connector InputConnector { get { return m_inputConnector; } set { m_inputConnector = value; } } #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="doc">Revit document</param> /// <param name="id">Element's Id</param> public TreeNode( Document doc, ElementId id ) { m_document = doc; m_Id = id; m_childNodes = new List<TreeNode>(); } #endregion // Constructor #region GetElementById /// <summary> /// Get Element by its Id /// </summary> /// <param name="eid">Element's Id</param> /// <returns>Element</returns> private Element GetElementById( ElementId eid ) { return m_document.GetElement( eid ); } #endregion // GetElementById #region JSON Output public static string GetName( Element e ) { return Util.ElementDescription( e ) .Replace( "\"", "\\\"" ); } public static string GetId( Element e ) { return Options.StoreUniqueId ? e.UniqueId : e.Id.IntegerValue.ToString(); } /// <summary> /// Add JSON strings representing all children /// of this node to the given collection. /// </summary> public void DumpToJsonBottomUp( List<string> json_collector, string parent_id ) { Element e = GetElementById( m_Id ); string id = GetId( e ); string json = string.Format( _json_format_to_store_parent_in_child, id, Options.NodeLabelTag, GetName( e ), parent_id ); json_collector.Add( json ); foreach( TreeNode node in m_childNodes ) { node.DumpToJsonBottomUp( json_collector, id ); } } /// <summary> /// Return a JSON string representing this node and /// including the recursive hierarchical graph of /// all its all children. /// </summary> public string DumpToJsonTopDown() { Element e = GetElementById( m_Id ); List<string> json_collector = new List<string>(); foreach( TreeNode child in m_childNodes ) { json_collector.Add( child.DumpToJsonTopDown() ); } string json = CreateJsonParentNode( GetId( e ), GetName( e ), json_collector.ToArray() ); // Todo: properties print return json; } #endregion // JSON Output #region XML Output /// <summary> /// Dump the node into XML file. /// </summary> public void DumpIntoXML( XmlWriter writer ) { // Write node information Element element = GetElementById( m_Id ); FamilyInstance fi = element as FamilyInstance; if( fi != null ) { MEPModel mepModel = fi.MEPModel; String type = String.Empty; if( mepModel is MechanicalEquipment ) { type = "MechanicalEquipment"; writer.WriteStartElement( type ); } else if( mepModel is MechanicalFitting ) { MechanicalFitting mf = mepModel as MechanicalFitting; type = "MechanicalFitting"; writer.WriteStartElement( type ); writer.WriteAttributeString( "Category", element.Category.Name ); writer.WriteAttributeString( "PartType", mf.PartType.ToString() ); } else { type = "FamilyInstance"; writer.WriteStartElement( type ); writer.WriteAttributeString( "Category", element.Category.Name ); } writer.WriteAttributeString( "Name", element.Name ); writer.WriteAttributeString( "Id", element.Id.IntegerValue.ToString() ); writer.WriteAttributeString( "Direction", m_direction.ToString() ); writer.WriteEndElement(); } else { String type = element.GetType().Name; writer.WriteStartElement( type ); writer.WriteAttributeString( "Name", element.Name ); writer.WriteAttributeString( "Id", element.Id.IntegerValue.ToString() ); writer.WriteAttributeString( "Direction", m_direction.ToString() ); writer.WriteEndElement(); } foreach( TreeNode node in m_childNodes ) { if( m_childNodes.Count > 1 ) { writer.WriteStartElement( "Path" ); } node.DumpIntoXML( writer ); if( m_childNodes.Count > 1 ) { writer.WriteEndElement(); } } } #endregion // XML Output public void CollectUniqueIds( StringBuilder sb ) { Element element = GetElementById( this.m_Id ); sb.Append( "\"" + GetId( element ) + "\"," ); foreach( TreeNode node in this.m_childNodes ) { node.CollectUniqueIds( sb ); } } } /// <summary> /// Data structure of the system traversal /// </summary> public class TraversalTree { public static byte MECHANICAL_MASK = 1; public static byte ELECTRICAL_MASK = 2; public static byte PIPING_MAKS = 4; #region Member variables /// <summary> /// Active Revit document /// </summary> private Document m_document; /// <summary> /// The MEP system of the traversal /// </summary> private MEPSystem m_system; /// <summary> /// Flag whether the MEP system is mechanical or piping /// </summary> private Boolean m_isMechanicalSystem; /// <summary> /// The starting element node /// </summary> private TreeNode m_startingElementNode; /// <summary> /// Map element id integer to the number /// of times the element has been visited. /// </summary> Dictionary<int, int> _visitedElementCount; #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="activeDocument">Revit document</param> /// <param name="system">The MEP system to traverse</param> public TraversalTree( MEPSystem system ) { m_document = system.Document; m_system = system; m_isMechanicalSystem = ( system is MechanicalSystem ); _visitedElementCount = new Dictionary<int, int>(); } #endregion // Constructor #region Tree Construction /// <summary> /// Traverse the system /// </summary> public bool Traverse() { // Get the starting element node m_startingElementNode = GetStartingElementNode(); if( null != m_startingElementNode ) { // Traverse the system recursively Traverse( m_startingElementNode ); } return null != m_startingElementNode; } /// <summary> /// Get the starting element node. /// If the system has base equipment then get it; /// Otherwise get the owner of the open connector in the system /// </summary> /// <returns>The starting element node</returns> private TreeNode GetStartingElementNode() { TreeNode startingElementNode = null; FamilyInstance equipment = m_system.BaseEquipment; // // If the system has base equipment then get it; // Otherwise get the owner of the open connector in the system if( equipment != null ) { startingElementNode = new TreeNode( m_document, equipment.Id ); } else { Element root = GetOwnerOfOpenConnector(); if( null != root ) { startingElementNode = new TreeNode( m_document, root.Id ); } } if( null != startingElementNode ) { startingElementNode.Parent = null; startingElementNode.InputConnector = null; } return startingElementNode; } /// <summary> /// Get the owner of the open connector as the starting element /// </summary> /// <returns>The owner</returns> private Element GetOwnerOfOpenConnector() { Element element = null; // // Get an element from the system's terminals ElementSet elements = m_system.Elements; foreach( Element ele in elements ) { element = ele; break; } // Get the open connector recursively Connector openConnector = GetOpenConnector( element, null ); return null != openConnector ? openConnector.Owner : null; } /// <summary> /// Get the open connector of the system if the system has no base equipment /// </summary> /// <param name="element">An element in the system</param> /// <param name="inputConnector">The connector of the previous element /// to which the element is connected </param> /// <returns>The found open connector</returns> private Connector GetOpenConnector( Element element, Connector inputConnector ) { Connector openConnector = null; ConnectorManager cm = null; // // Get the connector manager of the element if( element is FamilyInstance ) { FamilyInstance fi = element as FamilyInstance; cm = fi.MEPModel.ConnectorManager; } else { MEPCurve mepCurve = element as MEPCurve; cm = mepCurve.ConnectorManager; } foreach( Connector conn in cm.Connectors ) { // Ignore the connector does not belong to any MEP System or belongs to another different MEP system if( conn.MEPSystem == null || !conn.MEPSystem.Id.IntegerValue.Equals( m_system.Id.IntegerValue ) ) { continue; } // If the connector is connected to the input connector, they will have opposite flow directions. if( inputConnector != null && conn.IsConnectedTo( inputConnector ) ) { continue; } // If the connector is not connected, it is the open connector if( !conn.IsConnected ) { openConnector = conn; break; } // // If open connector not found, then look for it from elements connected to the element foreach( Connector refConnector in conn.AllRefs ) { // Ignore non-EndConn connectors and connectors of the current element if( refConnector.ConnectorType != ConnectorType.End || refConnector.Owner.Id.IntegerValue.Equals( conn.Owner.Id.IntegerValue ) ) { continue; } // Ignore connectors of the previous element if( inputConnector != null && refConnector.Owner.Id.IntegerValue.Equals( inputConnector.Owner.Id.IntegerValue ) ) { continue; } openConnector = GetOpenConnector( refConnector.Owner, conn ); if( openConnector != null ) { return openConnector; } } } return openConnector; } /// <summary> /// Traverse the system recursively by analyzing each element /// </summary> /// <param name="elementNode">The element to be analyzed</param> private void Traverse( TreeNode elementNode ) { int id = elementNode.Id.IntegerValue; // Terminate if we revisit a node we have already inspected: if( _visitedElementCount.ContainsKey( id ) ) { return; } // Otherwise, add the new node to the collection of visited elements: if( !_visitedElementCount.ContainsKey( id ) ) { _visitedElementCount.Add( id, 0 ); } ++_visitedElementCount[id]; // // Find all child nodes and analyze them recursively AppendChildren( elementNode ); foreach( TreeNode node in elementNode.ChildNodes ) { Traverse( node ); } } /// <summary> /// Find all child nodes of the specified element node /// </summary> /// <param name="elementNode">The specified element node to be analyzed</param> private void AppendChildren( TreeNode elementNode ) { List<TreeNode> nodes = elementNode.ChildNodes; ConnectorSet connectors; // Get connector manager Element element = GetElementById( elementNode.Id ); //Debug.Print( element.Id.IntegerValue.ToString() ); FamilyInstance fi = element as FamilyInstance; if( fi != null ) { connectors = fi.MEPModel.ConnectorManager.Connectors; } else { MEPCurve mepCurve = element as MEPCurve; connectors = mepCurve.ConnectorManager.Connectors; } // Find connected connector for each connector foreach( Connector connector in connectors ) { MEPSystem mepSystem = connector.MEPSystem; // Ignore the connector does not belong to any MEP System or belongs to another different MEP system if( mepSystem == null || !mepSystem.Id.IntegerValue.Equals( m_system.Id.IntegerValue ) ) { continue; } // // Get the direction of the TreeNode object if( elementNode.Parent == null ) { if( connector.IsConnected ) { elementNode.Direction = connector.Direction; } } else { // If the connector is connected to the input connector, they will have opposite flow directions. // Then skip it. if( connector.IsConnectedTo( elementNode.InputConnector ) ) { elementNode.Direction = connector.Direction; continue; } } // Get the connector connected to current connector Connector connectedConnector = GetConnectedConnector( connector ); if( connectedConnector != null ) { TreeNode node = new TreeNode( m_document, connectedConnector.Owner.Id ); node.InputConnector = connector; node.Parent = elementNode; nodes.Add( node ); } } nodes.Sort( delegate ( TreeNode t1, TreeNode t2 ) { return t1.Id.IntegerValue > t2.Id.IntegerValue ? 1 : ( t1.Id.IntegerValue < t2.Id.IntegerValue ? -1 : 0 ); } ); } /// <summary> /// Get the connected connector of one connector /// </summary> /// <param name="connector">The connector to be analyzed</param> /// <returns>The connected connector</returns> static private Connector GetConnectedConnector( Connector connector ) { Connector connectedConnector = null; ConnectorSet allRefs = connector.AllRefs; foreach( Connector conn in allRefs ) { // Ignore non-EndConn connectors and connectors of the current element if( conn.ConnectorType != ConnectorType.End || conn.Owner.Id.IntegerValue.Equals( connector.Owner.Id.IntegerValue ) ) { continue; } connectedConnector = conn; break; } return connectedConnector; } /// <summary> /// Get element by its id /// </summary> private Element GetElementById( ElementId eid ) { return m_document.GetElement( eid ); } #endregion // Tree Construction #region JSON Output /// <summary> /// Dump the top-down traversal graph into JSON. /// In this case, each parent node is populated /// with a full hierarchical graph of all its /// children, cf. https://www.jstree.com/docs/json. /// </summary> public string DumpToJsonTopDown() { return m_startingElementNode .DumpToJsonTopDown(); } /// <summary> /// Dump the bottom-up traversal graph into JSON. /// In this case, each child node is equipped with /// a 'parent' pointer, cf. /// https://www.jstree.com/docs/json/ /// </summary> public string DumpToJsonBottomUp() { List<string> a = new List<string>(); m_startingElementNode.DumpToJsonBottomUp( a, "#" ); return "[" + string.Join( ",", a ) + "]"; } #endregion // JSON Output #region XML Output /// <summary> /// Dump the traversal into an XML file /// </summary> /// <param name="fileName">Name of the XML file</param> public void DumpIntoXML( String fileName ) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; XmlWriter writer = XmlWriter.Create( fileName, settings ); // Write the root element String mepSystemType = String.Empty; mepSystemType = ( m_system is MechanicalSystem ? "MechanicalSystem" : "PipingSystem" ); writer.WriteStartElement( mepSystemType ); // Write basic information of the MEP system WriteBasicInfo( writer ); // Write paths of the traversal WritePaths( writer ); // Close the root element writer.WriteEndElement(); writer.Flush(); writer.Close(); } /// <summary> /// Write basic information of the MEP system into the XML file /// </summary> /// <param name="writer">XMLWriter object</param> private void WriteBasicInfo( XmlWriter writer ) { MechanicalSystem ms = null; PipingSystem ps = null; if( m_isMechanicalSystem ) { ms = m_system as MechanicalSystem; } else { ps = m_system as PipingSystem; } // Write basic information of the system writer.WriteStartElement( "BasicInformation" ); // Write Name property writer.WriteStartElement( "Name" ); writer.WriteString( m_system.Name ); writer.WriteEndElement(); // Write Id property writer.WriteStartElement( "Id" ); writer.WriteValue( m_system.Id.IntegerValue ); writer.WriteEndElement(); // Write UniqueId property writer.WriteStartElement( "UniqueId" ); writer.WriteString( m_system.UniqueId ); writer.WriteEndElement(); // Write SystemType property writer.WriteStartElement( "SystemType" ); if( m_isMechanicalSystem ) { writer.WriteString( ms.SystemType.ToString() ); } else { writer.WriteString( ps.SystemType.ToString() ); } writer.WriteEndElement(); // Write Category property writer.WriteStartElement( "Category" ); writer.WriteAttributeString( "Id", m_system.Category.Id.IntegerValue.ToString() ); writer.WriteAttributeString( "Name", m_system.Category.Name ); writer.WriteEndElement(); // Write IsWellConnected property writer.WriteStartElement( "IsWellConnected" ); if( m_isMechanicalSystem ) { writer.WriteValue( ms.IsWellConnected ); } else { writer.WriteValue( ps.IsWellConnected ); } writer.WriteEndElement(); // Write HasBaseEquipment property writer.WriteStartElement( "HasBaseEquipment" ); bool hasBaseEquipment = ( ( m_system.BaseEquipment == null ) ? false : true ); writer.WriteValue( hasBaseEquipment ); writer.WriteEndElement(); // Write TerminalElementsCount property writer.WriteStartElement( "TerminalElementsCount" ); writer.WriteValue( m_system.Elements.Size ); writer.WriteEndElement(); // Write Flow property //writer.WriteStartElement( "Flow" ); //if( m_isMechanicalSystem ) //{ // writer.WriteValue( ms.GetFlow() ); //} //else //{ // writer.WriteValue( ps.GetFlow() ); //} //writer.WriteEndElement(); // Close basic information writer.WriteEndElement(); } /// <summary> /// Write paths of the traversal into the XML file /// </summary> /// <param name="writer">XMLWriter object</param> private void WritePaths( XmlWriter writer ) { writer.WriteStartElement( "Path" ); m_startingElementNode.DumpIntoXML( writer ); writer.WriteEndElement(); } public void CollectUniqueIds( StringBuilder[] sbs ) { StringBuilder conn_sb = new StringBuilder(); if( this.m_startingElementNode != null ) { conn_sb.Append( "{ \"id\":\"" + TreeNode.GetId( m_system ) + "\",\"name\":\"" + TreeNode.GetName( m_system ) + "\", \"children\":[], \"udids\":[" ); this.m_startingElementNode.CollectUniqueIds( conn_sb ); if( conn_sb[conn_sb.Length - 1] == ',' ) { conn_sb.Remove( conn_sb.Length - 1, 1 ); } conn_sb.Append( "]}," ); string str = conn_sb.ToString(); if( this.m_system is MechanicalSystem ) { sbs[0].Append( str ); } if( this.m_system is ElectricalSystem ) { sbs[1].Append( str ); } if( this.m_system is PipingSystem ) { sbs[2].Append( str ); } } } #endregion // XML Output } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class SimSet : SimObject { public SimSet() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.SimSetCreateInstance()); } public SimSet(uint pId) : base(pId) { } public SimSet(string pName) : base(pName) { } public SimSet(IntPtr pObjPtr) : base(pObjPtr) { } public SimSet(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public SimSet(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _SimSetCreateInstance(); private static _SimSetCreateInstance _SimSetCreateInstanceFunc; internal static IntPtr SimSetCreateInstance() { if (_SimSetCreateInstanceFunc == null) { _SimSetCreateInstanceFunc = (_SimSetCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetCreateInstance"), typeof(_SimSetCreateInstance)); } return _SimSetCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetListObjects(IntPtr set); private static _SimSetListObjects _SimSetListObjectsFunc; internal static void SimSetListObjects(IntPtr set) { if (_SimSetListObjectsFunc == null) { _SimSetListObjectsFunc = (_SimSetListObjects)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetListObjects"), typeof(_SimSetListObjects)); } _SimSetListObjectsFunc(set); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetAdd(IntPtr set, IntPtr obj); private static _SimSetAdd _SimSetAddFunc; internal static void SimSetAdd(IntPtr set, IntPtr obj) { if (_SimSetAddFunc == null) { _SimSetAddFunc = (_SimSetAdd)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetAdd"), typeof(_SimSetAdd)); } _SimSetAddFunc(set, obj); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetRemove(IntPtr set, IntPtr obj); private static _SimSetRemove _SimSetRemoveFunc; internal static void SimSetRemove(IntPtr set, IntPtr obj) { if (_SimSetRemoveFunc == null) { _SimSetRemoveFunc = (_SimSetRemove)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetRemove"), typeof(_SimSetRemove)); } _SimSetRemoveFunc(set, obj); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetDeleteObjects(IntPtr set); private static _SimSetDeleteObjects _SimSetDeleteObjectsFunc; internal static void SimSetDeleteObjects(IntPtr set) { if (_SimSetDeleteObjectsFunc == null) { _SimSetDeleteObjectsFunc = (_SimSetDeleteObjects)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetDeleteObjects"), typeof(_SimSetDeleteObjects)); } _SimSetDeleteObjectsFunc(set); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetClear(IntPtr set); private static _SimSetClear _SimSetClearFunc; internal static void SimSetClear(IntPtr set) { if (_SimSetClearFunc == null) { _SimSetClearFunc = (_SimSetClear)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetClear"), typeof(_SimSetClear)); } _SimSetClearFunc(set); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetCallOnChildren(IntPtr set, string method, int argc, string[] argv); private static _SimSetCallOnChildren _SimSetCallOnChildrenFunc; internal static void SimSetCallOnChildren(IntPtr set, string method, int argc, string[] argv) { if (_SimSetCallOnChildrenFunc == null) { _SimSetCallOnChildrenFunc = (_SimSetCallOnChildren)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetCallOnChildren"), typeof(_SimSetCallOnChildren)); } _SimSetCallOnChildrenFunc(set, method, argc, argv); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetReorderChild(IntPtr set, IntPtr obj1, IntPtr obj2); private static _SimSetReorderChild _SimSetReorderChildFunc; internal static void SimSetReorderChild(IntPtr set, IntPtr obj1, IntPtr obj2) { if (_SimSetReorderChildFunc == null) { _SimSetReorderChildFunc = (_SimSetReorderChild)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetReorderChild"), typeof(_SimSetReorderChild)); } _SimSetReorderChildFunc(set, obj1, obj2); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _SimSetGetCount(IntPtr set); private static _SimSetGetCount _SimSetGetCountFunc; internal static int SimSetGetCount(IntPtr set) { if (_SimSetGetCountFunc == null) { _SimSetGetCountFunc = (_SimSetGetCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetGetCount"), typeof(_SimSetGetCount)); } return _SimSetGetCountFunc(set); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _SimSetGetObject(IntPtr set, int index); private static _SimSetGetObject _SimSetGetObjectFunc; internal static IntPtr SimSetGetObject(IntPtr set, int index) { if (_SimSetGetObjectFunc == null) { _SimSetGetObjectFunc = (_SimSetGetObject)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetGetObject"), typeof(_SimSetGetObject)); } return _SimSetGetObjectFunc(set, index); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _SimSetIsMember(IntPtr set, IntPtr obj); private static _SimSetIsMember _SimSetIsMemberFunc; internal static bool SimSetIsMember(IntPtr set, IntPtr obj) { if (_SimSetIsMemberFunc == null) { _SimSetIsMemberFunc = (_SimSetIsMember)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetIsMember"), typeof(_SimSetIsMember)); } return _SimSetIsMemberFunc(set, obj); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _SimSetFindObjectByInternalName(IntPtr set, string name, bool searchChildren); private static _SimSetFindObjectByInternalName _SimSetFindObjectByInternalNameFunc; internal static IntPtr SimSetFindObjectByInternalName(IntPtr set, string name, bool searchChildren) { if (_SimSetFindObjectByInternalNameFunc == null) { _SimSetFindObjectByInternalNameFunc = (_SimSetFindObjectByInternalName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetFindObjectByInternalName"), typeof(_SimSetFindObjectByInternalName)); } return _SimSetFindObjectByInternalNameFunc(set, name, searchChildren); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetBringToFront(IntPtr set, IntPtr obj); private static _SimSetBringToFront _SimSetBringToFrontFunc; internal static void SimSetBringToFront(IntPtr set, IntPtr obj) { if (_SimSetBringToFrontFunc == null) { _SimSetBringToFrontFunc = (_SimSetBringToFront)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetBringToFront"), typeof(_SimSetBringToFront)); } _SimSetBringToFrontFunc(set, obj); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _SimSetPushToBack(IntPtr set, IntPtr obj); private static _SimSetPushToBack _SimSetPushToBackFunc; internal static void SimSetPushToBack(IntPtr set, IntPtr obj) { if (_SimSetPushToBackFunc == null) { _SimSetPushToBackFunc = (_SimSetPushToBack)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "SimSetPushToBack"), typeof(_SimSetPushToBack)); } _SimSetPushToBackFunc(set, obj); } } #endregion #region Properties #endregion #region Methods public void ListObjects() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetListObjects(ObjectPtr->ObjPtr); } public void Add(SimObject obj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetAdd(ObjectPtr->ObjPtr, obj.ObjectPtr->ObjPtr); } public void Remove(SimObject obj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetRemove(ObjectPtr->ObjPtr, obj.ObjectPtr->ObjPtr); } public void DeleteObjects() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetDeleteObjects(ObjectPtr->ObjPtr); } public void Clear() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetClear(ObjectPtr->ObjPtr); } public void CallOnChildren(string method, int argc, string[] argv) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetCallOnChildren(ObjectPtr->ObjPtr, method, argc, argv); } public void ReorderChild(SimObject obj1, SimObject obj2) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetReorderChild(ObjectPtr->ObjPtr, obj1.ObjectPtr->ObjPtr, obj2.ObjectPtr->ObjPtr); } public int GetCount() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.SimSetGetCount(ObjectPtr->ObjPtr); } public SimObject GetObject(int index) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new SimObject(InternalUnsafeMethods.SimSetGetObject(ObjectPtr->ObjPtr, index)); } public bool IsMember(SimObject obj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.SimSetIsMember(ObjectPtr->ObjPtr, obj.ObjectPtr->ObjPtr); } public SimObject FindObjectByInternalName(string name, bool searchChildren = false) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new SimObject(InternalUnsafeMethods.SimSetFindObjectByInternalName(ObjectPtr->ObjPtr, name, searchChildren)); } public void BringToFront(SimObject obj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetBringToFront(ObjectPtr->ObjPtr, obj.ObjectPtr->ObjPtr); } public void PushToBack(SimObject obj) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.SimSetPushToBack(ObjectPtr->ObjPtr, obj.ObjectPtr->ObjPtr); } #endregion } }
//----------------------------------------------------------------------- // <copyright file="Shape.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Akka.Streams.Implementation; namespace Akka.Streams { /// <summary> /// An input port of a <see cref="IModule"/>. This type logically belongs /// into the impl package but must live here due to how sealed works. /// It is also used in the Java DSL for "untyped Inlets" as a work-around /// for otherwise unreasonable existential types. /// </summary> public abstract class InPort { /// <summary> /// TBD /// </summary> internal int Id = -1; } /// <summary> /// An output port of a StreamLayout.Module. This type logically belongs /// into the impl package but must live here due to how sealed works. /// It is also used in the Java DSL for "untyped Outlets" as a work-around /// for otherwise unreasonable existential types. /// </summary> public abstract class OutPort { /// <summary> /// TBD /// </summary> internal int Id = -1; } /// <summary> /// An Inlet is a typed input to a Shape. Its partner in the Module view /// is the InPort(which does not bear an element type because Modules only /// express the internal structural hierarchy of stream topologies). /// </summary> public abstract class Inlet : InPort { /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="inlet">TBD</param> /// <returns>TBD</returns> public static Inlet<T> Create<T>(Inlet inlet) => inlet as Inlet<T> ?? new Inlet<T>(inlet.Name); /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the specified <paramref name="name"/> is undefined. /// </exception> protected Inlet(string name) { if (name == null) throw new ArgumentException("Inlet name must be defined"); Name = name; } /// <summary> /// TBD /// </summary> public readonly string Name; /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public abstract Inlet CarbonCopy(); /// <inheritdoc/> public sealed override string ToString() => Name; } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class Inlet<T> : Inlet { /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> public Inlet(string name) : base(name) { } /// <summary> /// TBD /// </summary> /// <typeparam name="TOther">TBD</typeparam> /// <returns>TBD</returns> internal Inlet<TOther> As<TOther>() => Create<TOther>(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Inlet CarbonCopy() => new Inlet<T>(Name); } /// <summary> /// An Outlet is a typed output to a Shape. Its partner in the Module view /// is the OutPort(which does not bear an element type because Modules only /// express the internal structural hierarchy of stream topologies). /// </summary> public abstract class Outlet : OutPort { /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="outlet">TBD</param> /// <returns>TBD</returns> public static Outlet<T> Create<T>(Outlet outlet) => outlet as Outlet<T> ?? new Outlet<T>(outlet.Name); /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> protected Outlet(string name) { Name = name; } /// <summary> /// TBD /// </summary> public readonly string Name; /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public abstract Outlet CarbonCopy(); /// <inheritdoc/> public sealed override string ToString() => Name; } /// <summary> /// TBD /// </summary> public sealed class Outlet<T> : Outlet { /// <summary> /// TBD /// </summary> /// <param name="name">TBD</param> public Outlet(string name) : base(name) { } /// <summary> /// TBD /// </summary> /// <typeparam name="TOther">TBD</typeparam> /// <returns>TBD</returns> internal Outlet<TOther> As<TOther>() => Create<TOther>(this); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Outlet CarbonCopy() => new Outlet<T>(Name); } /// <summary> /// A Shape describes the inlets and outlets of a <see cref="IGraph{TShape}"/>. In keeping with the /// philosophy that a Graph is a freely reusable blueprint, everything that /// matters from the outside are the connections that can be made with it, /// otherwise it is just a black box. /// </summary> public abstract class Shape #if CLONEABLE : ICloneable #endif { /// <summary> /// Gets list of all input ports. /// </summary> public abstract ImmutableArray<Inlet> Inlets { get; } /// <summary> /// Gets list of all output ports. /// </summary> public abstract ImmutableArray<Outlet> Outlets { get; } /// <summary> /// Create a copy of this Shape object, returning the same type as the /// original; this constraint can unfortunately not be expressed in the /// type system. /// </summary> /// <returns>TBD</returns> public abstract Shape DeepCopy(); /// <summary> /// Create a copy of this Shape object, returning the same type as the /// original but containing the ports given within the passed-in Shape. /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <returns>TBD</returns> public abstract Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets); /// <summary> /// Compare this to another shape and determine whether the set of ports is the same (ignoring their ordering). /// </summary> /// <param name="shape">TBD</param> /// <returns>TBD</returns> public bool HasSamePortsAs(Shape shape) { var inlets = new HashSet<Inlet>(Inlets); var outlets = new HashSet<Outlet>(Outlets); return inlets.SetEquals(shape.Inlets) && outlets.SetEquals(shape.Outlets); } /// <summary> /// Compare this to another shape and determine whether the arrangement of ports is the same (including their ordering). /// </summary> /// <param name="shape">TBD</param> /// <returns>TBD</returns> public bool HasSamePortsAndShapeAs(Shape shape) => Inlets.Equals(shape.Inlets) && Outlets.Equals(shape.Outlets); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public object Clone() => DeepCopy(); /// <inheritdoc/> public sealed override string ToString() => $"{GetType().Name}([{string.Join(", ", Inlets)}] [{string.Join(", ", Outlets)}])"; } /// <summary> /// This <see cref="Shape"/> is used for graphs that have neither open inputs nor open /// outputs. Only such a <see cref="IGraph{TShape,TMaterializer}"/> can be materialized by a <see cref="IMaterializer"/>. /// </summary> public class ClosedShape : Shape { /// <summary> /// TBD /// </summary> public static readonly ClosedShape Instance = new ClosedShape(); private ClosedShape() { } /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets => ImmutableArray<Inlet>.Empty; /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets => ImmutableArray<Outlet>.Empty; /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => this; /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero /// or the size of the specified <paramref name="outlets"/> array is zero. /// </exception> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (inlets.Any()) throw new ArgumentException("Proposed inlets do not fit ClosedShape", nameof(inlets)); if (outlets.Any()) throw new ArgumentException("Proposed outlets do not fit ClosedShape", nameof(outlets)); return this; } } /// <summary> /// This type of <see cref="Shape"/> can express any number of inputs and outputs at the /// expense of forgetting about their specific types. It is used mainly in the /// implementation of the <see cref="IGraph{TShape,TMaterializer}"/> builders and typically replaced by a more /// meaningful type of Shape when the building is finished. /// </summary> public class AmorphousShape : Shape { /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> public AmorphousShape(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { Inlets = inlets; Outlets = outlets; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => new AmorphousShape(Inlets.Select(i => i.CarbonCopy()).ToImmutableArray(),Outlets.Select(o => o.CarbonCopy()).ToImmutableArray()); /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) => new AmorphousShape(inlets, outlets); } /// <summary> /// A Source <see cref="Shape"/> has exactly one output and no inputs, it models a source of data. /// </summary> /// <typeparam name="TOut">TBD</typeparam> public sealed class SourceShape<TOut> : Shape { /// <summary> /// TBD /// </summary> /// <param name="outlet">TBD</param> /// <exception cref="ArgumentNullException">TBD</exception> public SourceShape(Outlet<TOut> outlet) { if (outlet == null) throw new ArgumentNullException(nameof(outlet)); Outlet = outlet; Outlets = ImmutableArray.Create<Outlet>(outlet); } /// <summary> /// TBD /// </summary> public readonly Outlet<TOut> Outlet; /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets => ImmutableArray<Inlet>.Empty; /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => new SourceShape<TOut>((Outlet<TOut>) Outlet.CarbonCopy()); /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero /// or the size of the specified <paramref name="outlets"/> array is one. /// </exception> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (inlets.Length != 0) throw new ArgumentException("Proposed inlets do not fit SourceShape", nameof(inlets)); if (outlets.Length != 1) throw new ArgumentException("Proposed outlets do not fit SourceShape", nameof(outlets)); return new SourceShape<TOut>(outlets[0] as Outlet<TOut>); } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SourceShape<TOut> && Equals((SourceShape<TOut>) obj); } /// <inheritdoc/> private bool Equals(SourceShape<TOut> other) => Outlet.Equals(other.Outlet); /// <inheritdoc/> public override int GetHashCode() => Outlet.GetHashCode(); } /// <summary> /// TBD /// </summary> public interface IFlowShape { /// <summary> /// TBD /// </summary> Inlet Inlet { get; } /// <summary> /// TBD /// </summary> Outlet Outlet { get; } } /// <summary> /// A Flow <see cref="Shape"/> has exactly one input and one output, it looks from the /// outside like a pipe (but it can be a complex topology of streams within of course). /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> public sealed class FlowShape<TIn, TOut> : Shape, IFlowShape { /// <summary> /// TBD /// </summary> /// <param name="inlet">TBD</param> /// <param name="outlet">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when either the specified <paramref name="inlet"/> or <paramref name="outlet"/> is undefined. /// </exception> public FlowShape(Inlet<TIn> inlet, Outlet<TOut> outlet) { if (inlet == null) throw new ArgumentNullException(nameof(inlet), "FlowShape expected non-null inlet"); if (outlet == null) throw new ArgumentNullException(nameof(outlet), "FlowShape expected non-null outlet"); Inlet = inlet; Outlet = outlet; Inlets = ImmutableArray.Create<Inlet>(inlet); Outlets = ImmutableArray.Create<Outlet>(outlet); } Inlet IFlowShape.Inlet => Inlet; Outlet IFlowShape.Outlet => Outlet; /// <summary> /// TBD /// </summary> public Inlet<TIn> Inlet { get; } /// <summary> /// TBD /// </summary> public Outlet<TOut> Outlet { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => new FlowShape<TIn, TOut>((Inlet<TIn>) Inlet.CarbonCopy(), (Outlet<TOut>) Outlet.CarbonCopy()); /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the size of the specified <paramref name="inlets"/> array is one /// or the size of the specified <paramref name="outlets"/> array is one. /// </exception> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (inlets.Length != 1) throw new ArgumentException("Proposed inlets do not fit FlowShape", nameof(inlets)); if (outlets.Length != 1) throw new ArgumentException("Proposed outlets do not fit FlowShape", nameof(outlets)); return new FlowShape<TIn, TOut>(inlets[0] as Inlet<TIn>, outlets[0] as Outlet<TOut>); } } /// <summary> /// A Sink <see cref="Shape"/> has exactly one input and no outputs, it models a data sink. /// </summary> /// <typeparam name="TIn">TBD</typeparam> public sealed class SinkShape<TIn> : Shape { /// <summary> /// TBD /// </summary> public readonly Inlet<TIn> Inlet; /// <summary> /// TBD /// </summary> /// <param name="inlet">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when the specified <paramref name="inlet"/> is undefined. /// </exception> public SinkShape(Inlet<TIn> inlet) { if (inlet == null) throw new ArgumentNullException(nameof(inlet), "SinkShape expected non-null inlet"); Inlet = inlet; Inlets = ImmutableArray.Create<Inlet>(inlet); } /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets => ImmutableArray<Outlet>.Empty; /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() => new SinkShape<TIn>((Inlet<TIn>) Inlet.CarbonCopy()); /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the size of the specified <paramref name="inlets"/> array is zero /// or the size of the specified <paramref name="outlets"/> array is one. /// </exception> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (outlets.Length != 0) throw new ArgumentException("Proposed outlets do not fit SinkShape", nameof(outlets)); if (inlets.Length != 1) throw new ArgumentException("Proposed inlets do not fit SinkShape", nameof(inlets)); return new SinkShape<TIn>(inlets[0] as Inlet<TIn>); } /// <inheritdoc/> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SinkShape<TIn> && Equals((SinkShape<TIn>) obj); } private bool Equals(SinkShape<TIn> other) => Equals(Inlet, other.Inlet); /// <inheritdoc/> public override int GetHashCode() => Inlet.GetHashCode(); } /// <summary> /// A bidirectional flow of elements that consequently has two inputs and two outputs. /// </summary> /// <typeparam name="TIn1">TBD</typeparam> /// <typeparam name="TOut1">TBD</typeparam> /// <typeparam name="TIn2">TBD</typeparam> /// <typeparam name="TOut2">TBD</typeparam> public sealed class BidiShape<TIn1, TOut1, TIn2, TOut2> : Shape { /// <summary> /// TBD /// </summary> public readonly Inlet<TIn1> Inlet1; /// <summary> /// TBD /// </summary> public readonly Inlet<TIn2> Inlet2; /// <summary> /// TBD /// </summary> public readonly Outlet<TOut1> Outlet1; /// <summary> /// TBD /// </summary> public readonly Outlet<TOut2> Outlet2; /// <summary> /// TBD /// </summary> /// <param name="in1">TBD</param> /// <param name="out1">TBD</param> /// <param name="in2">TBD</param> /// <param name="out2">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when either the specified <paramref name="in1"/>, <paramref name="out1"/>, /// <paramref name="in2"/>, or <paramref name="out2"/> is undefined. /// </exception> public BidiShape(Inlet<TIn1> in1, Outlet<TOut1> out1, Inlet<TIn2> in2, Outlet<TOut2> out2) { if (in1 == null) throw new ArgumentNullException(nameof(in1)); if (out1 == null) throw new ArgumentNullException(nameof(out1)); if (in2 == null) throw new ArgumentNullException(nameof(in2)); if (out2 == null) throw new ArgumentNullException(nameof(out2)); Inlet1 = in1; Inlet2 = in2; Outlet1 = out1; Outlet2 = out2; Inlets = ImmutableArray.Create<Inlet>(Inlet1, Inlet2); Outlets = ImmutableArray.Create<Outlet>(Outlet1, Outlet2); } /// <summary> /// TBD /// </summary> /// <param name="top">TBD</param> /// <param name="bottom">TBD</param> public BidiShape(FlowShape<TIn1, TOut1> top, FlowShape<TIn2, TOut2> bottom) : this(top.Inlet, top.Outlet, bottom.Inlet, bottom.Outlet) { } /// <summary> /// TBD /// </summary> public override ImmutableArray<Inlet> Inlets { get; } /// <summary> /// TBD /// </summary> public override ImmutableArray<Outlet> Outlets { get; } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public override Shape DeepCopy() { return new BidiShape<TIn1, TOut1, TIn2, TOut2>( (Inlet<TIn1>) Inlet1.CarbonCopy(), (Outlet<TOut1>) Outlet1.CarbonCopy(), (Inlet<TIn2>) Inlet2.CarbonCopy(), (Outlet<TOut2>) Outlet2.CarbonCopy()); } /// <summary> /// TBD /// </summary> /// <param name="inlets">TBD</param> /// <param name="outlets">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the size of the specified <paramref name="inlets"/> array is two /// or the size of the specified <paramref name="outlets"/> array is two. /// </exception> /// <returns>TBD</returns> public override Shape CopyFromPorts(ImmutableArray<Inlet> inlets, ImmutableArray<Outlet> outlets) { if (inlets.Length != 2) throw new ArgumentException($"Proposed inlets [{string.Join(", ", inlets)}] don't fit BidiShape"); if (outlets.Length != 2) throw new ArgumentException($"Proposed outlets [{string.Join(", ", outlets)}] don't fit BidiShape"); return new BidiShape<TIn1, TOut1, TIn2, TOut2>((Inlet<TIn1>)inlets[0], (Outlet<TOut1>)outlets[0], (Inlet<TIn2>)inlets[1], (Outlet<TOut2>)outlets[1]); } /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public Shape Reversed() => new BidiShape<TIn2, TOut2, TIn1, TOut1>(Inlet2, Outlet2, Inlet1, Outlet1); } /// <summary> /// TBD /// </summary> public static class BidiShape { /// <summary> /// TBD /// </summary> /// <typeparam name="TIn1">TBD</typeparam> /// <typeparam name="TOut1">TBD</typeparam> /// <typeparam name="TIn2">TBD</typeparam> /// <typeparam name="TOut2">TBD</typeparam> /// <param name="top">TBD</param> /// <param name="bottom">TBD</param> /// <returns>TBD</returns> public static BidiShape<TIn1, TOut1, TIn2, TOut2> FromFlows<TIn1, TOut1, TIn2, TOut2>( FlowShape<TIn1, TOut1> top, FlowShape<TIn2, TOut2> bottom) => new BidiShape<TIn1, TOut1, TIn2, TOut2>(top.Inlet, top.Outlet, bottom.Inlet, bottom.Outlet); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MSCloudIPs.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, All rights reserved. // // File: BitmapSizeOptions.cs // //------------------------------------------------------------------------------ using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Imaging { #region BitmapSizeOptions /// <summary> /// Sizing options for an bitmap. The resulting bitmap /// will be scaled based on these options. /// </summary> public class BitmapSizeOptions { /// <summary> /// Construct an BitmapSizeOptions object. Still need to set the Width and Height Properties. /// </summary> private BitmapSizeOptions() { } /// <summary> /// Whether or not to preserve the aspect ratio of the original /// bitmap. If so, then the PixelWidth and PixelHeight are /// maximum values for the bitmap size. The resulting bitmap /// is only guaranteed to have either its width or its height /// match the specified values. For example, if you want to /// specify the height, while preserving the aspect ratio for /// the width, then set the height to the desired value, and /// set the width to Int32.MaxValue. /// /// If we are not to preserve aspect ratio, then both the /// specified width and the specified height are used, and /// the bitmap will be stretched to fit both those values. /// </summary> public bool PreservesAspectRatio { get { return _preservesAspectRatio; } } /// <summary> /// PixelWidth of the resulting bitmap. See description of /// PreserveAspectRatio for how this value is used. /// /// PixelWidth must be set to a value greater than zero to be valid. /// </summary> public int PixelWidth { get { return _pixelWidth; } } /// <summary> /// PixelHeight of the resulting bitmap. See description of /// PreserveAspectRatio for how this value is used. /// /// PixelHeight must be set to a value greater than zero to be valid. /// </summary> public int PixelHeight { get { return _pixelHeight; } } /// <summary> /// Rotation to rotate the bitmap. Only multiples of 90 are supported. /// </summary> public Rotation Rotation { get { return _rotationAngle; } } /// <summary> /// Constructs an identity BitmapSizeOptions (when passed to a TransformedBitmap, the /// input is the same as the output). /// </summary> public static BitmapSizeOptions FromEmptyOptions() { BitmapSizeOptions sizeOptions = new BitmapSizeOptions(); sizeOptions._rotationAngle = Rotation.Rotate0; sizeOptions._preservesAspectRatio = true; sizeOptions._pixelHeight = 0; sizeOptions._pixelWidth = 0; return sizeOptions; } /// <summary> /// Constructs an BitmapSizeOptions that preserves the aspect ratio and enforces a height of pixelHeight. /// </summary> /// <param name="pixelHeight">Height of the resulting Bitmap</param> public static BitmapSizeOptions FromHeight(int pixelHeight) { if (pixelHeight <= 0) { throw new System.ArgumentOutOfRangeException("pixelHeight", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } BitmapSizeOptions sizeOptions = new BitmapSizeOptions(); sizeOptions._rotationAngle = Rotation.Rotate0; sizeOptions._preservesAspectRatio = true; sizeOptions._pixelHeight = pixelHeight; sizeOptions._pixelWidth = 0; return sizeOptions; } /// <summary> /// Constructs an BitmapSizeOptions that preserves the aspect ratio and enforces a width of pixelWidth. /// </summary> /// <param name="pixelWidth">Width of the resulting Bitmap</param> public static BitmapSizeOptions FromWidth(int pixelWidth) { if (pixelWidth <= 0) { throw new System.ArgumentOutOfRangeException("pixelWidth", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } BitmapSizeOptions sizeOptions = new BitmapSizeOptions(); sizeOptions._rotationAngle = Rotation.Rotate0; sizeOptions._preservesAspectRatio = true; sizeOptions._pixelWidth = pixelWidth; sizeOptions._pixelHeight = 0; return sizeOptions; } /// <summary> /// Constructs an BitmapSizeOptions that does not preserve the aspect ratio and /// instead uses dimensions pixelWidth x pixelHeight. /// </summary> /// <param name="pixelWidth">Width of the resulting Bitmap</param> /// <param name="pixelHeight">Height of the resulting Bitmap</param> public static BitmapSizeOptions FromWidthAndHeight(int pixelWidth, int pixelHeight) { if (pixelWidth <= 0) { throw new System.ArgumentOutOfRangeException("pixelWidth", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } if (pixelHeight <= 0) { throw new System.ArgumentOutOfRangeException("pixelHeight", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } BitmapSizeOptions sizeOptions = new BitmapSizeOptions(); sizeOptions._rotationAngle = Rotation.Rotate0; sizeOptions._preservesAspectRatio = false; sizeOptions._pixelWidth = pixelWidth; sizeOptions._pixelHeight = pixelHeight; return sizeOptions; } /// <summary> /// Constructs an BitmapSizeOptions that does not preserve the aspect ratio and /// instead uses dimensions pixelWidth x pixelHeight. /// </summary> /// <param name="rotation">Angle to rotate</param> public static BitmapSizeOptions FromRotation(Rotation rotation) { switch(rotation) { case Rotation.Rotate0: case Rotation.Rotate90: case Rotation.Rotate180: case Rotation.Rotate270: break; default: throw new ArgumentException(SR.Get(SRID.Image_SizeOptionsAngle), "rotation"); } BitmapSizeOptions sizeOptions = new BitmapSizeOptions(); sizeOptions._rotationAngle = rotation; sizeOptions._preservesAspectRatio = true; sizeOptions._pixelWidth = 0; sizeOptions._pixelHeight = 0; return sizeOptions; } // Note: In this method, newWidth, newHeight are not affected by the // rotation angle. internal void GetScaledWidthAndHeight( uint width, uint height, out uint newWidth, out uint newHeight) { if (_pixelWidth == 0 && _pixelHeight != 0) { Debug.Assert(_preservesAspectRatio == true); newWidth = (uint)((_pixelHeight * width)/height); newHeight = (uint)_pixelHeight; } else if (_pixelWidth != 0 && _pixelHeight == 0) { Debug.Assert(_preservesAspectRatio == true); newWidth = (uint)_pixelWidth; newHeight = (uint)((_pixelWidth * height)/width); } else if (_pixelWidth != 0 && _pixelHeight != 0) { Debug.Assert(_preservesAspectRatio == false); newWidth = (uint)_pixelWidth; newHeight = (uint)_pixelHeight; } else { newWidth = width; newHeight = height; } } internal bool DoesScale { get { return (_pixelWidth != 0 || _pixelHeight != 0); } } internal WICBitmapTransformOptions WICTransformOptions { get { WICBitmapTransformOptions options = 0; switch (_rotationAngle) { case Rotation.Rotate0: options = WICBitmapTransformOptions.WICBitmapTransformRotate0; break; case Rotation.Rotate90: options = WICBitmapTransformOptions.WICBitmapTransformRotate90; break; case Rotation.Rotate180: options = WICBitmapTransformOptions.WICBitmapTransformRotate180; break; case Rotation.Rotate270: options = WICBitmapTransformOptions.WICBitmapTransformRotate270; break; default: Debug.Assert(false); break; } return options; } } private bool _preservesAspectRatio; private int _pixelWidth; private int _pixelHeight; private Rotation _rotationAngle; } #endregion // BitmapSizeOptions }
// FindBarTest.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using NUnit.Framework; using Layout; namespace Testing { [TestFixture] public class FindBarTest { public FindBarTest () { } /// <summary> /// Tests the position not changing when it should not. /// /// THE REASON for this test is a bug fix I made so that when you modify text during a search /// the Position is kept close to what the Position was before the text edit was made. This just /// makes editing a bit easier /// Feb 23 2013 /// </summary> [Test] public void TestPositionNotChangingWhenItShouldNot() { _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); RichTextExtended fakeText = new RichTextExtended(); form.Controls.Add (fakeText); fakeText.Text = "We have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. He is a nice dog. We all love dogs."; findBar.DoFind("dog", false,fakeText,0); Assert.AreEqual(3, findBar.PositionsFOUND(), "Found 3 dogs"); findBar.GoToNext(); findBar.GoToNext(); Assert.AreEqual (2, findBar.zPosition()); findBar.DoFindBuildLIstTesty(fakeText.Text); Assert.AreEqual (2, findBar.zPosition()); } [Test] public void TestAsterix() { _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); RichTextExtended fakeText = new RichTextExtended(); form.Controls.Add (fakeText); fakeText.Text = "We have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. He is a nice dog. We all love dogs."; findBar.DoFind("*dog", false,fakeText,0); Assert.AreEqual(0, findBar.PositionsFOUND(), "Found 0 *dogs"); // I removed the code that prevented typing asertixes. Do not remember why I had it. // make sure it does not crash\ } [Test] public void TestFindexact() { _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); RichTextExtended fakeText = new RichTextExtended(); form.Controls.Add (fakeText); fakeText.Text = "We corndog and have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. He is a nice dog. We all love dogs."; findBar.DoFind("dog", true,fakeText,0); Assert.AreEqual(2, findBar.PositionsFOUND(), "Found 2 *dogs"); // I removed the code that prevented typing asertixes. Do not remember why I had it. // make sure it does not crash\ } [Test] public void TestReplaceWorks() { _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); FAKE_NoteDataXML_Text fakeTextNote = new FAKE_NoteDataXML_Text(); fakeTextNote.Caption ="Fake Text Note"; panel.AddNote(fakeTextNote); fakeTextNote.CreateParent(panel); // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); //RichTextExtended fakeText = new RichTextExtended(); //form.Controls.Add (fakeText); LayoutDetails.Instance.CurrentLayout = panel; LayoutDetails.Instance.CurrentLayout.CurrentTextNote = fakeTextNote; panel.SetFindBar(findBar); findBar.SupressMode = true; //!= null && LayoutDetails.Instance.CurrentLayout.CurrentTextNote != null fakeTextNote.GetRichTextBox().Text = "We have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. And that cat. He is a nice dog. We all love dogs. Dogs are neat."; findBar.SetLastRichText(fakeTextNote.GetRichTextBox()); findBar.DoFind("dog", false,fakeTextNote.GetRichTextBox(),0); //need to rewrite 'find/repalce' to make accessible better to test? It crashes. Assert.AreEqual(4, findBar.PositionsFOUND(), "Found 4 dogs"); findBar.Replace_Text("dog", "cat"); findBar.DoFind("dog", false,fakeTextNote.GetRichTextBox(),0); Assert.AreEqual(0, findBar.PositionsFOUND(), "Found 0 dogs"); findBar.DoFind("cat", false,fakeTextNote.GetRichTextBox(),0); Assert.AreEqual(5, findBar.PositionsFOUND(), "Found 5 cats. 4 replacements + 1 original"); } [Test] public void TestReplaceWorks_WithSimiliarWORDS() { //NOTE: This will not work until I implement the Replace system improvements _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); FAKE_NoteDataXML_Text fakeTextNote = new FAKE_NoteDataXML_Text(); fakeTextNote.Caption ="Fake Text Note"; panel.AddNote(fakeTextNote); fakeTextNote.CreateParent(panel); // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); //RichTextExtended fakeText = new RichTextExtended(); //form.Controls.Add (fakeText); LayoutDetails.Instance.CurrentLayout = panel; LayoutDetails.Instance.CurrentLayout.CurrentTextNote = fakeTextNote; panel.SetFindBar(findBar); findBar.SupressMode = true; //!= null && LayoutDetails.Instance.CurrentLayout.CurrentTextNote != null fakeTextNote.GetRichTextBox().Text = "We have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. And that cat. He is a nice dog. We dog all love dogs. Dogs are neat."; findBar.SetLastRichText(fakeTextNote.GetRichTextBox()); findBar.DoFind("dog", false,fakeTextNote.GetRichTextBox(),0); //need to rewrite 'find/repalce' to make accessible better to test? It crashes. Assert.AreEqual(5, findBar.PositionsFOUND(), "Found 5 dogs"); findBar.Replace_Text("dog", "dog2"); findBar.DoFind("dog", false,fakeTextNote.GetRichTextBox(),0); Assert.AreEqual(5, findBar.PositionsFOUND(), "Found 5 dogs because we are doing a partial search"); findBar.DoFind("dog", true,fakeTextNote.GetRichTextBox(),0); Assert.AreEqual(0, findBar.PositionsFOUND(), "Found 0 dogs because we are doing an exact search NOTE: This will not work until I implement the Replace system improvements"); findBar.DoFind("dog2", false,fakeTextNote.GetRichTextBox(),0); Assert.AreEqual(5, findBar.PositionsFOUND(), "Found 4 dog2. 4 replacements NOTE: This will not work until I implement the Replace system improvements "); } [Test] public void AlLFindBarsAreTheSame() { // children panels have the same findbar as a parent _TestSingleTon.Instance._SetupForLayoutPanelTests(); System.Windows.Forms .Form form = new System.Windows.Forms.Form(); FAKE_LayoutPanel panel = new FAKE_LayoutPanel (CoreUtilities.Constants.BLANK, false); form.Controls.Add (panel); // needed else DataGrid does not initialize form.Show (); //form.Visible = false; //NOTE: For now remember that htis ADDS 1 Extra notes string panelname = System.Guid.NewGuid().ToString(); panel.NewLayout (panelname,true, null); LayoutDetails.Instance.AddToList (typeof(FAKE_NoteDataXML_Panel), "testingpanel"); FAKE_NoteDataXML_Panel panelA = new FAKE_NoteDataXML_Panel(); panelA.GuidForNote="panelA"; panel.AddNote(panelA); //panel.AddNote(panelA); Intentionally do not add this because it should bea failre // Won't actually add things properly because I need to override the findbar FAKE_FindBar findBar = new FAKE_FindBar(); form.Controls.Add (findBar); RichTextExtended fakeText = new RichTextExtended(); form.Controls.Add (fakeText); fakeText.Text = "We have a dog. His name is Jake." + Environment.NewLine + "We love him a lot. He is a nice dog. We all love dogs."; findBar.DoFind("dog", false,fakeText,0); Assert.AreEqual(panelA.GetPanelsLayout().GetFindbar(), panel.GetFindbar()); // Assert.AreEqual(panelB.GetPanelsLayout().GetFindbar(), panel.GetFindbar()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Interpolation utility functions: easing, bezier, and catmull-rom. * Consider using Unity's Animation curve editor and AnimationCurve class * before scripting the desired behaviour using this utility. * * Interpolation functionality available at different levels of abstraction. * Low level access via individual easing functions (ex. EaseInOutCirc), * Bezier(), and CatmullRom(). High level access using sequence generators, * NewEase(), NewBezier(), and NewCatmullRom(). * * Sequence generators are typically used as follows: * * IEnumerable<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration); * foreach (Vector3 newPoint in sequence) { * transform.position = newPoint; * yield return WaitForSeconds(1.0f); * } * * Or: * * IEnumerator<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration).GetEnumerator(); * function Update() { * if (sequence.MoveNext()) { * transform.position = sequence.Current; * } * } * * The low level functions work similarly to Unity's built in Lerp and it is * up to you to track and pass in elapsedTime and duration on every call. The * functions take this form (or the logical equivalent for Bezier() and CatmullRom()). * * transform.position = ease(start, distance, elapsedTime, duration); * * For convenience in configuration you can use the Ease(EaseType) function to * look up a concrete easing function: * * [SerializeField] * Interpolate.EaseType easeType; // set using Unity's property inspector * Interpolate.Function ease; // easing of a particular EaseType * function Awake() { * ease = Interpolate.Ease(easeType); * } * * @author Fernando Zapata (fernando@cpudreams.com) * @Traduzione Andrea85cs (andrea85cs@dynematica.it) */ public class Interpolate { /** * Different methods of easing interpolation. */ public enum EaseType { Linear, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInSine, EaseOutSine, EaseInOutSine, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc } /** * Sequence of eleapsedTimes until elapsedTime is >= duration. * * Note: elapsedTimes are calculated using the value of Time.deltatTime each * time a value is requested. */ static Vector3 Identity(Vector3 v) { return v; } static Vector3 TransformDotPosition(Transform t) { return t.position; } static IEnumerable<float> NewTimer(float duration) { float elapsedTime = 0.0f; while (elapsedTime < duration) { yield return elapsedTime; elapsedTime += Time.deltaTime; // make sure last value is never skipped if (elapsedTime >= duration) { yield return elapsedTime; } } } public delegate Vector3 ToVector3<T>(T v); public delegate float Function(float a, float b, float c, float d); /** * Generates sequence of integers from start to end (inclusive) one step * at a time. */ static IEnumerable<float> NewCounter(int start, int end, int step) { for (int i = start; i <= end; i += step) { yield return i; } } /** * Returns sequence generator from start to end over duration using the * given easing function. The sequence is generated as it is accessed * using the Time.deltaTime to calculate the portion of duration that has * elapsed. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewEase(ease, start, end, duration, timer); } /** * Instead of easing based on time, generate n interpolated points (slices) * between the start and end positions. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, int slices) { IEnumerable<float> counter = Interpolate.NewCounter(0, slices + 1, 1); return NewEase(ease, start, end, slices + 1, counter); } /** * Generic easing sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float total, IEnumerable<float> driver) { Vector3 distance = end - start; foreach (float i in driver) { yield return Ease(ease, start, distance, i, total); } } /** * Vector3 interpolation using given easing method. Easing is done independently * on all three vector axis. */ static Vector3 Ease(Function ease, Vector3 start, Vector3 distance, float elapsedTime, float duration) { start.x = ease(start.x, distance.x, elapsedTime, duration); start.y = ease(start.y, distance.y, elapsedTime, duration); start.z = ease(start.z, distance.z, elapsedTime, duration); return start; } /** * Returns the static method that implements the given easing type for scalars. * Use this method to easily switch between easing interpolation types. * * All easing methods clamp elapsedTime so that it is always <= duration. * * var ease = Interpolate.Ease(EaseType.EaseInQuad); * i = ease(start, distance, elapsedTime, duration); */ public static Function Ease(EaseType type) { // Source Flash easing functions: // http://gizma.com/easing/ // http://www.robertpenner.com/easing/easing_demo.html // // Changed to use more friendly variable names, that follow my Lerp // conventions: // start = b (start value) // distance = c (change in value) // elapsedTime = t (current time) // duration = d (time duration) Function f = null; switch (type) { case EaseType.Linear: f = Interpolate.Linear; break; case EaseType.EaseInQuad: f = Interpolate.EaseInQuad; break; case EaseType.EaseOutQuad: f = Interpolate.EaseOutQuad; break; case EaseType.EaseInOutQuad: f = Interpolate.EaseInOutQuad; break; case EaseType.EaseInCubic: f = Interpolate.EaseInCubic; break; case EaseType.EaseOutCubic: f = Interpolate.EaseOutCubic; break; case EaseType.EaseInOutCubic: f = Interpolate.EaseInOutCubic; break; case EaseType.EaseInQuart: f = Interpolate.EaseInQuart; break; case EaseType.EaseOutQuart: f = Interpolate.EaseOutQuart; break; case EaseType.EaseInOutQuart: f = Interpolate.EaseInOutQuart; break; case EaseType.EaseInQuint: f = Interpolate.EaseInQuint; break; case EaseType.EaseOutQuint: f = Interpolate.EaseOutQuint; break; case EaseType.EaseInOutQuint: f = Interpolate.EaseInOutQuint; break; case EaseType.EaseInSine: f = Interpolate.EaseInSine; break; case EaseType.EaseOutSine: f = Interpolate.EaseOutSine; break; case EaseType.EaseInOutSine: f = Interpolate.EaseInOutSine; break; case EaseType.EaseInExpo: f = Interpolate.EaseInExpo; break; case EaseType.EaseOutExpo: f = Interpolate.EaseOutExpo; break; case EaseType.EaseInOutExpo: f = Interpolate.EaseInOutExpo; break; case EaseType.EaseInCirc: f = Interpolate.EaseInCirc; break; case EaseType.EaseOutCirc: f = Interpolate.EaseOutCirc; break; case EaseType.EaseInOutCirc: f = Interpolate.EaseInOutCirc; break; } return f; } /** * Returns sequence generator from the first node to the last node over * duration time using the points in-between the first and last node * as control points of a bezier curve used to generate the interpolated points * in the sequence. If there are no control points (ie. only two nodes, first * and last) then this behaves exactly the same as NewEase(). In other words * a zero-degree bezier spline curve is just the easing method. The sequence * is generated as it is accessed using the Time.deltaTime to calculate the * portion of duration that has elapsed. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewBezier<Transform>(ease, nodes, TransformDotPosition, duration, timer); } /** * Instead of interpolating based on time, generate n interpolated points * (slices) between the first and last node. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Transform>(ease, nodes, TransformDotPosition, slices + 1, counter); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, float duration) { IEnumerable<float> timer = NewTimer(duration); return NewBezier<Vector3>(ease, points, Identity, duration, timer); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Vector3>(ease, points, Identity, slices + 1, counter); } /** * Generic bezier spline sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerable<Vector3> NewBezier<T>(Function ease, IList nodes, ToVector3<T> toVector3, float maxStep, IEnumerable<float> steps) { // need at least two nodes to spline between if (nodes.Count >= 2) { // copy nodes array since Bezier is destructive Vector3[] points = new Vector3[nodes.Count]; foreach (float step in steps) { // re-initialize copy before each destructive call to Bezier for (int i = 0; i < nodes.Count; i++) { points[i] = toVector3((T)nodes[i]); } yield return Bezier(ease, points, step, maxStep); // make sure last value is always generated } } } /** * A Vector3 n-degree bezier spline. * * WARNING: The points array is modified by Bezier. See NewBezier() for a * safe and user friendly alternative. * * You can pass zero control points, just the start and end points, for just * plain easing. In other words a zero-degree bezier spline curve is just the * easing method. * * @param points start point, n control points, end point */ static Vector3 Bezier(Function ease, Vector3[] points, float elapsedTime, float duration) { // Reference: http://ibiblio.org/e-notes/Splines/Bezier.htm // Interpolate the n starting points to generate the next j = (n - 1) points, // then interpolate those n - 1 points to generate the next n - 2 points, // continue this until we have generated the last point (n - (n - 1)), j = 1. // We store the next set of output points in the same array as the // input points used to generate them. This works because we store the // result in the slot of the input point that is no longer used for this // iteration. for (int j = points.Length - 1; j > 0; j--) { for (int i = 0; i < j; i++) { points[i].x = ease(points[i].x, points[i + 1].x - points[i].x, elapsedTime, duration); points[i].y = ease(points[i].y, points[i + 1].y - points[i].y, elapsedTime, duration); points[i].z = ease(points[i].z, points[i + 1].z - points[i].z, elapsedTime, duration); } } return points[0]; } /** * Returns sequence generator from the first node, through each control point, * and to the last node. N points are generated between each node (slices) * using Catmull-Rom. */ public static IEnumerable<Vector3> NewCatmullRom(Transform[] nodes, int slices, bool loop) { return NewCatmullRom<Transform>(nodes, TransformDotPosition, slices, loop); } /** * A Vector3[] variation of the Transform[] NewCatmullRom() function. * Same functionality but using Vector3s to define curve. */ public static IEnumerable<Vector3> NewCatmullRom(Vector3[] points, int slices, bool loop) { return NewCatmullRom<Vector3>(points, Identity, slices, loop); } /** * Generic catmull-rom spline sequence generator used to implement the * Vector3[] and Transform[] variants. Normally you would not use this * function directly. */ static IEnumerable<Vector3> NewCatmullRom<T>(IList nodes, ToVector3<T> toVector3, int slices, bool loop) { // need at least two nodes to spline between if (nodes.Count >= 2) { // yield the first point explicitly, if looping the first point // will be generated again in the step for loop when interpolating // from last point back to the first point yield return toVector3((T)nodes[0]); int last = nodes.Count - 1; for (int current = 0; loop || current < last; current++) { // wrap around when looping if (loop && current > last) { current = 0; } // handle edge cases for looping and non-looping scenarios // when looping we wrap around, when not looping use start for previous // and end for next when you at the ends of the nodes array int previous = (current == 0) ? ((loop) ? last : current) : current - 1; int start = current; int end = (current == last) ? ((loop) ? 0 : current) : current + 1; int next = (end == last) ? ((loop) ? 0 : end) : end + 1; // adding one guarantees yielding at least the end point int stepCount = slices + 1; for (int step = 1; step <= stepCount; step++) { yield return CatmullRom(toVector3((T)nodes[previous]), toVector3((T)nodes[start]), toVector3((T)nodes[end]), toVector3((T)nodes[next]), step, stepCount); } } } } /** * A Vector3 Catmull-Rom spline. Catmull-Rom splines are similar to bezier * splines but have the useful property that the generated curve will go * through each of the control points. * * NOTE: The NewCatmullRom() functions are an easier to use alternative to this * raw Catmull-Rom implementation. * * @param previous the point just before the start point or the start point * itself if no previous point is available * @param start generated when elapsedTime == 0 * @param end generated when elapsedTime >= duration * @param next the point just after the end point or the end point itself if no * next point is available */ static Vector3 CatmullRom(Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime, float duration) { // References used: // p.266 GemsV1 // // tension is often set to 0.5 but you can use any reasonable value: // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf // // bias and tension controls: // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/ float percentComplete = elapsedTime / duration; float percentCompleteSquared = percentComplete * percentComplete; float percentCompleteCubed = percentCompleteSquared * percentComplete; return previous * (-0.5f * percentCompleteCubed + percentCompleteSquared - 0.5f * percentComplete) + start * ( 1.5f * percentCompleteCubed + -2.5f * percentCompleteSquared + 1.0f) + end * (-1.5f * percentCompleteCubed + 2.0f * percentCompleteSquared + 0.5f * percentComplete) + next * ( 0.5f * percentCompleteCubed - 0.5f * percentCompleteSquared); } /** * Linear interpolation (same as Mathf.Lerp) */ static float Linear(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (elapsedTime / duration) + start; } /** * quadratic easing in - accelerating from zero velocity */ static float EaseInQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime + start; } /** * quadratic easing out - decelerating to zero velocity */ static float EaseOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * elapsedTime * (elapsedTime - 2) + start; } /** * quadratic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime + start; elapsedTime--; return -distance / 2 * (elapsedTime * (elapsedTime - 2) - 1) + start; } /** * cubic easing in - accelerating from zero velocity */ static float EaseInCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime + start; } /** * cubic easing out - decelerating to zero velocity */ static float EaseOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * cubic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * quartic easing in - accelerating from zero velocity */ static float EaseInQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quartic easing out - decelerating to zero velocity */ static float EaseOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return -distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 1) + start; } /** * quartic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return -distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 2) + start; } /** * quintic easing in - accelerating from zero velocity */ static float EaseInQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quintic easing out - decelerating to zero velocity */ static float EaseOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * quintic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2f); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * sinusoidal easing in - accelerating from zero velocity */ static float EaseInSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance * Mathf.Cos(elapsedTime / duration * (Mathf.PI / 2)) + distance + start; } /** * sinusoidal easing out - decelerating to zero velocity */ static float EaseOutSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Sin(elapsedTime / duration * (Mathf.PI / 2)) + start; } /** * sinusoidal easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance / 2 * (Mathf.Cos(Mathf.PI * elapsedTime / duration) - 1) + start; } /** * exponential easing in - accelerating from zero velocity */ static float EaseInExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Pow(2, 10 * (elapsedTime / duration - 1)) + start; } /** * exponential easing out - decelerating to zero velocity */ static float EaseOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (-Mathf.Pow(2, -10 * elapsedTime / duration) + 1) + start; } /** * exponential easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * Mathf.Pow(2, 10 * (elapsedTime - 1)) + start; elapsedTime--; return distance / 2 * (-Mathf.Pow(2, -10 * elapsedTime) + 2) + start; } /** * circular easing in - accelerating from zero velocity */ static float EaseInCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; } /** * circular easing out - decelerating to zero velocity */ static float EaseOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * Mathf.Sqrt(1 - elapsedTime * elapsedTime) + start; } /** * circular easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return -distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; elapsedTime -= 2; return distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) + 1) + start; } }
using System; using System.Collections; using System.Net.Sockets; using System.Text; using AzureFtpServer.Ftp.FileSystem; using AzureFtpServer.FtpCommands; using AzureFtpServer.Ftp; using AzureFtpServer.General; using System.Diagnostics; namespace AzureFtpServer.Ftp { /// Processes incoming messages and passes the data on to the relevant handler class. internal class FtpConnectionObject : FtpConnectionData { private readonly IFileSystemClassFactory m_fileSystemClassFactory; private readonly Hashtable m_theCommandHashTable; private bool isLogged; private static bool m_useDataSocket; private StringBuilder currentMessage; public event AzureFtpServer.Ftp.FtpServer.UserAccessEvent UserLoginEvent; public event AzureFtpServer.Ftp.FtpServer.UserAccessEvent UserLogoutEvent; public bool DataSocketOpen { get { return m_useDataSocket; } } public FtpConnectionObject(IFileSystemClassFactory fileSystemClassFactory, int nId, TcpClient socket) : base(nId, socket) { m_theCommandHashTable = new Hashtable(); m_fileSystemClassFactory = fileSystemClassFactory; isLogged = false; m_useDataSocket = false; LoadCommands(); currentMessage = new StringBuilder(); } ~FtpConnectionObject() { LogOut(); } public bool Login(string sPassword) { if ((User == null) || (sPassword == null)) { return false; } IFileSystem fileSystem = m_fileSystemClassFactory.Create(User, sPassword); if (fileSystem == null) //user and pass combo doesn't exist { return false; } if (UserLoginEvent != null) UserLoginEvent(User); SetFileSystemObject(fileSystem); isLogged = true; return true; } private void LoadCommands() { //RFC959: Base Commands AddCommand(new AbortCommandHandler(this));// stop data connection AddCommand(new AccountCommandHandler(this)); AddCommand(new AlloCommandHandler(this)); AddCommand(new AppendCommandHandler(this)); AddCommand(new CdupCommandHandler(this)); AddCommand(new CwdCommandHandler(this)); AddCommand(new DeleCommandHandler(this)); AddCommand(new HelpCommandHandler(this)); AddCommand(new ListCommandHandler(this)); AddCommand(new MakeDirectoryCommandHandler(this)); AddCommand(new ModeCommandHandler(this)); AddCommand(new NlstCommandHandler(this)); AddCommand(new NoopCommandHandler(this)); AddCommand(new PasswordCommandHandler(this)); AddCommand(new PasvCommandHandler(this)); AddCommand(new PortCommandHandler(this)); AddCommand(new PwdCommandHandler(this)); AddCommand(new QuitCommandHandler(this)); AddCommand(new ReinitializeCommandHandler(this)); AddCommand(new RestartCommandHandler(this));// not imp AddCommand(new RetrCommandHandler(this)); AddCommand(new RemoveDirectoryCommandHandler(this)); AddCommand(new RenameStartCommandHandler(this)); AddCommand(new RenameCompleteCommandHandler(this)); AddCommand(new SiteCommandHandler(this)); AddCommand(new SmntCommandHandler(this)); AddCommand(new StatCommandHandler(this)); AddCommand(new StoreCommandHandler(this)); AddCommand(new StructureCommandHandler(this)); AddCommand(new StouCommandHandler(this)); AddCommand(new SystemCommandHandler(this)); AddCommand(new TypeCommandHandler(this)); AddCommand(new UserCommandHandler(this)); //Obsolete commands AddCommand(new XCdupCommandHandler(this)); AddCommand(new XCwdCommandHandler(this)); AddCommand(new XMkdCommandHandler(this)); AddCommand(new XPwdCommandHandler(this)); AddCommand(new XRmdCommandHandler(this)); //Other commands AddCommand(new FeatCommandHandler(this)); AddCommand(new MdtmCommandHandler(this)); AddCommand(new MlsdCommandHandler(this)); AddCommand(new MlstCommandHandler(this)); AddCommand(new SizeCommandHandler(this)); } private void AddCommand(FtpCommandHandler handler) { m_theCommandHashTable.Add(handler.Command, handler); } public void Process(Byte[] abData, int bufferLength) { string sMessage = this.Encoding.GetString(abData, 0, bufferLength); int indexOfCarriageReturn = sMessage.IndexOf('\r'); if (indexOfCarriageReturn == -1) { // the full message line has not yet been sent, append the current buffer and return // so that the rest of the message can be read currentMessage.Append(sMessage); return; } else { // current payload contains carriage return, read up to that point and // append to the current message sMessage = sMessage.Substring(0, indexOfCarriageReturn); currentMessage.Append(sMessage); // don't return; time to process the message } sMessage = currentMessage.ToString(); currentMessage = new StringBuilder(); FtpServerMessageHandler.SendMessage(Id, sMessage); string sCommand; string sValue; int nSpaceIndex = sMessage.IndexOf(' '); if (nSpaceIndex < 0) { sCommand = sMessage.ToUpper(); sValue = ""; } else { sCommand = sMessage.Substring(0, nSpaceIndex).ToUpper(); sValue = sMessage.Substring(sCommand.Length + 1); } // check whether the client has logged in if (!isLogged) { if (!((sCommand == "USER") || (sCommand == "PASS") || (sCommand == "HELP") || (sCommand == "FEAT") || (sCommand == "QUIT"))) { SocketHelpers.Send(Socket, "530 Not logged in\r\n", this.Encoding); return; } } // check if data connection will be used if ((sCommand == "APPE") || (sCommand == "MLSD") || (sCommand == "LIST") || (sCommand == "RETR") || (sCommand == "STOR")) { m_useDataSocket = true; } var handler = m_theCommandHashTable[sCommand] as FtpCommandHandler; if (handler == null) { FtpServerMessageHandler.SendMessage(Id, string.Format("\"{0}\" : Unknown command", sCommand)); SocketHelpers.Send(Socket, "550 Unknown command\r\n", this.Encoding); } else { handler.Process(sValue); } // reset m_useDataSocket = false; } public void LogOut() { isLogged = false; if (UserLogoutEvent != null) UserLogoutEvent(User); //TODO: stop current cmd & close data connection // reinitialize all parameters SetFileSystemObject(null); CurrentDirectory = "/"; User = null; FileToRename = null; DataConnectionType = DataConnectionType.Invalid; DataType = DataType.Image; // currently won't change TransmissionMode = TransmissionMode.Stream; DataStructure = DataStructure.File; FormatControl = FormatControl.NonPrint; } } }
using System; using UIKit; using CoreGraphics; using SDWebImage; using Foundation; namespace RepositoryStumble.Views { public class ImageAndTitleHeaderView : UIView { private readonly UIImageView _imageView; private readonly UILabel _label; private readonly UILabel _label2; private readonly UIView _seperatorView; private readonly UIView _subView; private readonly UIImageView _subImageView; private const float SubImageAppearTime = 0.25f; public UIButton ImageButton { get; private set; } public UIImageView SubImageView { get { return _subImageView; } } public Action ImageButtonAction { get; set; } public string ImageUri { set { if (value == null) _imageView.Image = null; else { _imageView.SetImage(new NSUrl(value), Image, (image, error, cacheType, imageUrl) => { if (image != null && error == null) UIView.Transition(_imageView, 0.35f, UIViewAnimationOptions.TransitionCrossDissolve, () => _imageView.Image = image, null); }); } } } public UIImage Image { get { return _imageView.Image; } set { _imageView.Image = value; } } public string Text { get { return _label.Text; } set { _label.Text = value; this.SetNeedsLayout(); this.LayoutIfNeeded(); } } public UIColor TextColor { get { return _label.TextColor; } set { _label.TextColor = value; } } public string SubText { get { return _label2.Text; } set { if (!string.IsNullOrEmpty(value)) _label2.Hidden = false; _label2.Text = value; this.SetNeedsLayout(); this.LayoutIfNeeded(); } } public UIColor SubTextColor { get { return _label2.TextColor; } set { _label2.TextColor = value; } } public bool EnableSeperator { get { return !_seperatorView.Hidden; } set { _seperatorView.Hidden = !value; } } public UIColor SeperatorColor { get { return _seperatorView.BackgroundColor; } set { _seperatorView.BackgroundColor = value; } } public bool RoundedImage { get { return _imageView.Layer.CornerRadius > 0; } set { if (value) { _imageView.Layer.CornerRadius = _imageView.Frame.Width / 2f; _imageView.Layer.MasksToBounds = true; } else { _imageView.Layer.MasksToBounds = false; _imageView.Layer.CornerRadius = 0; } } } public UIColor ImageTint { get { return _imageView.TintColor; } set { _imageView.TintColor = value; } } public ImageAndTitleHeaderView() : base(new CGRect(0, 0, 320f, 100f)) { ImageButton = new UIButton(UIButtonType.Custom); ImageButton.Frame = new CGRect(0, 0, 80, 80); ImageButton.TouchUpInside += (sender, e) => { if (ImageButtonAction != null) ImageButtonAction(); }; Add(ImageButton); _imageView = new UIImageView(); _imageView.Frame = new CGRect(0, 0, 80, 80); _imageView.BackgroundColor = UIColor.White; _imageView.Layer.BorderWidth = 2f; _imageView.Layer.BorderColor = UIColor.White.CGColor; ImageButton.Add(_imageView); _label = new UILabel(); _label.TextAlignment = UITextAlignment.Center; _label.Lines = 0; _label.Font = UIFont.PreferredHeadline; Add(_label); _label2 = new UILabel(); _label2.Hidden = true; _label2.TextAlignment = UITextAlignment.Center; _label2.Font = UIFont.PreferredSubheadline; _label2.Lines = 0; Add(_label2); _seperatorView = new UIView(); _seperatorView.BackgroundColor = UIColor.FromWhiteAlpha(214.0f / 255.0f, 1.0f); Add(_seperatorView); _subView = new UIView(); _subView.Frame = new CGRect(56, 56, 22, 22); _subView.Layer.CornerRadius = 10f; _subView.Layer.MasksToBounds = true; _subView.BackgroundColor = UIColor.White; _subView.Hidden = true; ImageButton.Add(_subView); _subImageView = new UIImageView(new CGRect(0, 0, _subView.Frame.Width - 4f, _subView.Frame.Height - 4f)); _subImageView.Center = new CGPoint(11f, 11f); _subView.Add(_subImageView); EnableSeperator = false; RoundedImage = true; } public void SetSubImage(UIImage image) { if (image == null && _subImageView.Image != null) { UIView.Animate(SubImageAppearTime, 0, UIViewAnimationOptions.CurveEaseIn, () => _subView.Transform = CGAffineTransform.MakeScale(0.01f, 0.01f), () => { _subView.Hidden = true; _subImageView.Image = null; }); } else if (image != null && _subImageView.Image != null) { UIView.Animate(SubImageAppearTime, 0, UIViewAnimationOptions.TransitionCrossDissolve, () => _subImageView.Image = image, null); } else if (image != null && _subImageView.Image == null) { _subView.Transform = CGAffineTransform.MakeScale(0.01f, 0.01f); _subView.Hidden = false; _subImageView.Image = image; UIView.Animate(SubImageAppearTime, 0, UIViewAnimationOptions.CurveEaseIn, () => _subView.Transform = CGAffineTransform.MakeIdentity(), null); } } public override void LayoutSubviews() { base.LayoutSubviews(); ImageButton.Center = new CGPoint(Bounds.Width / 2, 15 + ImageButton.Frame.Height / 2); _label.Frame = new CGRect(20, ImageButton.Frame.Bottom + 10f, Bounds.Width - 40, Bounds.Height - (ImageButton.Frame.Bottom + 5f)); _label.SizeToFit(); _label.Frame = new CGRect(20, ImageButton.Frame.Bottom + 10f, Bounds.Width - 40, _label.Frame.Height); _label2.Frame = new CGRect(20, _label.Frame.Bottom + 2f, Bounds.Width - 40f, _label2.Font.LineHeight + 2f); _label2.SizeToFit(); _label2.Frame = new CGRect(20, _label.Frame.Bottom + 2f, Bounds.Width - 40f, _label2.Frame.Height); var bottom = _label2.Hidden == false? _label2.Frame.Bottom : _label.Frame.Bottom; var f = Frame; f.Height = bottom + 15f; Frame = f; _seperatorView.Frame = new CGRect(0, Frame.Height - 0.5f, Frame.Width, 0.5f); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** __ComObject is the root class for all COM wrappers. This class ** defines only the basics. This class is used for wrapping COM objects ** accessed from COM+ ** ** ===========================================================*/ namespace System { using System; using System.Collections; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.CompilerServices; using System.Reflection; using System.Security.Permissions; internal class __ComObject : MarshalByRefObject { private Hashtable m_ObjectToDataMap; /*============================================================ ** default constructor ** can't instantiate this directly =============================================================*/ protected __ComObject () { } //==================================================================== // Overrides ToString() to make sure we call to IStringable if the // COM object implements it in the case of weakly typed RCWs //==================================================================== public override string ToString() { // // Only do the IStringable cast when running under AppX for better compat // Otherwise we could do a IStringable cast in classic apps which could introduce // a thread transition which would lead to deadlock // if (AppDomain.IsAppXModel()) { // Check whether the type implements IStringable. IStringable stringableType = this as IStringable; if (stringableType != null) { return stringableType.ToString(); } } return base.ToString(); } [System.Security.SecurityCritical] // auto-generated internal IntPtr GetIUnknown(out bool fIsURTAggregated) { fIsURTAggregated = !GetType().IsDefined(typeof(ComImportAttribute), false); return System.Runtime.InteropServices.Marshal.GetIUnknownForObject(this); } //==================================================================== // This method retrieves the data associated with the specified // key if any such data exists for the current __ComObject. //==================================================================== internal Object GetData(Object key) { Object data = null; // Synchronize access to the map. lock(this) { // If the map hasn't been allocated, then there can be no data for the specified key. if (m_ObjectToDataMap != null) { // Look up the data in the map. data = m_ObjectToDataMap[key]; } } return data; } //==================================================================== // This method sets the data for the specified key on the current // __ComObject. //==================================================================== internal bool SetData(Object key, Object data) { bool bAdded = false; // Synchronize access to the map. lock(this) { // If the map hasn't been allocated yet, allocate it. if (m_ObjectToDataMap == null) m_ObjectToDataMap = new Hashtable(); // If there isn't already data in the map then add it. if (m_ObjectToDataMap[key] == null) { m_ObjectToDataMap[key] = data; bAdded = true; } } return bAdded; } //==================================================================== // This method is called from within the EE and releases all the // cached data for the __ComObject. //==================================================================== [System.Security.SecurityCritical] // auto-generated internal void ReleaseAllData() { // Synchronize access to the map. lock(this) { // If the map hasn't been allocated, then there is nothing to do. if (m_ObjectToDataMap != null) { foreach (Object o in m_ObjectToDataMap.Values) { // Note: the value could be an object[] // We are fine for now as object[] doesn't implement IDisposable nor derive from __ComObject // If the object implements IDisposable, then call Dispose on it. IDisposable DisposableObj = o as IDisposable; if (DisposableObj != null) DisposableObj.Dispose(); // If the object is a derived from __ComObject, then call Marshal.ReleaseComObject on it. __ComObject ComObj = o as __ComObject; if (ComObj != null) Marshal.ReleaseComObject(ComObj); } // Set the map to null to indicate it has been cleaned up. m_ObjectToDataMap = null; } } } //==================================================================== // This method is called from within the EE and is used to handle // calls on methods of event interfaces. //==================================================================== [System.Security.SecurityCritical] // auto-generated internal Object GetEventProvider(RuntimeType t) { // Check to see if we already have a cached event provider for this type. Object EvProvider = GetData(t); // If we don't then we need to create one. if (EvProvider == null) EvProvider = CreateEventProvider(t); return EvProvider; } [System.Security.SecurityCritical] // auto-generated internal int ReleaseSelf() { return Marshal.InternalReleaseComObject(this); } [System.Security.SecurityCritical] // auto-generated internal void FinalReleaseSelf() { Marshal.InternalFinalReleaseComObject(this); } [System.Security.SecurityCritical] // auto-generated #if !FEATURE_CORECLR [ReflectionPermissionAttribute(SecurityAction.Assert, MemberAccess=true)] #endif private Object CreateEventProvider(RuntimeType t) { // Create the event provider for the specified type. Object EvProvider = Activator.CreateInstance(t, Activator.ConstructorDefault | BindingFlags.NonPublic, null, new Object[]{this}, null); // Attempt to cache the wrapper on the object. if (!SetData(t, EvProvider)) { // Dispose the event provider if it implements IDisposable. IDisposable DisposableEvProv = EvProvider as IDisposable; if (DisposableEvProv != null) DisposableEvProv.Dispose(); // Another thead already cached the wrapper so use that one instead. EvProvider = GetData(t); } return EvProvider; } } }
// 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\Arm\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; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector128_UInt64() { var test = new LoadUnaryOpTest__LoadVector128_UInt64(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector128_UInt64 { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(UInt64[] inArray1, UInt64[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt64>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt64>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt64, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64); private static UInt64[] _data = new UInt64[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector128_UInt64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); } _dataTable = new DataTable(_data, new UInt64[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector128( (UInt64*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(UInt64*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(UInt64*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (firstOp[i] != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<UInt64>(Vector128<UInt64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.Tests { public class ArrayList_IndexOfTests { [Fact] public void TestArrayListWrappers01() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- // no null string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Batman", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Batman", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Batman", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Batman", "Wildcat", "Wonder Woman", "Batman", }; ArrayList arrList = null; int ndx = -1; // Construct ArrayList. arrList = new ArrayList((ICollection)strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // Construct array lists. // Assert.NotNull(arrList); // // [] Obtain index of "Batman" items. // int startIndex = 0; while (startIndex < arrList.Count && (ndx = arrList.IndexOf("Batman", startIndex)) != -1) { Assert.True(startIndex <= ndx); Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx])); // // [] Attempt to find null object. // // Remove range of items. ndx = arrList.IndexOf(null, 0); Assert.Equal(-1, ndx); // // [] Attempt invalid IndexOf using negative index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.IndexOf("Batman", -1000)); // // [] Attempt invalid IndexOf using out of range index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.IndexOf("Batman", 1000)); // []Team review feedback - query for an existing object after the index. expects -1 arrList.Clear(); for (int i = 0; i < 10; i++) arrList.Add(i); Assert.Equal(-1, arrList.IndexOf(0, 1)); } } } [Fact] public void TestArrayListWrappers02() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; int ndx = -1; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Batman", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Batman", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Batman", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Batman", "Wildcat", "Wonder Woman", "Batman", null }; // // Construct array lists. // arrList = new ArrayList((ICollection)strHeroes); Assert.NotNull(arrList); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { arrList, ArrayList.Adapter(arrList), ArrayList.FixedSize(arrList), arrList.GetRange(0, arrList.Count), ArrayList.ReadOnly(arrList), ArrayList.Synchronized(arrList)}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Obtain index of "Batman" items. // ndx = 0; int startIndex = 0; int tmpNdx = 0; while (startIndex < arrList.Count && (ndx = arrList.IndexOf("Batman", startIndex, (arrList.Count - startIndex))) != -1) { Assert.True(ndx >= startIndex); Assert.Equal(0, strHeroes[ndx].CompareTo((string)arrList[ndx])); tmpNdx = arrList.IndexOf("Batman", startIndex, ndx - startIndex + 1); Assert.Equal(ndx, tmpNdx); tmpNdx = arrList.IndexOf("Batman", startIndex, ndx - startIndex); Assert.Equal(-1, tmpNdx); startIndex = ndx + 1; } // // [] Attempt to find null object when a null element exists in the collections // ndx = arrList.IndexOf(null, 0, arrList.Count); Assert.Null(arrList[ndx]); // // [] Attempt invalid IndexOf using negative index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.IndexOf("Batman", -1000, arrList.Count)); // // [] Attempt invalid IndexOf using out of range index // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.IndexOf("Batman", 1000, arrList.Count)); // // [] Attempt invalid IndexOf using index=Count // Assert.Equal(-1, arrList.IndexOf("Batman", arrList.Count, 0)); // // [] Attempt invalid IndexOf using endIndex greater than the size. // // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.IndexOf("Batman", 3, arrList.Count + 10)); //[]Team Review feedback - attempt to find non-existent object and confirm that -1 returned arrList = new ArrayList(); for (int i = 0; i < 10; i++) arrList.Add(i); Assert.Equal(-1, arrList.IndexOf(50, 0, arrList.Count)); Assert.Equal(-1, arrList.IndexOf(0, 1, arrList.Count - 1)); } } [Fact] public void TestDuplicatedItems() { //-------------------------------------------------------------------------- // Variable definitions. //-------------------------------------------------------------------------- ArrayList arrList = null; string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Daniel Takacs", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Gene", "Thor", "Wildcat", null }; // Construct ArrayList. arrList = new ArrayList(strHeroes); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { (ArrayList)arrList.Clone(), (ArrayList)ArrayList.Adapter(arrList).Clone(), (ArrayList)arrList.GetRange(0, arrList.Count).Clone(), (ArrayList)ArrayList.Synchronized(arrList).Clone()}; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] IndexOf an array normal // for (int i = 0; i < strHeroes.Length; i++) { Assert.Equal(i, arrList.IndexOf(strHeroes[i])); } //[] Check IndexOf when element is in list twice arrList.Clear(); arrList.Add(null); arrList.Add(arrList); arrList.Add(null); Assert.Equal(0, arrList.IndexOf(null)); //[] check for something which does not exist in a list arrList.Clear(); Assert.Equal(-1, arrList.IndexOf(null)); } } } }
using System.ComponentModel; using System.Drawing.Design; using System.Web.UI.WebControls; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.UserInterface.TypeEditors; using DisplayNameAttribute=GuruComponents.Netrix.UserInterface.TypeEditors.DisplayNameAttribute; using TE=GuruComponents.Netrix.UserInterface.TypeEditors; namespace GuruComponents.Netrix.WebEditing.Elements { /// <summary> /// This class represents the &lt;a&gt; element. /// </summary> /// <remarks> /// <para> /// </para> /// Classes directly or indirectly inherited from /// <see cref="GuruComponents.Netrix.WebEditing.Elements.Element"/> are not intended to be instantiated /// directly by the host application. Use the various insertion or creation methods in the base classes /// instead. The return values are of type <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement"/> /// and can be casted into the element just created. /// <para> /// Examples of how to create and modify elements with the native element classes can be found in the /// description of other element classes. /// </para> /// </remarks> /// <example> /// The following code will set up double click event handlers for all anchor tags in the document: /// <code> /// ArrayList anchors = this.HtmlEditor.DocumentStructure.GetElementCollection("A") as ArrayList; /// if (anchors != null) /// { /// foreach (AnchorElement a in anchors) /// { /// a.OnDblClick += new GuruComponents.NetrixEvents.DocumentEventHandler(a_OnDblClick); /// } /// } /// </code> /// Remember, that this is a one-time action. If the user removes an anchor and inserts another one later, the event /// handler will no longer be active. You can control this by adding the event handler after creating a new element; /// the following code inserts a new hyperlink, using the current selection as viewable content and presets to properties. /// Then the double click event will be tied with the event handler. /// <code> /// AnchorElement a = (AnchorElement) this.HtmlEditor.Document.InsertHyperlink(); /// a.href = "http://www.comzept.de"; /// a.target = "_blank"; /// a.OnDblClick += new GuruComponents.NetrixEvents.DocumentEventHandler(a_OnDblClick); /// </code> /// The handler should be the same as in the previous example. The DEMO application uses the following code: /// <code> /// private void a_OnDblClick(GuruComponents.NetrixEvents.DocumentEventArgs e) /// { /// if (HyperlinkWizardDlg.ShowDialog() == DialogResult.OK) /// { /// AnchorElement a = (AnchorElement) e.SrcElement; /// a.href = String.Concat(HyperlinkWizardDlg.Protocol,"//",HyperlinkWizardDlg.Url); /// a.target = HyperlinkWizardDlg.Target; /// } /// } /// </code> /// HyperlinkWizardDlg is the dialog, which appears, if the user double clicks an anchor to change the behavior in a more user friendly and individual way than the PropertyGrid. /// </example> public sealed class AnchorElement : SelectableElement { /// <summary> /// HREF indicates the URL being linked to. /// </summary> /// <remarks>HREF makes the anchor into a link.</remarks> [Category("Element Behavior")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorUrl), typeof(UITypeEditor))] [DisplayNameAttribute()] public string href { set { try { System.Uri uri; if (System.Uri.TryCreate(value, System.UriKind.Absolute, out uri)) { this.SetStringAttribute("href", uri.AbsoluteUri); return; } } catch { } this.SetStringAttribute ("href", this.GetRelativeUrl(value)); return; } get { string href = this.GetStringAttribute("href"); try { System.Uri uri; if (System.Uri.TryCreate(href, System.UriKind.Absolute, out uri)) { return uri.AbsoluteUri; } } catch { } return this.GetRelativeUrl(href); } } /// <summary> /// NAME gives the anchor a name. /// </summary> /// <remarks>Other links target the anchor using that name. This allows you to link to specific places within the page.</remarks> [CategoryAttribute("Element Behavior")] [DefaultValueAttribute("")] [DescriptionAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] public string name { get { return base.GetStringAttribute("name"); } set { base.SetStringAttribute("name", value); } } [CategoryAttribute("JavaScript Events")] [DefaultValueAttribute("")] [DescriptionAttribute("Event raised when a mouse click begins over this object")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] [ScriptingVisible()] public string ScriptOnMouseDown { get { return base.GetStringAttribute("onMouseDown"); } set { base.SetStringAttribute("onMouseDown", value); } } [CategoryAttribute("JavaScript Events")] [DescriptionAttribute("")] [DefaultValueAttribute("")] [EditorAttribute( typeof(UITypeEditorString), typeof(UITypeEditor))] [DisplayName()] [ScriptingVisible()] public string ScriptOnMouseUp { get { return base.GetStringAttribute("onmouseup"); } set { base.SetStringAttribute("onmouseup", value); } } /// <include file='DocumentorIncludes.xml' path='WebEditing/Elements[@name="TargetAttribute"]'/> [CategoryAttribute("Element Behavior")] [TypeConverterAttribute(typeof(TargetConverter))] [DescriptionAttribute("")] [DefaultValueAttribute("")] [DisplayName()] public string target { get { return base.GetStringAttribute("target"); } set { base.SetStringAttribute("target", value); } } /// <summary> /// Creates the specified element. /// </summary> /// <remarks> /// The element is being created and attached to the current document, but nevertheless not visible, /// until it's being placed anywhere within the DOM. To attach an element it's possible to either /// use the <see cref="ElementDom"/> property of any other already placed element and refer to this /// DOM or use the body element (<see cref="HtmlEditor.GetBodyElement"/>) and add the element there. Also, in /// case of user interactive solutions, it's possible to add an element near the current caret /// position, using <see cref="HtmlEditor.CreateElementAtCaret(string)"/> method. /// <para> /// Note: Invisible elements do neither appear in the DOM nor do they get saved. /// </para> /// </remarks> /// <param name="editor">The editor this element belongs to.</param> public AnchorElement(IHtmlEditor editor) : base("a", editor) { } internal AnchorElement(Interop.IHTMLElement peer, IHtmlEditor editor) : base (peer, editor) { } } }
// 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.CodeAnalysis; using System.Runtime.Serialization; namespace System.Collections.Generic { [DebuggerTypeProxy(typeof(ICollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class LinkedList<T> : ICollection<T>, ICollection, IReadOnlyCollection<T>, ISerializable, IDeserializationCallback { // This LinkedList is a doubly-Linked circular list. internal LinkedListNode<T> head; internal int count; internal int version; private object _syncRoot; private SerializationInfo _siInfo; //A temporary variable which we need during deserialization. // names for serialization private const string VersionName = "Version"; private const string CountName = "Count"; private const string ValuesName = "Data"; public LinkedList() { } public LinkedList(IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } foreach (T item in collection) { AddLast(item); } } protected LinkedList(SerializationInfo info, StreamingContext context) { _siInfo = info; } public int Count { get { return count; } } public LinkedListNode<T> First { get { return head; } } public LinkedListNode<T> Last { get { return head == null ? null : head.prev; } } bool ICollection<T>.IsReadOnly { get { return false; } } void ICollection<T>.Add(T value) { AddLast(value); } public LinkedListNode<T> AddAfter(LinkedListNode<T> node, T value) { ValidateNode(node); LinkedListNode<T> result = new LinkedListNode<T>(node.list, value); InternalInsertNodeBefore(node.next, result); return result; } public void AddAfter(LinkedListNode<T> node, LinkedListNode<T> newNode) { ValidateNode(node); ValidateNewNode(newNode); InternalInsertNodeBefore(node.next, newNode); newNode.list = this; } public LinkedListNode<T> AddBefore(LinkedListNode<T> node, T value) { ValidateNode(node); LinkedListNode<T> result = new LinkedListNode<T>(node.list, value); InternalInsertNodeBefore(node, result); if (node == head) { head = result; } return result; } public void AddBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) { ValidateNode(node); ValidateNewNode(newNode); InternalInsertNodeBefore(node, newNode); newNode.list = this; if (node == head) { head = newNode; } } public LinkedListNode<T> AddFirst(T value) { LinkedListNode<T> result = new LinkedListNode<T>(this, value); if (head == null) { InternalInsertNodeToEmptyList(result); } else { InternalInsertNodeBefore(head, result); head = result; } return result; } public void AddFirst(LinkedListNode<T> node) { ValidateNewNode(node); if (head == null) { InternalInsertNodeToEmptyList(node); } else { InternalInsertNodeBefore(head, node); head = node; } node.list = this; } public LinkedListNode<T> AddLast(T value) { LinkedListNode<T> result = new LinkedListNode<T>(this, value); if (head == null) { InternalInsertNodeToEmptyList(result); } else { InternalInsertNodeBefore(head, result); } return result; } public void AddLast(LinkedListNode<T> node) { ValidateNewNode(node); if (head == null) { InternalInsertNodeToEmptyList(node); } else { InternalInsertNodeBefore(head, node); } node.list = this; } public void Clear() { LinkedListNode<T> current = head; while (current != null) { LinkedListNode<T> temp = current; current = current.Next; // use Next the instead of "next", otherwise it will loop forever temp.Invalidate(); } head = null; count = 0; version++; } public bool Contains(T value) { return Find(value) != null; } public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_BiggerThanCollection); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } LinkedListNode<T> node = head; if (node != null) { do { array[index++] = node.item; node = node.next; } while (node != head); } } public LinkedListNode<T> Find(T value) { LinkedListNode<T> node = head; EqualityComparer<T> c = EqualityComparer<T>.Default; if (node != null) { if (value != null) { do { if (c.Equals(node.item, value)) { return node; } node = node.next; } while (node != head); } else { do { if (node.item == null) { return node; } node = node.next; } while (node != head); } } return null; } public LinkedListNode<T> FindLast(T value) { if (head == null) return null; LinkedListNode<T> last = head.prev; LinkedListNode<T> node = last; EqualityComparer<T> c = EqualityComparer<T>.Default; if (node != null) { if (value != null) { do { if (c.Equals(node.item, value)) { return node; } node = node.prev; } while (node != last); } else { do { if (node.item == null) { return node; } node = node.prev; } while (node != last); } } return null; } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } public bool Remove(T value) { LinkedListNode<T> node = Find(value); if (node != null) { InternalRemoveNode(node); return true; } return false; } public void Remove(LinkedListNode<T> node) { ValidateNode(node); InternalRemoveNode(node); } public void RemoveFirst() { if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head); } public void RemoveLast() { if (head == null) { throw new InvalidOperationException(SR.LinkedListEmpty); } InternalRemoveNode(head.prev); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Customized serialization for LinkedList. // We need to do this because it will be too expensive to Serialize each node. // This will give us the flexiblility to change internal implementation freely in future. if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue(VersionName, version); info.AddValue(CountName, count); // this is the length of the bucket array. if (count != 0) { T[] array = new T[count]; CopyTo(array, 0); info.AddValue(ValuesName, array, typeof(T[])); } } public virtual void OnDeserialization(Object sender) { if (_siInfo == null) { return; //Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it. } int realVersion = _siInfo.GetInt32(VersionName); int count = _siInfo.GetInt32(CountName); if (count != 0) { T[] array = (T[])_siInfo.GetValue(ValuesName, typeof(T[])); if (array == null) { throw new SerializationException(SR.Serialization_MissingValues); } for (int i = 0; i < array.Length; i++) { AddLast(array[i]); } } else { head = null; } version = realVersion; _siInfo = null; } private void InternalInsertNodeBefore(LinkedListNode<T> node, LinkedListNode<T> newNode) { newNode.next = node; newNode.prev = node.prev; node.prev.next = newNode; node.prev = newNode; version++; count++; } private void InternalInsertNodeToEmptyList(LinkedListNode<T> newNode) { Debug.Assert(head == null && count == 0, "LinkedList must be empty when this method is called!"); newNode.next = newNode; newNode.prev = newNode; head = newNode; version++; count++; } internal void InternalRemoveNode(LinkedListNode<T> node) { Debug.Assert(node.list == this, "Deleting the node from another list!"); Debug.Assert(head != null, "This method shouldn't be called on empty list!"); if (node.next == node) { Debug.Assert(count == 1 && head == node, "this should only be true for a list with only one node"); head = null; } else { node.next.prev = node.prev; node.prev.next = node.next; if (head == node) { head = node.next; } } node.Invalidate(); count--; version++; } internal void ValidateNewNode(LinkedListNode<T> node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (node.list != null) { throw new InvalidOperationException(SR.LinkedListNodeIsAttached); } } internal void ValidateNode(LinkedListNode<T> node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (node.list != this) { throw new InvalidOperationException(SR.ExternalLinkedListNode); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null); } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } T[] tArray = array as T[]; if (tArray != null) { CopyTo(tArray, index); } else { // No need to use reflection to verify that the types are compatible because it isn't 100% correct and we can rely // on the runtime validation during the cast that happens below (i.e. we will get an ArrayTypeMismatchException). object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } LinkedListNode<T> node = head; try { if (node != null) { do { objects[index++] = node.item; node = node.next; } while (node != head); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, IEnumerator, ISerializable, IDeserializationCallback { private LinkedList<T> _list; private LinkedListNode<T> _node; private int _version; private T _current; private int _index; private SerializationInfo _siInfo; //A temporary variable which we need during deserialization. const string LinkedListName = "LinkedList"; const string CurrentValueName = "Current"; const string VersionName = "Version"; const string IndexName = "Index"; internal Enumerator(LinkedList<T> list) { _list = list; _version = list.version; _node = list.head; _current = default(T); _index = 0; _siInfo = null; } private Enumerator(SerializationInfo info, StreamingContext context) { _siInfo = info; _list = null; _version = 0; _node = null; _current = default(T); _index = 0; } public T Current { get { return _current; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _list.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _current; } } public bool MoveNext() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (_node == null) { _index = _list.Count + 1; return false; } ++_index; _current = _node.item; _node = _node.next; if (_node == _list.head) { _node = null; } return true; } void IEnumerator.Reset() { if (_version != _list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _current = default(T); _node = _list.head; _index = 0; } public void Dispose() { } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException(nameof(info)); } info.AddValue(LinkedListName, _list); info.AddValue(VersionName, _version); info.AddValue(CurrentValueName, _current); info.AddValue(IndexName, _index); } void IDeserializationCallback.OnDeserialization(Object sender) { if (_list != null) { return; // Somebody had a dependency on this Dictionary and fixed us up before the ObjectManager got to it. } if (_siInfo == null) { throw new SerializationException(SR.Serialization_InvalidOnDeser); } _list = (LinkedList<T>)_siInfo.GetValue(LinkedListName, typeof(LinkedList<T>)); _version = _siInfo.GetInt32(VersionName); _current = (T)_siInfo.GetValue(CurrentValueName, typeof(T)); _index = _siInfo.GetInt32(IndexName); if (_list._siInfo != null) { _list.OnDeserialization(sender); } if (_index == _list.Count + 1) { // end of enumeration _node = null; } else { _node = _list.First; // We don't care if we can point to the correct node if the LinkedList was changed // MoveNext will throw upon next call and Current has the correct value. if (_node != null && _index != 0) { for (int i = 0; i < _index; i++) { _node = _node.next; } if (_node == _list.First) { _node = null; } } } _siInfo = null; } } } // Note following class is not serializable since we customized the serialization of LinkedList. public sealed class LinkedListNode<T> { internal LinkedList<T> list; internal LinkedListNode<T> next; internal LinkedListNode<T> prev; internal T item; public LinkedListNode(T value) { item = value; } internal LinkedListNode(LinkedList<T> list, T value) { this.list = list; item = value; } public LinkedList<T> List { get { return list; } } public LinkedListNode<T> Next { get { return next == null || next == list.head ? null : next; } } public LinkedListNode<T> Previous { get { return prev == null || this == list.head ? null : prev; } } public T Value { get { return item; } set { item = value; } } internal void Invalidate() { list = null; next = null; prev = null; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; /* * Each CipherSuite instance encodes a cipher suite and its parameters. * * Static methods are used to locate the relevant CipherSuite instance. */ class CipherSuite { /* * Get the suite identifier (16 bits). */ internal int Suite { get { return suite; } } /* * Get the suite name. */ internal string Name { get { return name; } } /* * Get the suite "encryption strength": * 0 = no encryption * 1 = weak (40 bits) * 2 = medium (56 bits) * 3 = strong (96 bits or more) * * "Medium" will deter low-level amateurs, because they won't * get through it with a couple of PC (it can be done within a * week or so, with a FPGA-based machine that costs a few * thousands of dollars -- not a lot, but enough to make it not * worth the effort is the target is something as trivial as a * credit card number). * * "Strong" is beyond current technology, even with lots of billions * of dollars thrown at the problem. Though I put the cut-off at * 96 bits, there is no cipher suite between 57 and 111 bits. */ internal int Strength { get { return strength; } } /* * Set to true if the suite uses a block cipher in CBC mode. */ internal bool IsCBC { get { return isCBC; } } /* * Set to true if the suite uses RC4. */ internal bool IsRC4 { get { return isRC4; } } /* * This returned true if the suite provides forward secrecy (unless * the server does something stupid like using very weak ephemeral * parameters, or storing ephemeral keys). */ internal bool HasForwardSecrecy { get { return isDHE || isECDHE || isSRP; } } /* * This returned true if the suite does not ensure server * authentication. */ internal bool IsAnonymous { get { return !(isSRP || isPSK) && serverKeyType == "none"; } } /* * Set to true if the suite uses ephemeral Diffie-Hellman (classic). */ internal bool IsDHE { get { return isDHE; } } /* * Set to true if the suite uses ephemeral Diffie-Hellman (on * elliptic curves). */ internal bool IsECDHE { get { return isECDHE; } } /* * Set to true if the suite may use an ephemeral RSA key pair * (this is a weak RSA key pair for "export" cipher suites; its * length will be no more than 512 bits). */ internal bool IsRSAExport { get { return isRSAExport; } } /* * Set to true if the suite uses SRP (hence a form of DH key * exchange, but a different ServerKeyExchange message). */ internal bool IsSRP { get { return isSRP; } } /* * Set to true if the suite uses a pre-shared key. This modifies * the ServerKeyExchange format, if any (coupled with IsDHE * or IsECDHE). */ internal bool IsPSK { get { return isPSK; } } /* * Expected server key type. Defined types are: * RSA * DSA * DH * EC (for ECDH or ECDSA) * none (anonymous cipher suites) */ internal string ServerKeyType { get { return serverKeyType; } } int suite; string name; int strength; bool isCBC; bool isRC4; bool isDHE; bool isECDHE; bool isRSAExport; bool isSRP; bool isPSK; string serverKeyType; CipherSuite(string descriptor) { string[] ww = descriptor.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); if (ww.Length != 6) { throw new ArgumentException( "Bad cipher suite descriptor"); } suite = ParseHex(ww[0]); switch (ww[1]) { case "0": case "1": case "2": case "3": strength = ww[1][0] - '0'; break; default: throw new ArgumentException( "Bad encryption strength: " + ww[1]); } switch (ww[2].ToLowerInvariant()) { case "c": isCBC = true; break; case "r": isRC4 = true; break; case "-": break; default: throw new ArgumentException( "Bad encryption flags: " + ww[2]); } switch (ww[3].ToLowerInvariant()) { case "d": isDHE = true; break; case "e": isECDHE = true; break; case "s": isSRP = true; break; case "x": isRSAExport = true; break; case "-": break; default: throw new ArgumentException( "Bad key exchange flags: " + ww[3]); } switch (ww[4].ToLowerInvariant()) { case "r": serverKeyType = "RSA"; break; case "d": serverKeyType = "DSA"; break; case "h": serverKeyType = "DH"; break; case "e": serverKeyType = "EC"; break; case "p": isPSK = true; serverKeyType = "none"; break; case "q": isPSK = true; serverKeyType = "RSA"; break; case "n": serverKeyType = "none"; break; default: throw new ArgumentException( "Bad server key type: " + ww[4]); } name = ww[5]; } static int ParseHex(string s) { int acc = 0; foreach (char c in s) { int d; if (c >= '0' && c <= '9') { d = c - '0'; } else if (c >= 'A' && c <= 'F') { d = c - ('A' - 10); } else if (c >= 'a' && c <= 'f') { d = c - ('a' - 10); } else { throw new ArgumentException("Not hex digit"); } if (acc > 0x7FFFFFF) { throw new ArgumentException("Hex overflow"); } acc = (acc << 4) + d; } return acc; } /* * A map of all cipher suites, indexed by identifier. */ internal static readonly IDictionary<int, CipherSuite> ALL = new SortedDictionary<int, CipherSuite>(); /* * Some constants for cipher strength. */ internal const int CLEAR = 0; // no encryption internal const int WEAK = 1; // weak encryption: 40-bit key internal const int MEDIUM = 2; // medium encryption: 56-bit key internal const int STRONG = 3; // strong encryption /* * Convert strength to a human-readable string. */ internal static string ToStrength(int strength) { switch (strength) { case CLEAR: return "no encryption"; case WEAK: return "weak encryption (40-bit)"; case MEDIUM: return "medium encryption (56-bit)"; case STRONG: return "strong encryption (96-bit or more)"; default: throw new Exception("strange strength: " + strength); } } /* * Get cipher suite name. If the identifier is unknown, then a * synthetic name is returned. */ internal static string ToName(int suite) { if (ALL.ContainsKey(suite)) { return ALL[suite].name; } else { return string.Format("UNKNOWN_SUITE:0x{0:X4}", suite); } } /* * Some constants for SSLv2 cipher suites. */ internal const int SSL_CK_RC4_128_WITH_MD5 = 0x010080; internal const int SSL_CK_RC4_128_EXPORT40_WITH_MD5 = 0x020080; internal const int SSL_CK_RC2_128_CBC_WITH_MD5 = 0x030080; internal const int SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5 = 0x040080; internal const int SSL_CK_IDEA_128_CBC_WITH_MD5 = 0x050080; internal const int SSL_CK_DES_64_CBC_WITH_MD5 = 0x060040; internal const int SSL_CK_DES_192_EDE3_CBC_WITH_MD5 = 0x0700C0; /* * Get the name for a SSLv2 cipher suite. If the identifier is * unknown, then a synthetic name is returned. */ internal static string ToNameV2(int suite) { switch (suite) { case SSL_CK_RC4_128_WITH_MD5: return "RC4_128_WITH_MD5"; case SSL_CK_RC4_128_EXPORT40_WITH_MD5: return "RC4_128_EXPORT40_WITH_MD5"; case SSL_CK_RC2_128_CBC_WITH_MD5: return "RC2_128_CBC_WITH_MD5"; case SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5: return "RC2_128_CBC_EXPORT40_WITH_MD5"; case SSL_CK_IDEA_128_CBC_WITH_MD5: return "IDEA_128_CBC_WITH_MD5"; case SSL_CK_DES_64_CBC_WITH_MD5: return "DES_64_CBC_WITH_MD5"; case SSL_CK_DES_192_EDE3_CBC_WITH_MD5: return "DES_192_EDE3_CBC_WITH_MD5"; default: return string.Format("UNKNOWN_SUITE:0x{0:X6}", suite); } } static CipherSuite() { StringReader r = new StringReader(STD_SUITES); for (;;) { string line = r.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.Length == 0 || line.StartsWith("#")) { continue; } CipherSuite cs = new CipherSuite(line); if (ALL.ContainsKey(cs.Suite)) { throw new ArgumentException(string.Format( "Duplicate suite: 0x{0:X4}", cs.Suite)); } ALL[cs.Suite] = cs; string name = cs.Name; /* * Consistency test: the strength and CBC status can * normally be inferred from the name itself. */ bool inferredCBC = name.Contains("_CBC_"); bool inferredRC4 = name.Contains("RC4"); int inferredStrength; if (name.Contains("_NULL_")) { inferredStrength = CLEAR; } else if (name.Contains("DES40") || name.Contains("_40_")) { inferredStrength = WEAK; } else if (name.Contains("_DES_")) { inferredStrength = MEDIUM; } else { inferredStrength = STRONG; } bool isDHE = false; bool isECDHE = false; bool isRSAExport = false; bool isSRP = false; bool isPSK = false; string serverKeyType = "none"; if (name.StartsWith("RSA_PSK")) { isPSK = true; serverKeyType = "RSA"; } else if (name.StartsWith("RSA_EXPORT")) { isRSAExport = true; serverKeyType = "RSA"; } else if (name.StartsWith("RSA_")) { serverKeyType = "RSA"; } else if (name.StartsWith("DHE_PSK")) { isDHE = true; isPSK = true; } else if (name.StartsWith("DHE_DSS")) { isDHE = true; serverKeyType = "DSA"; } else if (name.StartsWith("DHE_RSA")) { isDHE = true; serverKeyType = "RSA"; } else if (name.StartsWith("DH_anon")) { isDHE = true; } else if (name.StartsWith("DH_")) { serverKeyType = "DH"; } else if (name.StartsWith("ECDHE_PSK")) { isECDHE = true; isPSK = true; } else if (name.StartsWith("ECDHE_ECDSA")) { isECDHE = true; serverKeyType = "EC"; } else if (name.StartsWith("ECDHE_RSA")) { isECDHE = true; serverKeyType = "RSA"; } else if (name.StartsWith("ECDH_anon")) { isECDHE = true; } else if (name.StartsWith("ECDH_")) { serverKeyType = "EC"; } else if (name.StartsWith("PSK_DHE")) { isDHE = true; isPSK = true; } else if (name.StartsWith("PSK_")) { isPSK = true; } else if (name.StartsWith("KRB5_")) { isPSK = true; } else if (name.StartsWith("SRP_")) { isSRP = true; } else { throw new ArgumentException( "Weird name: " + cs.Name); } if (inferredStrength != cs.Strength || inferredCBC != cs.IsCBC || inferredRC4 != cs.IsRC4 || isDHE != cs.IsDHE || isECDHE != cs.IsECDHE || isRSAExport != cs.IsRSAExport || isSRP != cs.IsSRP || isPSK != cs.IsPSK || serverKeyType != cs.ServerKeyType) { Console.WriteLine("BAD: {0}", cs.Name); Console.WriteLine("strength: {0} / {1}", inferredStrength, cs.Strength); Console.WriteLine("RC4: {0} / {1}", inferredRC4, cs.IsRC4); Console.WriteLine("DHE: {0} / {1}", isDHE, cs.IsDHE); Console.WriteLine("ECDHE: {0} / {1}", isECDHE, cs.IsECDHE); Console.WriteLine("SRP: {0} / {1}", isSRP, cs.IsSRP); Console.WriteLine("PSK: {0} / {1}", isPSK, cs.IsPSK); Console.WriteLine("keytype: {0} / {1}", serverKeyType, cs.ServerKeyType); throw new ArgumentException( "Wrong classification: " + cs.Name); } } } const string STD_SUITES = /* +------------- cipher suite identifier (hex) | +---------- encryption strength (0=none, 1=weak, 2=medium, 3=strong) | | +-------- encryption flags (c=block cipher in CBC mode, r=RC4) | | | +------ key exchange flags (d=DHE, e=ECDHE, s=SRP, x=RSA/export) | | | | +---- server key type (r=RSA, d=DSA, h=DH, e=EC, p=PSK, | | | | | q=RSA+PSK, n=none) | | | | | +-- suite name | | | | | | V V V V V V */ @" 0001 0 - - r RSA_WITH_NULL_MD5 0002 0 - - r RSA_WITH_NULL_SHA 0003 1 r x r RSA_EXPORT_WITH_RC4_40_MD5 0004 3 r - r RSA_WITH_RC4_128_MD5 0005 3 r - r RSA_WITH_RC4_128_SHA 0006 1 c x r RSA_EXPORT_WITH_RC2_CBC_40_MD5 0007 3 c - r RSA_WITH_IDEA_CBC_SHA 0008 1 c x r RSA_EXPORT_WITH_DES40_CBC_SHA 0009 2 c - r RSA_WITH_DES_CBC_SHA 000A 3 c - r RSA_WITH_3DES_EDE_CBC_SHA 000B 1 c - h DH_DSS_EXPORT_WITH_DES40_CBC_SHA 000C 2 c - h DH_DSS_WITH_DES_CBC_SHA 000D 3 c - h DH_DSS_WITH_3DES_EDE_CBC_SHA 000E 1 c - h DH_RSA_EXPORT_WITH_DES40_CBC_SHA 000F 2 c - h DH_RSA_WITH_DES_CBC_SHA 0010 3 c - h DH_RSA_WITH_3DES_EDE_CBC_SHA 0011 1 c d d DHE_DSS_EXPORT_WITH_DES40_CBC_SHA 0012 2 c d d DHE_DSS_WITH_DES_CBC_SHA 0013 3 c d d DHE_DSS_WITH_3DES_EDE_CBC_SHA 0014 1 c d r DHE_RSA_EXPORT_WITH_DES40_CBC_SHA 0015 2 c d r DHE_RSA_WITH_DES_CBC_SHA 0016 3 c d r DHE_RSA_WITH_3DES_EDE_CBC_SHA 0017 1 r d n DH_anon_EXPORT_WITH_RC4_40_MD5 0018 3 r d n DH_anon_WITH_RC4_128_MD5 0019 1 c d n DH_anon_EXPORT_WITH_DES40_CBC_SHA 001A 2 c d n DH_anon_WITH_DES_CBC_SHA 001B 3 c d n DH_anon_WITH_3DES_EDE_CBC_SHA 001E 2 c - p KRB5_WITH_DES_CBC_SHA 001F 3 c - p KRB5_WITH_3DES_EDE_CBC_SHA 0020 3 r - p KRB5_WITH_RC4_128_SHA 0021 3 c - p KRB5_WITH_IDEA_CBC_SHA 0022 2 c - p KRB5_WITH_DES_CBC_MD5 0023 3 c - p KRB5_WITH_3DES_EDE_CBC_MD5 0024 3 r - p KRB5_WITH_RC4_128_MD5 0025 3 c - p KRB5_WITH_IDEA_CBC_MD5 0026 1 c - p KRB5_EXPORT_WITH_DES_CBC_40_SHA 0027 1 c - p KRB5_EXPORT_WITH_RC2_CBC_40_SHA 0028 1 r - p KRB5_EXPORT_WITH_RC4_40_SHA 0029 1 c - p KRB5_EXPORT_WITH_DES_CBC_40_MD5 002A 1 c - p KRB5_EXPORT_WITH_RC2_CBC_40_MD5 002B 1 r - p KRB5_EXPORT_WITH_RC4_40_MD5 002C 0 - - p PSK_WITH_NULL_SHA 002D 0 - d p DHE_PSK_WITH_NULL_SHA 002E 0 - - q RSA_PSK_WITH_NULL_SHA 002F 3 c - r RSA_WITH_AES_128_CBC_SHA 0030 3 c - h DH_DSS_WITH_AES_128_CBC_SHA 0031 3 c - h DH_RSA_WITH_AES_128_CBC_SHA 0032 3 c d d DHE_DSS_WITH_AES_128_CBC_SHA 0033 3 c d r DHE_RSA_WITH_AES_128_CBC_SHA 0034 3 c d n DH_anon_WITH_AES_128_CBC_SHA 0035 3 c - r RSA_WITH_AES_256_CBC_SHA 0036 3 c - h DH_DSS_WITH_AES_256_CBC_SHA 0037 3 c - h DH_RSA_WITH_AES_256_CBC_SHA 0038 3 c d d DHE_DSS_WITH_AES_256_CBC_SHA 0039 3 c d r DHE_RSA_WITH_AES_256_CBC_SHA 003A 3 c d n DH_anon_WITH_AES_256_CBC_SHA 003B 0 - - r RSA_WITH_NULL_SHA256 003C 3 c - r RSA_WITH_AES_128_CBC_SHA256 003D 3 c - r RSA_WITH_AES_256_CBC_SHA256 003E 3 c - h DH_DSS_WITH_AES_128_CBC_SHA256 003F 3 c - h DH_RSA_WITH_AES_128_CBC_SHA256 0040 3 c d d DHE_DSS_WITH_AES_128_CBC_SHA256 0041 3 c - r RSA_WITH_CAMELLIA_128_CBC_SHA 0042 3 c - h DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0043 3 c - h DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0044 3 c d d DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0045 3 c d r DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0046 3 c d n DH_anon_WITH_CAMELLIA_128_CBC_SHA 0067 3 c d r DHE_RSA_WITH_AES_128_CBC_SHA256 0068 3 c - h DH_DSS_WITH_AES_256_CBC_SHA256 0069 3 c - h DH_RSA_WITH_AES_256_CBC_SHA256 006A 3 c d d DHE_DSS_WITH_AES_256_CBC_SHA256 006B 3 c d r DHE_RSA_WITH_AES_256_CBC_SHA256 006C 3 c d n DH_anon_WITH_AES_128_CBC_SHA256 006D 3 c d n DH_anon_WITH_AES_256_CBC_SHA256 0084 3 c - r RSA_WITH_CAMELLIA_256_CBC_SHA 0085 3 c - h DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0086 3 c - h DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0087 3 c d d DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0088 3 c d r DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0089 3 c d n DH_anon_WITH_CAMELLIA_256_CBC_SHA 008A 3 r - p PSK_WITH_RC4_128_SHA 008B 3 c - p PSK_WITH_3DES_EDE_CBC_SHA 008C 3 c - p PSK_WITH_AES_128_CBC_SHA 008D 3 c - p PSK_WITH_AES_256_CBC_SHA 008E 3 r d p DHE_PSK_WITH_RC4_128_SHA 008F 3 c d p DHE_PSK_WITH_3DES_EDE_CBC_SHA 0090 3 c d p DHE_PSK_WITH_AES_128_CBC_SHA 0091 3 c d p DHE_PSK_WITH_AES_256_CBC_SHA 0092 3 r - q RSA_PSK_WITH_RC4_128_SHA 0093 3 c - q RSA_PSK_WITH_3DES_EDE_CBC_SHA 0094 3 c - q RSA_PSK_WITH_AES_128_CBC_SHA 0095 3 c - q RSA_PSK_WITH_AES_256_CBC_SHA 0096 3 c - r RSA_WITH_SEED_CBC_SHA 0097 3 c - h DH_DSS_WITH_SEED_CBC_SHA 0098 3 c - h DH_RSA_WITH_SEED_CBC_SHA 0099 3 c d d DHE_DSS_WITH_SEED_CBC_SHA 009A 3 c d r DHE_RSA_WITH_SEED_CBC_SHA 009B 3 c d n DH_anon_WITH_SEED_CBC_SHA 009C 3 - - r RSA_WITH_AES_128_GCM_SHA256 009D 3 - - r RSA_WITH_AES_256_GCM_SHA384 009E 3 - d r DHE_RSA_WITH_AES_128_GCM_SHA256 009F 3 - d r DHE_RSA_WITH_AES_256_GCM_SHA384 00A0 3 - - h DH_RSA_WITH_AES_128_GCM_SHA256 00A1 3 - - h DH_RSA_WITH_AES_256_GCM_SHA384 00A2 3 - d d DHE_DSS_WITH_AES_128_GCM_SHA256 00A3 3 - d d DHE_DSS_WITH_AES_256_GCM_SHA384 00A4 3 - - h DH_DSS_WITH_AES_128_GCM_SHA256 00A5 3 - - h DH_DSS_WITH_AES_256_GCM_SHA384 00A6 3 - d n DH_anon_WITH_AES_128_GCM_SHA256 00A7 3 - d n DH_anon_WITH_AES_256_GCM_SHA384 00A8 3 - - p PSK_WITH_AES_128_GCM_SHA256 00A9 3 - - p PSK_WITH_AES_256_GCM_SHA384 00AA 3 - d p DHE_PSK_WITH_AES_128_GCM_SHA256 00AB 3 - d p DHE_PSK_WITH_AES_256_GCM_SHA384 00AC 3 - - q RSA_PSK_WITH_AES_128_GCM_SHA256 00AD 3 - - q RSA_PSK_WITH_AES_256_GCM_SHA384 00AE 3 c - p PSK_WITH_AES_128_CBC_SHA256 00AF 3 c - p PSK_WITH_AES_256_CBC_SHA384 00B0 0 - - p PSK_WITH_NULL_SHA256 00B1 0 - - p PSK_WITH_NULL_SHA384 00B2 3 c d p DHE_PSK_WITH_AES_128_CBC_SHA256 00B3 3 c d p DHE_PSK_WITH_AES_256_CBC_SHA384 00B4 0 - d p DHE_PSK_WITH_NULL_SHA256 00B5 0 - d p DHE_PSK_WITH_NULL_SHA384 00B6 3 c - q RSA_PSK_WITH_AES_128_CBC_SHA256 00B7 3 c - q RSA_PSK_WITH_AES_256_CBC_SHA384 00B8 0 - - q RSA_PSK_WITH_NULL_SHA256 00B9 0 - - q RSA_PSK_WITH_NULL_SHA384 00BA 3 c - r RSA_WITH_CAMELLIA_128_CBC_SHA256 00BB 3 c - h DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 00BC 3 c - h DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 00BD 3 c d d DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 00BE 3 c d r DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 00BF 3 c d n DH_anon_WITH_CAMELLIA_128_CBC_SHA256 00C0 3 c - r RSA_WITH_CAMELLIA_256_CBC_SHA256 00C1 3 c - h DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 00C2 3 c - h DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 00C3 3 c d d DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 00C4 3 c d r DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 00C5 3 c d n DH_anon_WITH_CAMELLIA_256_CBC_SHA256 C001 0 - - e ECDH_ECDSA_WITH_NULL_SHA C002 3 r - e ECDH_ECDSA_WITH_RC4_128_SHA C003 3 c - e ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA C004 3 c - e ECDH_ECDSA_WITH_AES_128_CBC_SHA C005 3 c - e ECDH_ECDSA_WITH_AES_256_CBC_SHA C006 0 - e e ECDHE_ECDSA_WITH_NULL_SHA C007 3 r e e ECDHE_ECDSA_WITH_RC4_128_SHA C008 3 c e e ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA C009 3 c e e ECDHE_ECDSA_WITH_AES_128_CBC_SHA C00A 3 c e e ECDHE_ECDSA_WITH_AES_256_CBC_SHA C00B 0 - - e ECDH_RSA_WITH_NULL_SHA C00C 3 r - e ECDH_RSA_WITH_RC4_128_SHA C00D 3 c - e ECDH_RSA_WITH_3DES_EDE_CBC_SHA C00E 3 c - e ECDH_RSA_WITH_AES_128_CBC_SHA C00F 3 c - e ECDH_RSA_WITH_AES_256_CBC_SHA C010 0 - e r ECDHE_RSA_WITH_NULL_SHA C011 3 r e r ECDHE_RSA_WITH_RC4_128_SHA C012 3 c e r ECDHE_RSA_WITH_3DES_EDE_CBC_SHA C013 3 c e r ECDHE_RSA_WITH_AES_128_CBC_SHA C014 3 c e r ECDHE_RSA_WITH_AES_256_CBC_SHA C015 0 - e n ECDH_anon_WITH_NULL_SHA C016 3 r e n ECDH_anon_WITH_RC4_128_SHA C017 3 c e n ECDH_anon_WITH_3DES_EDE_CBC_SHA C018 3 c e n ECDH_anon_WITH_AES_128_CBC_SHA C019 3 c e n ECDH_anon_WITH_AES_256_CBC_SHA C01A 3 c s n SRP_SHA_WITH_3DES_EDE_CBC_SHA C01B 3 c s n SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA C01C 3 c s n SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA C01D 3 c s n SRP_SHA_WITH_AES_128_CBC_SHA C01E 3 c s n SRP_SHA_RSA_WITH_AES_128_CBC_SHA C01F 3 c s n SRP_SHA_DSS_WITH_AES_128_CBC_SHA C020 3 c s n SRP_SHA_WITH_AES_256_CBC_SHA C021 3 c s n SRP_SHA_RSA_WITH_AES_256_CBC_SHA C022 3 c s n SRP_SHA_DSS_WITH_AES_256_CBC_SHA C023 3 c e e ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 C024 3 c e e ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 C025 3 c - e ECDH_ECDSA_WITH_AES_128_CBC_SHA256 C026 3 c - e ECDH_ECDSA_WITH_AES_256_CBC_SHA384 C027 3 c e r ECDHE_RSA_WITH_AES_128_CBC_SHA256 C028 3 c e r ECDHE_RSA_WITH_AES_256_CBC_SHA384 C029 3 c - e ECDH_RSA_WITH_AES_128_CBC_SHA256 C02A 3 c - e ECDH_RSA_WITH_AES_256_CBC_SHA384 C02B 3 - e e ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 C02C 3 - e e ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 C02D 3 - - e ECDH_ECDSA_WITH_AES_128_GCM_SHA256 C02E 3 - - e ECDH_ECDSA_WITH_AES_256_GCM_SHA384 C02F 3 - e r ECDHE_RSA_WITH_AES_128_GCM_SHA256 C030 3 - e r ECDHE_RSA_WITH_AES_256_GCM_SHA384 C031 3 - - e ECDH_RSA_WITH_AES_128_GCM_SHA256 C032 3 - - e ECDH_RSA_WITH_AES_256_GCM_SHA384 C033 3 r e p ECDHE_PSK_WITH_RC4_128_SHA C034 3 c e p ECDHE_PSK_WITH_3DES_EDE_CBC_SHA C035 3 c e p ECDHE_PSK_WITH_AES_128_CBC_SHA C036 3 c e p ECDHE_PSK_WITH_AES_256_CBC_SHA C037 3 c e p ECDHE_PSK_WITH_AES_128_CBC_SHA256 C038 3 c e p ECDHE_PSK_WITH_AES_256_CBC_SHA384 C039 0 - e p ECDHE_PSK_WITH_NULL_SHA C03A 0 - e p ECDHE_PSK_WITH_NULL_SHA256 C03B 0 - e p ECDHE_PSK_WITH_NULL_SHA384 C03C 3 c - r RSA_WITH_ARIA_128_CBC_SHA256 C03D 3 c - r RSA_WITH_ARIA_256_CBC_SHA384 C03E 3 c - h DH_DSS_WITH_ARIA_128_CBC_SHA256 C03F 3 c - h DH_DSS_WITH_ARIA_256_CBC_SHA384 C040 3 c - h DH_RSA_WITH_ARIA_128_CBC_SHA256 C041 3 c - h DH_RSA_WITH_ARIA_256_CBC_SHA384 C042 3 c d d DHE_DSS_WITH_ARIA_128_CBC_SHA256 C043 3 c d d DHE_DSS_WITH_ARIA_256_CBC_SHA384 C044 3 c d r DHE_RSA_WITH_ARIA_128_CBC_SHA256 C045 3 c d r DHE_RSA_WITH_ARIA_256_CBC_SHA384 C046 3 c d n DH_anon_WITH_ARIA_128_CBC_SHA256 C047 3 c d n DH_anon_WITH_ARIA_256_CBC_SHA384 C048 3 c e e ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 C049 3 c e e ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 C04A 3 c - e ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 C04B 3 c - e ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 C04C 3 c e r ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 C04D 3 c e r ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 C04E 3 c - e ECDH_RSA_WITH_ARIA_128_CBC_SHA256 C04F 3 c - e ECDH_RSA_WITH_ARIA_256_CBC_SHA384 C050 3 - - r RSA_WITH_ARIA_128_GCM_SHA256 C051 3 - - r RSA_WITH_ARIA_256_GCM_SHA384 C052 3 - d r DHE_RSA_WITH_ARIA_128_GCM_SHA256 C053 3 - d r DHE_RSA_WITH_ARIA_256_GCM_SHA384 C054 3 - - h DH_RSA_WITH_ARIA_128_GCM_SHA256 C055 3 - - h DH_RSA_WITH_ARIA_256_GCM_SHA384 C056 3 - d d DHE_DSS_WITH_ARIA_128_GCM_SHA256 C057 3 - d d DHE_DSS_WITH_ARIA_256_GCM_SHA384 C058 3 - - h DH_DSS_WITH_ARIA_128_GCM_SHA256 C059 3 - - h DH_DSS_WITH_ARIA_256_GCM_SHA384 C05A 3 - d n DH_anon_WITH_ARIA_128_GCM_SHA256 C05B 3 - d n DH_anon_WITH_ARIA_256_GCM_SHA384 C05C 3 - e e ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 C05D 3 - e e ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 C05E 3 - - e ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 C05F 3 - - e ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 C060 3 - e r ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 C061 3 - e r ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 C062 3 - - e ECDH_RSA_WITH_ARIA_128_GCM_SHA256 C063 3 - - e ECDH_RSA_WITH_ARIA_256_GCM_SHA384 C064 3 c - p PSK_WITH_ARIA_128_CBC_SHA256 C065 3 c - p PSK_WITH_ARIA_256_CBC_SHA384 C066 3 c d p DHE_PSK_WITH_ARIA_128_CBC_SHA256 C067 3 c d p DHE_PSK_WITH_ARIA_256_CBC_SHA384 C068 3 c - q RSA_PSK_WITH_ARIA_128_CBC_SHA256 C069 3 c - q RSA_PSK_WITH_ARIA_256_CBC_SHA384 C06A 3 - - p PSK_WITH_ARIA_128_GCM_SHA256 C06B 3 - - p PSK_WITH_ARIA_256_GCM_SHA384 C06C 3 - d p DHE_PSK_WITH_ARIA_128_GCM_SHA256 C06D 3 - d p DHE_PSK_WITH_ARIA_256_GCM_SHA384 C06E 3 - - q RSA_PSK_WITH_ARIA_128_GCM_SHA256 C06F 3 - - q RSA_PSK_WITH_ARIA_256_GCM_SHA384 C070 3 c e p ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 C071 3 c e p ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 C072 3 c e e ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 C073 3 c e e ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 C074 3 c - e ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 C075 3 c - e ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 C076 3 c e r ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 C077 3 c e r ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 C078 3 c - e ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 C079 3 c - e ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 C07A 3 - - r RSA_WITH_CAMELLIA_128_GCM_SHA256 C07B 3 - - r RSA_WITH_CAMELLIA_256_GCM_SHA384 C07C 3 - d r DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 C07D 3 - d r DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 C07E 3 - - h DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 C07F 3 - - h DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 C080 3 - d d DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 C081 3 - d d DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 C082 3 - - h DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 C083 3 - - h DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 C084 3 - d n DH_anon_WITH_CAMELLIA_128_GCM_SHA256 C085 3 - d n DH_anon_WITH_CAMELLIA_256_GCM_SHA384 C086 3 - e e ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 C087 3 - e e ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 C088 3 - - e ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 C089 3 - - e ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 C08A 3 - e r ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 C08B 3 - e r ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 C08C 3 - - e ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 C08D 3 - - e ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 C08E 3 - - p PSK_WITH_CAMELLIA_128_GCM_SHA256 C08F 3 - - p PSK_WITH_CAMELLIA_256_GCM_SHA384 C090 3 - d p DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 C091 3 - d p DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 C092 3 - - q RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 C093 3 - - q RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 C094 3 c - p PSK_WITH_CAMELLIA_128_CBC_SHA256 C095 3 c - p PSK_WITH_CAMELLIA_256_CBC_SHA384 C096 3 c d p DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 C097 3 c d p DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 C098 3 c - q RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 C099 3 c - q RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 C09A 3 c e p ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 C09B 3 c e p ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 C09C 3 - - r RSA_WITH_AES_128_CCM C09D 3 - - r RSA_WITH_AES_256_CCM C09E 3 - d r DHE_RSA_WITH_AES_128_CCM C09F 3 - d r DHE_RSA_WITH_AES_256_CCM C0A0 3 - - r RSA_WITH_AES_128_CCM_8 C0A1 3 - - r RSA_WITH_AES_256_CCM_8 C0A2 3 - d r DHE_RSA_WITH_AES_128_CCM_8 C0A3 3 - d r DHE_RSA_WITH_AES_256_CCM_8 C0A4 3 - - p PSK_WITH_AES_128_CCM C0A5 3 - - p PSK_WITH_AES_256_CCM C0A6 3 - d p DHE_PSK_WITH_AES_128_CCM C0A7 3 - d p DHE_PSK_WITH_AES_256_CCM C0A8 3 - - p PSK_WITH_AES_128_CCM_8 C0A9 3 - - p PSK_WITH_AES_256_CCM_8 C0AA 3 - d p PSK_DHE_WITH_AES_128_CCM_8 C0AB 3 - d p PSK_DHE_WITH_AES_256_CCM_8 C0AC 3 - e e ECDHE_ECDSA_WITH_AES_128_CCM C0AD 3 - e e ECDHE_ECDSA_WITH_AES_256_CCM C0AE 3 - e e ECDHE_ECDSA_WITH_AES_128_CCM_8 C0AF 3 - e e ECDHE_ECDSA_WITH_AES_256_CCM_8 # These ones are from draft-mavrogiannopoulos-chacha-tls-01 # Apparently some servers (Google...) deployed them. # We use the suffix '_OLD' to signify that they are not registered at # the IANA (and probably will never be). CC12 3 - - r RSA_WITH_CHACHA20_POLY1305_OLD CC13 3 - e r ECDHE_RSA_WITH_CHACHA20_POLY1305_OLD CC14 3 - e e ECDHE_ECDSA_WITH_CHACHA20_POLY1305_OLD CC15 3 - d r DHE_RSA_WITH_CHACHA20_POLY1305_OLD CC16 3 - d p DHE_PSK_WITH_CHACHA20_POLY1305_OLD CC17 3 - - p PSK_WITH_CHACHA20_POLY1305_OLD CC18 3 - e p ECDHE_PSK_WITH_CHACHA20_POLY1305_OLD CC19 3 - - q RSA_PSK_WITH_CHACHA20_POLY1305_OLD # Defined in draft-ietf-tls-chacha20-poly1305-04 CCA8 3 - e r ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 CCA9 3 - e e ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 CCAA 3 - d r DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 CCAB 3 - - p PSK_WITH_CHACHA20_POLY1305_SHA256 CCAC 3 - e p ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 CCAD 3 - d p DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 CCAE 3 - - q RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 "; /* * We do not support FORTEZZA cipher suites, because the * protocol is not published, and nobody uses it anyway. * One of the FORTEZZA cipher suites conflicts with one * of the Kerberos cipher suites (same ID: 0x001E). */ }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.ComponentModel; using XenAdmin.Controls; using XenAPI; using XenAdmin.Core; using XenAdmin.Properties; using System.Threading; using System.Drawing; using System.Drawing.Design; using System.Collections.ObjectModel; using XenAdmin.Network; namespace XenAdmin.Commands { /// <summary> /// This is the base ToolStripMenuItem for StartVMOnHostToolStripMenuItem, ResumeVMOnHostToolStripMenuItem and MigrateVMToolStripMenuItem. /// </summary> internal abstract class VMOperationToolStripMenuItem : CommandToolStripMenuItem { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly vm_operations _operation; private readonly bool _resumeAfter; protected VMOperationToolStripMenuItem(Command command, bool inContextMenu, vm_operations operation) : base(command, inContextMenu) { if (operation != vm_operations.start_on && operation != vm_operations.resume_on && operation != vm_operations.pool_migrate) { throw new ArgumentException("Invalid operation", "operation"); } if (operation.Equals(vm_operations.resume_on)) _resumeAfter = true; _operation = operation; base.DropDownItems.Add(new ToolStripMenuItem()); } protected override void OnDropDownOpening(EventArgs e) { base.DropDownItems.Clear(); // Work around bug in tool kit where disabled menu items show their dropdown menus if (!Enabled) { ToolStripMenuItem emptyMenuItem = new ToolStripMenuItem(Messages.HOST_MENU_EMPTY); emptyMenuItem.Font = Program.DefaultFont; emptyMenuItem.Enabled = false; base.DropDownItems.Add(emptyMenuItem); return; } VisualMenuItemAlignData.ParentStrip = this; IXenConnection connection = Command.GetSelection()[0].Connection; bool wlb = Helpers.WlbEnabled(connection); if (wlb) { base.DropDownItems.Add(new VMOperationToolStripMenuSubItem(Messages.WLB_OPT_MENU_OPTIMAL_SERVER, Images.StaticImages._000_ServerWlb_h32bit_16)); } else { base.DropDownItems.Add(new VMOperationToolStripMenuSubItem(Messages.HOME_SERVER_MENU_ITEM, Images.StaticImages._000_ServerHome_h32bit_16)); } List<Host> hosts = new List<Host>(connection.Cache.Hosts); hosts.Sort(); foreach (Host host in hosts) { VMOperationToolStripMenuSubItem item = new VMOperationToolStripMenuSubItem(String.Format(Messages.MAINWINDOW_CONTEXT_UPDATING, host.name_label.EscapeAmpersands()), Images.StaticImages._000_ServerDisconnected_h32bit_16); item.Tag = host; base.DropDownItems.Add(item); } // start a new thread to evaluate which hosts can be used. ThreadPool.QueueUserWorkItem(delegate { SelectedItemCollection selection = Command.GetSelection(); Session session = selection[0].Connection.DuplicateSession(); WlbRecommendations recommendations = new WlbRecommendations(selection.AsXenObjects<VM>(), session); recommendations.Initialize(); if (recommendations.IsError) { EnableAppropriateHostsNoWlb(session); } else { EnableAppropriateHostsWlb(session, recommendations); } }); } private void EnableAppropriateHostsWlb(Session session, WlbRecommendations recommendations) { SelectedItemCollection selection = Command.GetSelection(); // set the first menu item to be the WLB optimal server menu item Program.Invoke(Program.MainWindow, delegate { VMOperationToolStripMenuSubItem firstItem = (VMOperationToolStripMenuSubItem)base.DropDownItems[0]; firstItem.Command = new VMOperationWlbOptimalServerCommand(Command.MainWindowCommandInterface, selection, _operation, recommendations); }); List<VMOperationToolStripMenuSubItem> hostMenuItems = new List<VMOperationToolStripMenuSubItem>(); Program.Invoke(Program.MainWindow, delegate { foreach (VMOperationToolStripMenuSubItem item in base.DropDownItems) { Host host = item.Tag as Host; if (host != null) { item.Command = new VMOperationWlbHostCommand(Command.MainWindowCommandInterface, selection, host, _operation, recommendations.GetStarRating(host)); hostMenuItems.Add(item); } } }); // Shuffle the list to make it look cool Helpers.ShuffleList(hostMenuItems); // sort the hostMenuItems by star rating hostMenuItems.Sort(new WlbHostStarCompare()); // refresh the drop-down-items from the menuItems. Program.Invoke(Program.MainWindow, delegate() { foreach (VMOperationToolStripMenuSubItem menuItem in hostMenuItems) { base.DropDownItems.Insert(hostMenuItems.IndexOf(menuItem) + 1, menuItem); } }); Program.Invoke(Program.MainWindow, () => AddAdditionalMenuItems(selection)); } private void EnableAppropriateHostsNoWlb(Session session) { SelectedItemCollection selection = Command.GetSelection(); IXenConnection connection = selection[0].Connection; VMOperationCommand cmdHome = new VMOperationHomeServerCommand(Command.MainWindowCommandInterface, selection, _operation, session); Host affinityHost = connection.Resolve(((VM)Command.GetSelection()[0].XenObject).affinity); VMOperationCommand cpmCmdHome = new CrossPoolMigrateToHomeCommand(Command.MainWindowCommandInterface, selection, affinityHost); Program.Invoke(Program.MainWindow, delegate { var firstItem = (VMOperationToolStripMenuSubItem)base.DropDownItems[0]; bool oldMigrateToHomeCmdCanRun = cmdHome.CanExecute(); if (affinityHost == null || _operation == vm_operations.start_on || !oldMigrateToHomeCmdCanRun && !cpmCmdHome.CanExecute()) firstItem.Command = cmdHome; else firstItem.Command = oldMigrateToHomeCmdCanRun ? cmdHome : cpmCmdHome; }); List<VMOperationToolStripMenuSubItem> dropDownItems = DropDownItems.Cast<VMOperationToolStripMenuSubItem>().ToList(); foreach (VMOperationToolStripMenuSubItem item in dropDownItems) { Host host = item.Tag as Host; if (host != null) { VMOperationCommand cmd = new VMOperationHostCommand(Command.MainWindowCommandInterface, selection, delegate { return host; }, host.Name.EscapeAmpersands(), _operation, session); VMOperationCommand cpmCmd = new CrossPoolMigrateCommand(Command.MainWindowCommandInterface, selection, host, _resumeAfter); VMOperationToolStripMenuSubItem tempItem = item; Program.Invoke(Program.MainWindow, delegate { bool oldMigrateCmdCanRun = cmd.CanExecute(); if (_operation == vm_operations.start_on || !oldMigrateCmdCanRun && !cpmCmd.CanExecute()) tempItem.Command = cmd; else tempItem.Command = oldMigrateCmdCanRun ? cmd : cpmCmd; }); } } Program.Invoke(Program.MainWindow, () => AddAdditionalMenuItems(selection)); } /// <summary> /// Hook to add additional members to the menu item /// Note: Called on main window thread by executing code /// </summary> /// <param name="selection"></param> protected virtual void AddAdditionalMenuItems(SelectedItemCollection selection) { return; } /// <summary> /// This class is an implementation of the 'IComparer' interface /// for sorting vm placement menuItem List when wlb is enabled /// </summary> private class WlbHostStarCompare : IComparer<VMOperationToolStripMenuSubItem> { public int Compare(VMOperationToolStripMenuSubItem x, VMOperationToolStripMenuSubItem y) { int result = 0; // if x and y are enabled, compare their start rating if (x.Enabled && y.Enabled) result = y.StarRating.CompareTo(x.StarRating); // if x and y are disabled, they are equal else if (!x.Enabled && !y.Enabled) result = 0; // if x is disabled, y is greater else if (!x.Enabled) result = 1; // if y is disabled, x is greater else if (!y.Enabled) result = -1; return result; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using JetBrains.Metadata.Reader.API; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CodeAnnotations; using JetBrains.ReSharper.Psi.ControlFlow; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.ControlFlow; using JetBrains.ReSharper.Psi.CSharp.Impl.ControlFlow; using JetBrains.ReSharper.Psi.CSharp.Impl.ControlFlow.NullableAnalysis; using JetBrains.ReSharper.Psi.CSharp.Impl.ControlFlow.NullableAnalysis.Runner; using JetBrains.ReSharper.Psi.CSharp.Parsing; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Parsing; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.Psi.Util; namespace ReCommendedExtension.Analyzers.ControlFlow { [ElementProblemAnalyzer( typeof(ICSharpTreeNode), HighlightingTypes = new[] { typeof(RedundantAssertionStatementSuggestion), typeof(RedundantInlineAssertionSuggestion) })] public sealed class ControlFlowAnalyzer : ElementProblemAnalyzer<ICSharpTreeNode> { [Pure] [CanBeNull] static ICSharpExpression TryGetOtherOperand( [NotNull] IEqualityExpression equalityExpression, EqualityExpressionType equalityType, [NotNull] TokenNodeType operandNodeType) { if (equalityExpression.EqualityType == equalityType) { if (IsLiteral(equalityExpression.RightOperand, operandNodeType)) { return equalityExpression.LeftOperand; } if (IsLiteral(equalityExpression.LeftOperand, operandNodeType)) { return equalityExpression.RightOperand; } } return null; } [Pure] static bool IsLiteral([CanBeNull] IExpression expression, [NotNull] TokenNodeType tokenType) => (expression as ICSharpLiteralExpression)?.Literal?.GetTokenType() == tokenType; [Pure] static CSharpControlFlowNullReferenceState GetExpressionNullReferenceStateByNullableContext( [NotNull] CSharpCompilerNullableInspector nullabilityInspector, [NotNull] ICSharpExpression expression) { var type = expression.Type(); if (expression.IsDefaultValueOf(type)) { switch (type.Classify) { case TypeClassification.VALUE_TYPE: return type.IsNullable() ? CSharpControlFlowNullReferenceState.NULL : CSharpControlFlowNullReferenceState.NOT_NULL; case TypeClassification.REFERENCE_TYPE: return CSharpControlFlowNullReferenceState.NULL; case TypeClassification.UNKNOWN: return CSharpControlFlowNullReferenceState.UNKNOWN; // unconstrained generic type default: goto case TypeClassification.UNKNOWN; } } var closure = expression.GetContainingNode<ICSharpClosure>(); if (closure != null) { nullabilityInspector = nullabilityInspector.GetClosureAnalysisResult(closure) as CSharpCompilerNullableInspector; } var controlFlowGraph = nullabilityInspector?.ControlFlowGraph; var edge = controlFlowGraph?.GetLeafElementsFor(expression).LastOrDefault()?.Exits.FirstOrDefault(); if (edge != null) { var nullableContext = nullabilityInspector.GetContext(edge); switch (nullableContext?.ExpressionAnnotation) { case NullableAnnotation.NotAnnotated: case NullableAnnotation.NotNullable: return CSharpControlFlowNullReferenceState.NOT_NULL; case NullableAnnotation.Annotated: case NullableAnnotation.Nullable: return CSharpControlFlowNullReferenceState .MAY_BE_NULL; // todo: distinguish if the expression is "null" or just "may be null" here default: return CSharpControlFlowNullReferenceState.UNKNOWN; } } return CSharpControlFlowNullReferenceState.UNKNOWN; } [NotNull] readonly NullnessProvider nullnessProvider; [NotNull] readonly AssertionMethodAnnotationProvider assertionMethodAnnotationProvider; [NotNull] readonly AssertionConditionAnnotationProvider assertionConditionAnnotationProvider; [NotNull] readonly NullableReferenceTypesDataFlowAnalysisRunSynchronizer nullableReferenceTypesDataFlowAnalysisRunSynchronizer; public ControlFlowAnalyzer( [NotNull] CodeAnnotationsCache codeAnnotationsCache, [NotNull] NullableReferenceTypesDataFlowAnalysisRunSynchronizer nullableReferenceTypesDataFlowAnalysisRunSynchronizer) { nullnessProvider = codeAnnotationsCache.GetProvider<NullnessProvider>(); assertionMethodAnnotationProvider = codeAnnotationsCache.GetProvider<AssertionMethodAnnotationProvider>(); assertionConditionAnnotationProvider = codeAnnotationsCache.GetProvider<AssertionConditionAnnotationProvider>(); this.nullableReferenceTypesDataFlowAnalysisRunSynchronizer = nullableReferenceTypesDataFlowAnalysisRunSynchronizer; } void AnalyzeAssertions( [NotNull] ElementProblemAnalyzerData data, [NotNull] IHighlightingConsumer consumer, [NotNull] ICSharpTreeNode rootNode, [NotNull] ICSharpControlFlowGraph controlFlowGraph) { var assertions = Assertion.CollectAssertions(assertionMethodAnnotationProvider, assertionConditionAnnotationProvider, rootNode); assertions.ExceptWith( from highlightingInfo in consumer.Highlightings where highlightingInfo != null let redundantAssertionHighlighting = highlightingInfo.Highlighting as RedundantAssertionSuggestion where redundantAssertionHighlighting != null select redundantAssertionHighlighting.Assertion); if (assertions.Count == 0) { return; // no (new) assertions found } CSharpCompilerNullableInspector nullabilityInspector; CSharpControlFlowGraphInspector inspector; HashSet<IAsExpression> alwaysSuccessTryCastExpressions; if (rootNode.IsNullableWarningsContextEnabled()) { nullabilityInspector = (CSharpCompilerNullableInspector)nullableReferenceTypesDataFlowAnalysisRunSynchronizer.RunNullableAnalysisAndGetResults( rootNode, null, // wrong [NotNull] annotation in R# code ValueAnalysisMode.OFF); inspector = null; alwaysSuccessTryCastExpressions = null; } else { nullabilityInspector = null; inspector = CSharpControlFlowGraphInspector.Inspect(controlFlowGraph, data.GetValueAnalysisMode()); alwaysSuccessTryCastExpressions = new HashSet<IAsExpression>(inspector.AlwaysSuccessTryCastExpressions ?? Array.Empty<IAsExpression>()); } foreach (var assertion in assertions) { switch (assertion.AssertionConditionType) { case AssertionConditionType.IS_TRUE: AnalyzeWhenExpressionIsKnownToBeTrueOrFalse( consumer, nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, assertion, true); break; case AssertionConditionType.IS_FALSE: AnalyzeWhenExpressionIsKnownToBeTrueOrFalse( consumer, nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, assertion, false); break; case AssertionConditionType.IS_NOT_NULL: AnalyzeWhenExpressionIsKnownToBeNullOrNotNull( consumer, nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, assertion, false); break; case AssertionConditionType.IS_NULL: AnalyzeWhenExpressionIsKnownToBeNullOrNotNull( consumer, nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, assertion, true); break; } } } void AnalyzeWhenExpressionIsKnownToBeTrueOrFalse( [NotNull] IHighlightingConsumer context, [CanBeNull] CSharpCompilerNullableInspector nullabilityInspector, [CanBeNull] CSharpControlFlowGraphInspector inspector, [CanBeNull][ItemNotNull] HashSet<IAsExpression> alwaysSuccessTryCastExpressions, [NotNull] Assertion assertion, bool isKnownToBeTrue) { if (assertion is AssertionStatement assertionStatement) { if (nullabilityInspector != null && nullabilityInspector.ConditionIsAlwaysTrueOrFalseExpressions.TryGetValue(assertionStatement.Expression, out var value)) { switch (value) { case ConstantExpressionValue.TRUE when isKnownToBeTrue: context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is true here.", assertionStatement)); return; case ConstantExpressionValue.FALSE when !isKnownToBeTrue: context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is false here.", assertionStatement)); return; } } // pattern: Assert(true); or Assert(false); Debug.Assert(CSharpTokenType.TRUE_KEYWORD != null); Debug.Assert(CSharpTokenType.FALSE_KEYWORD != null); if (IsLiteral(assertionStatement.Expression, isKnownToBeTrue ? CSharpTokenType.TRUE_KEYWORD : CSharpTokenType.FALSE_KEYWORD)) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( $"Assertion is redundant because the expression is {(isKnownToBeTrue ? "true" : "false")} here.", assertionStatement)); } if (assertionStatement.Expression is IEqualityExpression equalityExpression) { // pattern: Assert(x != null); when x is known to be null or not null Debug.Assert(CSharpTokenType.NULL_KEYWORD != null); var expression = TryGetOtherOperand(equalityExpression, EqualityExpressionType.NE, CSharpTokenType.NULL_KEYWORD); if (expression != null) { switch (GetExpressionNullReferenceState(nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, expression)) { case CSharpControlFlowNullReferenceState.NOT_NULL: if (isKnownToBeTrue) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is true here.", assertionStatement)); } break; case CSharpControlFlowNullReferenceState.NULL: if (!isKnownToBeTrue) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is false here.", assertionStatement)); } break; } } // pattern: Assert(x == null); when x is known to be null or not null expression = TryGetOtherOperand(equalityExpression, EqualityExpressionType.EQEQ, CSharpTokenType.NULL_KEYWORD); if (expression != null) { switch (GetExpressionNullReferenceState(nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, expression)) { case CSharpControlFlowNullReferenceState.NOT_NULL: if (!isKnownToBeTrue) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is false here.", assertionStatement)); } break; case CSharpControlFlowNullReferenceState.NULL: if (isKnownToBeTrue) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is true here.", assertionStatement)); } break; } } } } } void AnalyzeWhenExpressionIsKnownToBeNullOrNotNull( [NotNull] IHighlightingConsumer context, [CanBeNull] CSharpCompilerNullableInspector nullabilityInspector, [CanBeNull] CSharpControlFlowGraphInspector inspector, [CanBeNull][ItemNotNull] HashSet<IAsExpression> alwaysSuccessTryCastExpressions, [NotNull] Assertion assertion, bool isKnownToBeNull) { if (assertion is AssertionStatement assertionStatement) { // pattern: Assert(null); Debug.Assert(CSharpTokenType.NULL_KEYWORD != null); if (isKnownToBeNull && IsLiteral(assertionStatement.Expression, CSharpTokenType.NULL_KEYWORD)) { context.AddHighlighting( new RedundantAssertionStatementSuggestion("Assertion is redundant because the expression is null here.", assertionStatement)); } // pattern: Assert(x); when x is known to be null or not null switch (GetExpressionNullReferenceState( nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, assertionStatement.Expression)) { case CSharpControlFlowNullReferenceState.NOT_NULL: if (!isKnownToBeNull) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is not null here.", assertionStatement)); } break; case CSharpControlFlowNullReferenceState.NULL: if (isKnownToBeNull) { context.AddHighlighting( new RedundantAssertionStatementSuggestion( "Assertion is redundant because the expression is null here.", assertionStatement)); } break; } } if (!isKnownToBeNull && assertion is InlineAssertion inlineAssertion && GetExpressionNullReferenceState( nullabilityInspector, inspector, alwaysSuccessTryCastExpressions, inlineAssertion.QualifierExpression) == CSharpControlFlowNullReferenceState.NOT_NULL) { context.AddHighlighting( new RedundantInlineAssertionSuggestion("Assertion is redundant because the expression is not null here.", inlineAssertion)); } } [Pure] CSharpControlFlowNullReferenceState GetExpressionNullReferenceState( [CanBeNull] CSharpCompilerNullableInspector nullabilityInspector, [CanBeNull] CSharpControlFlowGraphInspector inspector, [CanBeNull][ItemNotNull] HashSet<IAsExpression> alwaysSuccessTryCastExpressions, [NotNull] ICSharpExpression expression) { if (nullabilityInspector != null) { return GetExpressionNullReferenceStateByNullableContext(nullabilityInspector, expression); } Debug.Assert(inspector != null); Debug.Assert(alwaysSuccessTryCastExpressions != null); while (true) { switch (expression) { case IReferenceExpression referenceExpression: if (referenceExpression is IConditionalAccessExpression conditionalAccessExpression && conditionalAccessExpression.HasConditionalAccessSign) { var referenceState = GetExpressionNullReferenceStateByAnnotations(referenceExpression); if (referenceState == CSharpControlFlowNullReferenceState.NOT_NULL) { expression = conditionalAccessExpression.ConditionalQualifier; continue; } } var nullReferenceState = inspector.GetExpressionNullReferenceState(referenceExpression, true); if (nullReferenceState == CSharpControlFlowNullReferenceState.UNKNOWN) { nullReferenceState = GetExpressionNullReferenceStateByAnnotations(referenceExpression); } return nullReferenceState; case IAsExpression asExpression when alwaysSuccessTryCastExpressions.Contains(asExpression): return CSharpControlFlowNullReferenceState.NOT_NULL; case IObjectCreationExpression _: return CSharpControlFlowNullReferenceState.NOT_NULL; case IInvocationExpression invocationExpression: if (invocationExpression.InvokedExpression is IReferenceExpression invokedExpression) { return GetExpressionNullReferenceStateByAnnotations(invokedExpression); } goto default; default: return CSharpControlFlowNullReferenceState.UNKNOWN; } } } [Pure] CSharpControlFlowNullReferenceState GetExpressionNullReferenceStateByAnnotations([NotNull] IReferenceExpression referenceExpression) { switch (referenceExpression.Reference.Resolve().DeclaredElement) { case IFunction function when nullnessProvider.GetInfo(function) == CodeAnnotationNullableValue.NOT_NULL: return CSharpControlFlowNullReferenceState.NOT_NULL; case ITypeOwner typeOwner when !typeOwner.Type.IsDelegateType(): if (typeOwner is IAttributesOwner attributesOwner && nullnessProvider.GetInfo(attributesOwner) == CodeAnnotationNullableValue.NOT_NULL) { return CSharpControlFlowNullReferenceState.NOT_NULL; } goto default; default: return CSharpControlFlowNullReferenceState.UNKNOWN; } } protected override void Run(ICSharpTreeNode element, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { var controlFlowGraph = (ICSharpControlFlowGraph)ControlFlowBuilder.GetGraph(element); if (controlFlowGraph != null) { AnalyzeAssertions(data, consumer, element, controlFlowGraph); } } } }
/* * 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 { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; /// <summary> /// Grid proxy with fake serialization. /// </summary> [Serializable] [ExcludeFromCodeCoverage] internal class IgniteProxy : IIgnite, IBinaryWriteAware, ICluster { /** */ [NonSerialized] private readonly Ignite _ignite; /// <summary> /// Default ctor for marshalling. /// </summary> public IgniteProxy() { // No-op. } /// <summary> /// Constructor. /// </summary> /// <param name="ignite">Grid.</param> public IgniteProxy(Ignite ignite) { _ignite = ignite; } /** <inheritdoc /> */ public string Name { get { return _ignite.Name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ public IIgnite Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _ignite.GetCluster().ForLocal(); } /** <inheritdoc /> */ public ICompute GetCompute() { return _ignite.GetCompute(); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _ignite.GetCluster().ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(ICollection<Guid> ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _ignite.GetCluster().ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { return _ignite.GetCluster().ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _ignite.GetCluster().ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _ignite.GetCluster().ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _ignite.GetCluster().ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _ignite.GetCluster().ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _ignite.GetCluster().ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _ignite.GetCluster().ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { return _ignite.GetCluster().ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _ignite.GetCluster().ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _ignite.GetCluster().ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _ignite.GetCluster().ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _ignite.GetCluster().ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _ignite.GetCluster().ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _ignite.GetCluster().GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _ignite.GetCluster().GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _ignite.GetCluster().GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _ignite.GetCluster().GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] public void Dispose() { _ignite.Dispose(); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { return _ignite.GetCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { return _ignite.GetOrCreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.GetOrCreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.GetOrCreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { return _ignite.CreateCache<TK, TV>(name); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return _ignite.CreateCache<TK, TV>(configuration); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return _ignite.CreateCache<TK, TV>(configuration, nearConfiguration); } /** <inheritdoc /> */ public void DestroyCache(string name) { _ignite.DestroyCache(name); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _ignite.GetCluster().GetLocalNode(); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _ignite.GetCluster().PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _ignite.GetCluster().TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _ignite.GetCluster().GetTopology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _ignite.GetCluster().ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _ignite.GetCluster().ClientReconnectTask; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { return _ignite.GetDataStreamer<TK, TV>(cacheName); } /** <inheritdoc /> */ public IBinary GetBinary() { return _ignite.GetBinary(); } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string name) { return _ignite.GetAffinity(name); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return _ignite.GetTransactions(); } /** <inheritdoc /> */ public IMessaging GetMessaging() { return _ignite.GetMessaging(); } /** <inheritdoc /> */ public IEvents GetEvents() { return _ignite.GetEvents(); } /** <inheritdoc /> */ public IServices GetServices() { return _ignite.GetServices(); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { return _ignite.GetAtomicLong(name, initialValue, create); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return _ignite.GetConfiguration(); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.CreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return _ignite.GetOrCreateNearCache<TK, TV>(name, configuration); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return _ignite.GetCacheNames(); } /** <inheritdoc /> */ public ILogger Logger { get { return _ignite.Logger; } } /** <inheritdoc /> */ public event EventHandler Stopping { add { _ignite.Stopping += value; } remove { _ignite.Stopping -= value; } } /** <inheritdoc /> */ public event EventHandler Stopped { add { _ignite.Stopped += value; } remove { _ignite.Stopped -= value; } } /** <inheritdoc /> */ public event EventHandler ClientDisconnected { add { _ignite.ClientDisconnected += value; } remove { _ignite.ClientDisconnected -= value; } } /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected { add { _ignite.ClientReconnected += value; } remove { _ignite.ClientReconnected -= value; } } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { return _ignite.GetAtomicSequence(name, initialValue, create); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { return _ignite.GetAtomicReference(name, initialValue, create); } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { // No-op. } /// <summary> /// Target grid. /// </summary> internal Ignite Target { get { return _ignite; } } } }
#region Copyright (c) .NET Foundation and Contributors // // The MIT License (MIT) // // All rights reserved. // // 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 // https://github.com/dotnet/corefx/blob/v2.1.4/src/Common/src/System/PasteArguments.cs using System.Text; using System.Collections.Generic; namespace System { internal static partial class PasteArguments { internal static void AppendArgument(StringBuilder stringBuilder, string argument) { if (stringBuilder.Length != 0) { stringBuilder.Append(' '); } // Parsing rules for non-argv[0] arguments: // - Backslash is a normal character except followed by a quote. // - 2N backslashes followed by a quote ==> N literal backslashes followed by unescaped quote // - 2N+1 backslashes followed by a quote ==> N literal backslashes followed by a literal quote // - Parsing stops at first whitespace outside of quoted region. // - (post 2008 rule): A closing quote followed by another quote ==> literal quote, and parsing remains in quoting mode. if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument)) { // Simple case - no quoting or changes needed. stringBuilder.Append(argument); } else { stringBuilder.Append(Quote); int idx = 0; while (idx < argument.Length) { char c = argument[idx++]; if (c == Backslash) { int numBackSlash = 1; while (idx < argument.Length && argument[idx] == Backslash) { idx++; numBackSlash++; } if (idx == argument.Length) { // We'll emit an end quote after this so must double the number of backslashes. stringBuilder.Append(Backslash, numBackSlash * 2); } else if (argument[idx] == Quote) { // Backslashes will be followed by a quote. Must double the number of backslashes. stringBuilder.Append(Backslash, numBackSlash * 2 + 1); stringBuilder.Append(Quote); idx++; } else { // Backslash will not be followed by a quote, so emit as normal characters. stringBuilder.Append(Backslash, numBackSlash); } continue; } if (c == Quote) { // Escape the quote so it appears as a literal. This also guarantees that we won't end up generating a closing quote followed // by another quote (which parses differently pre-2008 vs. post-2008.) stringBuilder.Append(Backslash); stringBuilder.Append(Quote); continue; } stringBuilder.Append(c); } stringBuilder.Append(Quote); } } private static bool ContainsNoWhitespaceOrQuotes(string s) { for (int i = 0; i < s.Length; i++) { char c = s[i]; if (char.IsWhiteSpace(c) || c == Quote) { return false; } } return true; } private const char Quote = '\"'; private const char Backslash = '\\'; } } // https://github.com/dotnet/corefx/blob/v2.1.4/src/Common/src/System/PasteArguments.Unix.cs namespace System { internal static partial class PasteArguments { /// <summary> /// Repastes a set of arguments into a linear string that parses back into the originals under pre- or post-2008 VC parsing rules. /// On Unix: the rules for parsing the executable name (argv[0]) are ignored. /// </summary> internal static string PasteForUnix(IEnumerable<string> arguments, bool pasteFirstArgumentUsingArgV0Rules) { var stringBuilder = new StringBuilder(); foreach (string argument in arguments) { AppendArgument(stringBuilder, argument); } return stringBuilder.ToString(); } } } // https://github.com/dotnet/corefx/blob/v2.1.4/src/Common/src/System/PasteArguments.Windows.cs namespace System { internal static partial class PasteArguments { /// <summary> /// Repastes a set of arguments into a linear string that parses back into the originals under pre- or post-2008 VC parsing rules. /// The rules for parsing the executable name (argv[0]) are special, so you must indicate whether the first argument actually is argv[0]. /// </summary> internal static string PasteForWindows(IEnumerable<string> arguments, bool pasteFirstArgumentUsingArgV0Rules) { var stringBuilder = new StringBuilder(); foreach (string argument in arguments) { if (pasteFirstArgumentUsingArgV0Rules) { pasteFirstArgumentUsingArgV0Rules = false; // Special rules for argv[0] // - Backslash is a normal character. // - Quotes used to include whitespace characters. // - Parsing ends at first whitespace outside quoted region. // - No way to get a literal quote past the parser. bool hasWhitespace = false; foreach (char c in argument) { if (c == Quote) { throw new ApplicationException("The argv[0] argument cannot include a double quote."); } if (char.IsWhiteSpace(c)) { hasWhitespace = true; } } if (argument.Length == 0 || hasWhitespace) { stringBuilder.Append(Quote); stringBuilder.Append(argument); stringBuilder.Append(Quote); } else { stringBuilder.Append(argument); } } else { AppendArgument(stringBuilder, argument); } } return stringBuilder.ToString(); } } } namespace System { using Runtime.InteropServices; internal static partial class PasteArguments { internal static string Paste(IEnumerable<string> arguments, bool pasteFirstArgumentUsingArgV0Rules = false) => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PasteForWindows(arguments, pasteFirstArgumentUsingArgV0Rules) : PasteForUnix(arguments, pasteFirstArgumentUsingArgV0Rules); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; using System.Reflection; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MaskLoadDouble() { var test = new SimpleBinaryOpTest__MaskLoadDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MaskLoadDouble { private struct TestStruct { public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MaskLoadDouble testClass) { var result = Avx.MaskLoad((Double*)testClass._dataTable.inArray1Ptr, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(testClass._dataTable.inArray1Ptr, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__MaskLoadDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MaskLoadDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.MaskLoad( (Double*)_dataTable.inArray1Ptr, Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.MaskLoad( (Double*)_dataTable.inArray1Ptr, Avx.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.MaskLoad( (Double*)_dataTable.inArray1Ptr, Avx.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)), Avx.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.MaskLoad), new Type[] { typeof(Double*), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)), Avx.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.MaskLoad( (Double*)_dataTable.inArray1Ptr, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = (Double*)_dataTable.inArray1Ptr; var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Avx.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = (Double*)_dataTable.inArray1Ptr; var right = Avx.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Avx.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = (Double*)_dataTable.inArray1Ptr; var right = Avx.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Avx.MaskLoad(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MaskLoadDouble(); var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.MaskLoad((Double*)_dataTable.inArray1Ptr, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(void* left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits((BitConverter.DoubleToInt64Bits(right[0]) < 0) ? left[0] : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits((BitConverter.DoubleToInt64Bits(right[i]) < 0) ? left[i] : 0)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.MaskLoad)}<Double>(Double*, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Linq; namespace LinqToDB.Reflection { using Common; using Expressions; using Extensions; using Mapping; public class MemberAccessor { static readonly ConstructorInfo ArgumentExceptionConstructorInfo = typeof(ArgumentException).GetConstructor(new[] {typeof(string)}) ?? throw new Exception($"Can not retrieve information about constructor for {nameof(ArgumentException)}"); internal MemberAccessor(TypeAccessor typeAccessor, string memberName) { TypeAccessor = typeAccessor; if (memberName.IndexOf('.') < 0) { SetSimple(Expression.PropertyOrField(Expression.Constant(null, typeAccessor.Type), memberName).Member); } else { IsComplex = true; HasGetter = true; HasSetter = true; var members = memberName.Split('.'); var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var expr = (Expression)objParam; var infos = members.Select(m => { expr = Expression.PropertyOrField(expr, m); return new { member = ((MemberExpression)expr).Member, type = expr.Type, }; }).ToArray(); var lastInfo = infos[infos.Length - 1]; MemberInfo = lastInfo.member; Type = lastInfo.type; var checkNull = infos.Take(infos.Length - 1).Any(info => info.type.IsClassEx() || info.type.IsNullable()); // Build getter. // { if (checkNull) { var ret = Expression.Variable(Type, "ret"); Expression MakeGetter(Expression ex, int i) { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) return Expression.Assign(ret, next); if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); return Expression.Block( new[] { local }, Expression.Assign(local, next) as Expression, Expression.IfThen( Expression.NotEqual(local, Expression.Constant(null)), MakeGetter(local, i + 1))); } return MakeGetter(next, i + 1); } expr = Expression.Block( new[] { ret }, Expression.Assign(ret, new DefaultValueExpression(MappingSchema.Default, Type)), MakeGetter(objParam, 0), ret); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); } GetterExpression = Expression.Lambda(expr, objParam); } // Build setter. // { HasSetter = !infos.Any(info => info.member is PropertyInfo && ((PropertyInfo)info.member).GetSetMethodEx(true) == null); var valueParam = Expression.Parameter(Type, "value"); if (HasSetter) { if (checkNull) { var vars = new List<ParameterExpression>(); var exprs = new List<Expression>(); void MakeSetter(Expression ex, int i) { var info = infos[i]; var next = Expression.MakeMemberAccess(ex, info.member); if (i == infos.Length - 1) { exprs.Add(Expression.Assign(next, valueParam)); } else { if (next.Type.IsClassEx() || next.Type.IsNullable()) { var local = Expression.Variable(next.Type); vars.Add(local); exprs.Add(Expression.Assign(local, next)); exprs.Add( Expression.IfThen( Expression.Equal(local, Expression.Constant(null)), Expression.Block( Expression.Assign(local, Expression.New(local.Type)), Expression.Assign(next, local)))); MakeSetter(local, i + 1); } else { MakeSetter(next, i + 1); } } } MakeSetter(objParam, 0); expr = Expression.Block(vars, exprs); } else { expr = objParam; foreach (var info in infos) expr = Expression.MakeMemberAccess(expr, info.member); expr = Expression.Assign(expr, valueParam); } SetterExpression = Expression.Lambda(expr, objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] { fakeParam }, Expression.Assign(fakeParam, Expression.Constant(0))), objParam, valueParam); } } } SetExpressions(); } public MemberAccessor(TypeAccessor typeAccessor, MemberInfo memberInfo) { TypeAccessor = typeAccessor; SetSimple(memberInfo); SetExpressions(); } void SetSimple(MemberInfo memberInfo) { MemberInfo = memberInfo; Type = MemberInfo is PropertyInfo propertyInfo ? propertyInfo.PropertyType : ((FieldInfo)MemberInfo).FieldType; if (memberInfo is PropertyInfo info) { HasGetter = info.GetGetMethodEx(true) != null; HasSetter = info.GetSetMethodEx(true) != null; } else { HasGetter = true; HasSetter = !((FieldInfo)memberInfo).IsInitOnly; } var objParam = Expression.Parameter(TypeAccessor.Type, "obj"); var valueParam = Expression.Parameter(Type, "value"); if (HasGetter && memberInfo.IsDynamicColumnPropertyEx()) { IsComplex = true; if (TypeAccessor.DynamicColumnsStoreAccessor != null) { // get value via "Item" accessor; we're not null-checking var storageType = TypeAccessor.DynamicColumnsStoreAccessor.MemberInfo.GetMemberType(); var storedType = storageType.GetGenericArguments()[1]; var outVar = Expression.Variable(storedType); var resultVar = Expression.Variable(Type); MethodInfo tryGetValueMethodInfo = storageType.GetMethod("TryGetValue"); if (tryGetValueMethodInfo == null) throw new LinqToDBException("Storage property do not have method 'TryGetValue'"); GetterExpression = Expression.Lambda( Expression.Block( new[] { outVar, resultVar }, Expression.IfThenElse( Expression.Call( Expression.MakeMemberAccess(objParam, TypeAccessor.DynamicColumnsStoreAccessor.MemberInfo), tryGetValueMethodInfo, Expression.Constant(memberInfo.Name), outVar), Expression.Assign(resultVar, Expression.Convert(outVar, Type)), Expression.Assign(resultVar, new DefaultValueExpression(MappingSchema.Default, Type)) ), resultVar ), objParam); } else // dynamic columns store was not provided, throw exception when accessed GetterExpression = Expression.Lambda( Expression.Throw( Expression.New( ArgumentExceptionConstructorInfo, Expression.Constant("Tried getting dynamic column value, without setting dynamic column store on type."))), objParam); } else if (HasGetter) { GetterExpression = Expression.Lambda(Expression.MakeMemberAccess(objParam, memberInfo), objParam); } else { GetterExpression = Expression.Lambda(new DefaultValueExpression(MappingSchema.Default, Type), objParam); } if (HasSetter && memberInfo.IsDynamicColumnPropertyEx()) { IsComplex = true; if (TypeAccessor.DynamicColumnsStoreAccessor != null) // if null, create new dictionary; then assign value SetterExpression = Expression.Lambda( Expression.Block( Expression.IfThen( Expression.ReferenceEqual( Expression.MakeMemberAccess(objParam, TypeAccessor.DynamicColumnsStoreAccessor.MemberInfo), Expression.Constant(null)), Expression.Assign( Expression.MakeMemberAccess(objParam, TypeAccessor.DynamicColumnsStoreAccessor.MemberInfo), Expression.New(typeof(Dictionary<string, object>)))), Expression.Assign( Expression.Property( Expression.MakeMemberAccess(objParam, TypeAccessor.DynamicColumnsStoreAccessor.MemberInfo), "Item", Expression.Constant(memberInfo.Name)), Expression.Convert(valueParam, typeof(object)))), objParam, valueParam); else // dynamic columns store was not provided, throw exception when accessed GetterExpression = Expression.Lambda( Expression.Block( Expression.Throw( Expression.New( ArgumentExceptionConstructorInfo, Expression.Constant("Tried setting dynamic column value, without setting dynamic column store on type."))), Expression.Constant(DefaultValue.GetValue(valueParam.Type), valueParam.Type) ), objParam, valueParam); } else if (HasSetter) { SetterExpression = Expression.Lambda( Expression.Assign(Expression.MakeMemberAccess(objParam, memberInfo), valueParam), objParam, valueParam); } else { var fakeParam = Expression.Parameter(typeof(int)); SetterExpression = Expression.Lambda( Expression.Block( new[] { fakeParam }, new Expression[] { Expression.Assign(fakeParam, Expression.Constant(0)) }), objParam, valueParam); } } void SetExpressions() { var objParam = Expression.Parameter(typeof(object), "obj"); var getterExpr = GetterExpression.GetBody(Expression.Convert(objParam, TypeAccessor.Type)); var getter = Expression.Lambda<Func<object,object>>(Expression.Convert(getterExpr, typeof(object)), objParam); Getter = getter.Compile(); var valueParam = Expression.Parameter(typeof(object), "value"); if (SetterExpression != null) { var setterExpr = SetterExpression.GetBody( Expression.Convert(objParam, TypeAccessor.Type), Expression.Convert(valueParam, Type)); var setter = Expression.Lambda<Action<object, object>>(setterExpr, objParam, valueParam); Setter = setter.Compile(); } } #region Public Properties public MemberInfo MemberInfo { get; private set; } public TypeAccessor TypeAccessor { get; private set; } public bool HasGetter { get; private set; } public bool HasSetter { get; private set; } public Type Type { get; private set; } public bool IsComplex { get; private set; } public LambdaExpression GetterExpression { get; private set; } public LambdaExpression SetterExpression { get; private set; } public Func <object,object> Getter { get; private set; } public Action<object,object> Setter { get; private set; } public string Name { get { return MemberInfo.Name; } } #endregion #region Public Methods public T GetAttribute<T>() where T : Attribute { var attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0? (T)attrs[0]: null; } public T[] GetAttributes<T>() where T : Attribute { Array attrs = MemberInfo.GetCustomAttributesEx(typeof(T), true); return attrs.Length > 0? (T[])attrs: null; } public object[] GetAttributes() { var attrs = MemberInfo.GetCustomAttributesEx(true); return attrs.Length > 0? attrs: null; } public T[] GetTypeAttributes<T>() where T : Attribute { return TypeAccessor.Type.GetAttributes<T>(); } #endregion #region Set/Get Value public virtual object GetValue(object o) { return Getter(o); } public virtual void SetValue(object o, object value) { Setter(o, value); } #endregion } }
using Aspose.Email.Live.Demos.UI.FileProcessing; using Aspose.Email.Live.Demos.UI.LibraryHelpers; using Aspose.Email.Live.Demos.UI.Models; using Aspose.Email; using Aspose.Email.Mapi; using Aspose.Html; using Aspose.Imaging; using Aspose.Imaging.Brushes; using Aspose.Imaging.ImageOptions; using Aspose.Imaging.Sources; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web.Http; namespace Aspose.Email.Live.Demos.UI.Controllers { /// <summary> ///Implements the AsposeEmailWatermarkController Class to add or remove watermarks /// </summary> public class AsposeEmailWatermarkController : EmailBase { /// <summary> ///Init the AsposeEmailWatermarkController Class /// </summary> public AsposeEmailWatermarkController() { Aspose.Email.Live.Demos.UI.Models.License.SetAsposeEmailLicense(); } [MimeMultipart] [HttpPost] [AcceptVerbs("GET", "POST")] public async Task<Response> ProcessWatermark(string type, string textColor = null, string fontFamily = "Arial") { (string folderName, string[] fileNames) = (null, null); try { (folderName, fileNames) = await UploadFiles(); var text = ReadAndRemoveAsText(ref fileNames, folderName, "text"); byte[] image = null; if (type == "image") image = ReadAndRemoveAsBytes(ref fileNames, folderName, fileNames.Last()); var processor = new CustomSingleOrZipFileProcessor() { CustomFilesProcessMethod = (string[] inputFilePaths, string outputFolderPath) => { for (int i = 0; i < inputFilePaths.Length; i++) { var filePath = inputFilePaths[i]; var mail = MapiHelper.GetMapiMessageFromFile(filePath); if (mail == null) throw new Exception("Invalid file format"); switch (type) { case "text": AddTextWatermark(filePath, mail, outputFolderPath, text, fontFamily, textColor); break; case "image": AddImageWatermark(filePath, mail, outputFolderPath, image); break; case "remove": RemoveWatermark(filePath, mail, outputFolderPath); break; default: break; } } } }; return processor.Process(folderName, fileNames); } catch (Exception ex) { Console.WriteLine(ex.Message); return new Response() { Status = "200", Text = "Error on processing file" }; } } /// <summary> ///AddWatermarkToEmail method to add watermarks /// </summary> [HttpGet] [AcceptVerbs("GET", "POST")] public Task<Response> AddWatermarkToEmail(string fileName, string folderName, string watermarkText, string fontFamily, string outputType, string watermarkColor) { var processor = new CustomSingleOrZipFileProcessor() { CustomFileProcessMethod = (string inputFilePath, string outputFolderPath) => { var mail = MapiHelper.GetMapiMessageFromFile(inputFilePath); if (mail == null) throw new Exception("Invalid file format"); AddTextWatermark(inputFilePath, mail, outputFolderPath, watermarkText, fontFamily, watermarkColor); } }; return Task.FromResult(processor.Process(folderName, fileName)); } private void AddTextWatermark(string mailFilePath, MapiMessage mail, string outputFolderPath, string watermarkText, string fontFamily, string watermarkColor) { var html = mail.BodyHtml; //var imageBase64 = "";//Convert.ToBase64String(System.IO.File.ReadAllBytes(Path.Combine(AppSettings.WorkingDirectory, imageFoler, imageFile))); var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var options = new PngOptions(); options.Source = new StreamSource(new MemoryStream(), true); var width = watermarkText.Length * 17; var height = 120; using (Image image = Image.Create(options, width, height)) { // Create graphics object to perform draw operations. Graphics graphics = new Graphics(image); // Create font to draw watermark with. Font font = new Font(fontFamily, 20.0f); // Create a solid brush with color alpha set near to 0 to use watermarking effect. using (SolidBrush backgroundBrush = new SolidBrush(Color.White)) { using (SolidBrush brush = new SolidBrush(GetColor(watermarkColor))) { // Specify string alignment to put watermark at the image center. StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; graphics.FillRectangle(backgroundBrush, new Rectangle(0, 0, image.Width, image.Height)); // Draw watermark using font, partly-transparent brush and rotation matrix at the image center. graphics.DrawString(watermarkText, font, brush, new RectangleF(0, 0, image.Width, image.Height), sf); } } var ms = new MemoryStream(); image.Save(ms); mail.Attachments.Add("watermark", ms.ToArray()); } var attachment = mail.Attachments.Find(x => x.LongFileName == "watermark"); attachment.SetContentId("watermark"); var bodyHtml = htmlDocument.Body.InnerHTML; var watermarkHtml = $@"<table role=""presentation"" style=""width:100%; height:1200px; background-image:url(cid:watermark); background-repeat:repeat; table-layout: fixed;"" cellpadding=""0"" cellspacing=""0"" border=""0""> <tr> <td valign=""top"" style=""width:100%; height:1200px; background-size:cover; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important;""> <!--[if gte mso 9]> <v:rect xmlns:v=""urn:schemas-microsoft-com:vml"" fill=""true"" filltype=""tile"" stroke=""false"" style=""height:1200px; width:640px; border: 0;display: inline-block;position: absolute; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important; mso-position-vertical-relative:text;""> <v:fill type=""tile"" opacity=""100%"" src=""cid:watermark"" /> <v:textbox inset=""0,0,0,0""> <![endif]--> <div> {bodyHtml} </div> <!--[if gte mso 9]>\ </v:textbox> </v:fill> </v:rect> <![endif]--> </td> </tr> </table>"; htmlDocument.Body.InnerHTML = watermarkHtml; var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); Directory.Delete(folderPath, true); mail.SetBodyContent(content, BodyContentType.Html); if (mailFilePath.EndsWith("MSG", StringComparison.OrdinalIgnoreCase)) mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(mailFilePath) + " Marked.msg"), SaveOptions.DefaultMsgUnicode); else mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(mailFilePath) + " Marked.eml"), SaveOptions.DefaultEml); } ///<Summary> /// ImageWatermark method to add image watermark ///</Summary> [HttpGet] [AcceptVerbs("GET", "POST")] public Task<Response> ImageWatermark(string fileName, string folderName, string imageFileName, string imageFolderName, string outputType, bool grayScale = false) { var processor = new CustomSingleOrZipFileProcessor() { CustomFileProcessMethod = (string inputFilePath, string outputFolderPath) => { var mail = MapiHelper.GetMapiMessageFromFile(inputFilePath); if (mail == null) throw new Exception("Invalid file format"); var path = Path.Combine(Config.Configuration.WorkingDirectory, imageFolderName, imageFileName); if (grayScale) { var ms = new MemoryStream(); using (var image = Image.Load(path)) { var saveOptions = new Aspose.Imaging.ImageOptions.PsdOptions(); saveOptions.ColorMode = Imaging.FileFormats.Psd.ColorModes.Grayscale; saveOptions.CompressionMethod = Imaging.FileFormats.Psd.CompressionMethod.Raw; image.Save(ms, saveOptions); } ms.Position = 0; using (var newImage = Image.Load(ms)) { ms = new MemoryStream(); newImage.Save(ms, new PngOptions()); } AddImageWatermark(inputFilePath, mail, outputFolderPath, ms.ToArray()); } else AddImageWatermark(inputFilePath, mail, outputFolderPath, System.IO.File.ReadAllBytes(path)); } }; return Task.FromResult(processor.Process(folderName, fileName)); } private void AddImageWatermark(string inputFilePath, MapiMessage mail, string outputFolderPath, byte[] imageBytes) { Aspose.Email.Live.Demos.UI.Models.License.SetAsposeEmailLicense(); Aspose.Email.Live.Demos.UI.Models.License.SetAsposeImagingLicense(); mail.Attachments.Add("watermark", imageBytes); var html = mail.BodyHtml; var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var attachment = mail.Attachments.Find(x => x.LongFileName == "watermark"); attachment.SetContentId("watermark"); var bodyHtml = htmlDocument.Body.InnerHTML; var watermarkHtml = $@"<table role=""presentation"" style=""width:100%; height:1200px; background-image:url(cid:watermark); background-repeat:repeat; table-layout: fixed;"" cellpadding=""0"" cellspacing=""0"" border=""0""> <tr> <td valign=""top"" style=""width:100%; height:1200px; background-size:cover; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important;""> <!--[if gte mso 9]> <v:rect xmlns:v=""urn:schemas-microsoft-com:vml"" fill=""true"" filltype=""tile"" stroke=""false"" style=""height:1200px; width:640px; border: 0;display: inline-block;position: absolute; background-image:url(cid:watermark); background-repeat:repeat; word-break: normal; border-collapse : collapse !important; mso-position-vertical-relative:text;""> <v:fill type=""tile"" opacity=""100%"" src=""cid:watermark"" /> <v:textbox inset=""0,0,0,0""> <![endif]--> <div> {bodyHtml} </div> <!--[if gte mso 9]>\ </v:textbox> </v:fill> </v:rect> <![endif]--> </td> </tr> </table>"; htmlDocument.Body.InnerHTML = watermarkHtml; var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); Directory.Delete(folderPath, true); mail.SetBodyContent(content, BodyContentType.Html); if (inputFilePath.Equals("MSG", StringComparison.OrdinalIgnoreCase)) mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Marked.msg"), SaveOptions.DefaultMsgUnicode); else mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Marked.eml"), SaveOptions.DefaultEml); } ///<Summary> /// RemoveWatermark method to remove watermark ///</Summary> [HttpGet] [AcceptVerbs("GET", "POST")] public Task<Response> RemoveWatermark(string fileName, string folderName, string userEmail) { var processor = new CustomSingleOrZipFileProcessor() { CustomFileProcessMethod = (string inputFilePath, string outputFolderPath) => { var mail = MapiHelper.GetMapiMessageFromFile(inputFilePath); if (mail == null) throw new Exception("Invalid file format"); RemoveWatermark(inputFilePath, mail, outputFolderPath); } }; return Task.FromResult(processor.Process(folderName, fileName)); } private void RemoveWatermark(string inputFilePath, MapiMessage mail, string outputFolderPath) { var formatInfo = Email.Tools.FileFormatUtil.DetectFileFormat(inputFilePath); var html = mail.BodyHtml; var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var attachment = mail.Attachments.Find(x => x.LongFileName.Equals("watermark", StringComparison.OrdinalIgnoreCase)); if (attachment != null) mail.Attachments.Remove(attachment); // Remove body backgrounds htmlDocument.Body.RemoveAttribute("background"); htmlDocument.Body.Style.Background = string.Empty; htmlDocument.Body.Style.BackgroundImage = string.Empty; HTMLElement element = htmlDocument.Body; // Remove background from all single elements. do { element = (HTMLElement)element.Children[0]; // Process only default tags for watermark if (element.NodeName != "TABLE" && element.NodeName != "TR" && element.NodeName != "TD" && element.NodeName != "TBODY") { // If reached div, content starting here if (element.NodeName == "DIV") htmlDocument.Body.InnerHTML = element.InnerHTML; break; } // Remove comments for (int i = 0; i < element.ChildNodes.Length; i++) { var node = element.ChildNodes[i]; if (node.NodeType == Html.Dom.Node.COMMENT_NODE && node.NodeValue != null && node.NodeValue.StartsWith("[if gte mso 9]", StringComparison.OrdinalIgnoreCase)) { element.RemoveChild(node); i--; } } element.Style.Background = string.Empty; element.Style.BackgroundImage = string.Empty; } while (element.ChildElementCount == 1); var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); Directory.Delete(folderPath, true); mail.SetBodyContent(content, BodyContentType.Html); if (formatInfo.FileFormatType == FileFormatType.Msg) mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Unmarked.msg"), SaveOptions.DefaultMsgUnicode); else mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Unmarked.eml"), SaveOptions.DefaultEml); } private Color GetColor(string watermarkColor) { Color color; if (watermarkColor != "") { if (!watermarkColor.StartsWith("#")) { watermarkColor = "#" + watermarkColor; } System.Drawing.Color sColor = System.Drawing.ColorTranslator.FromHtml(watermarkColor); color = Color.FromArgb(sColor.A, sColor.R, sColor.G, sColor.B); } else { color = Color.FromArgb(50, 128, 128, 128); } return color; } private static ImageOptionsBase GetSaveFormat(string outputType) { switch (outputType) { case "bmp": return new Aspose.Imaging.ImageOptions.BmpOptions(); case "gif": return new Aspose.Imaging.ImageOptions.GifOptions(); case "jpeg": return new Aspose.Imaging.ImageOptions.JpegOptions(); case "pdf": return new Aspose.Imaging.ImageOptions.PdfOptions(); case "png": return new Aspose.Imaging.ImageOptions.PngOptions(); case "psd": return new Aspose.Imaging.ImageOptions.PsdOptions(); case "tiff": return new Aspose.Imaging.ImageOptions.TiffOptions(Imaging.FileFormats.Tiff.Enums.TiffExpectedFormat.Default); case "emf": return new Aspose.Imaging.ImageOptions.EmfRasterizationOptions(); } return null; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DotNETJumpStart.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using UnityEngine; using UnityEngine.UI; public class TutorialActions { #region SkipCurrentStep // DO: Skip the current step and try to goto the next step. // PARAMS: No parameters. // REMARKS: The tutorial will still have to wait until all next step conditions are passed. public static void SkipCurrentStep() { TutorialManager.instance.SkipCurrentStep(); } #endregion #region SkipToStep // DO: Skip the tutorial directly to specified step. // PARAMS: [0] - step id. public static void SkipToStep(string[] parameters) { if (parameters.Length != 1) return; TutorialManager.instance.SkipToStep(Int32.Parse(parameters[0])); } #endregion #region SaveAsCheckpoint // DO: Save the current tutorial and step as the checkpoint. // PARAMS: No parameters. public static void SaveAsCheckpoint() { TutorialManager.instance.SaveCurrentProgress(); } #endregion #region SaveCheckpoint // DO: Save the specified tutorial and step as the checkpoint. // PARAMS: [0] - tutorial id, [1] - step id. public static void SaveCheckpoint(string[] parameters) { if (parameters.Length != 2) return; TutorialProgressRecorder.UpdateInProgressTutorial(Convert.ToInt32(parameters[0]), Convert.ToInt32(parameters[1])); } #endregion #region SetActive // DO: Set the GameObject of the specified path to active/inactive. // PARAMS: [0] - the hierarchy path of the GameObject, [1] - true/false. public static void SetActive(string[] parameters) { if (parameters.Length != 2) return; GameObject obj = GameObject.Find(parameters[0]); if(obj != null) { obj.SetActive(bool.Parse(parameters[1])); } } #endregion #region SetLocalPosition // DO: Set the local position of GameObject of the specified path. // PARAMS: [0] - the hierarchy path of the GameObject, [1] - x, [2] - y, [3] - z. public static void SetLocalPosition(string[] parameters) { if (parameters.Length != 4) return; GameObject obj = GameObject.Find(parameters[0]); if (obj != null) { obj.transform.localPosition = new Vector3 ( Single.Parse(parameters[1]), Single.Parse(parameters[2]), Single.Parse(parameters[3]) ); } } #endregion #region SetPosition // DO: Set the world position of GameObject of the specified path. // PARAMS: [0] - the hierarchy path of the GameObject, [1] - x, [2] - y, [3] - z. public static void SetPosition(string[] parameters) { if (parameters.Length != 4) return; GameObject obj = GameObject.Find(parameters[0]); if (obj != null) { obj.transform.position = new Vector3 ( Single.Parse(parameters[1]), Single.Parse(parameters[2]), Single.Parse(parameters[3]) ); } } #endregion #region SetValue // DO: Set the value of specified field/property in specified component of the specified GameObject. // PARAMS: [0] - the hierarchy path of the GameObject, [1] - component name, [2] - field/property name, [3] - value. public static void SetValue(string[] parameters) { if (parameters.Length < 4) return; GameObject gameObj = GameObject.Find(parameters[0]); if (gameObj != null) { Component c = gameObj.GetComponent(parameters[1]); if (c == null) { Debug.LogError("Failed to find component " + parameters[1] + " in " + parameters[0] + "."); return; } string[] fieldSections = parameters[2].Split('.'); object obj = c; for (int i = 0; i < fieldSections.Length; ++i) { string fieldSection = fieldSections[i]; if(i == fieldSections.Length - 1) { if (obj != null) { } } else { FieldInfo fi = obj.GetType().GetField(fieldSection, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (fi != null) { obj = fi.GetValue(obj); } else { PropertyInfo pi = obj.GetType().GetProperty(parameters[2], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (pi != null) { obj = pi.GetGetMethod().Invoke(obj, new object[] { Convert.ChangeType(parameters[3], pi.DeclaringType) }); } else { Debug.LogError("Failed to find " + fieldSection + "."); return; } } } } } else { Debug.LogError("Failed to find GameObject " + parameters[0] + "."); } } #endregion #region ShowMask // DO: Show the semi-transparent black mask. // PARAMS: No parameters. public static void ShowMask() { TutorialManager.instance.ShowMask(); } #endregion #region HideMask // DO: Hide the semi-transparent black mask. // PARAMS: No parameters. public static void HideMask() { TutorialManager.instance.HideMask(); } #endregion #region SetupMask // DO: Setup the tutorial mask. // PARAMS: [0] - x, [1] - y, [2] - width, [3] - height, [4] - alpha (optional). public static void SetupMask(string[] parameters) { if(parameters.Length == 4) { TutorialManager.instance.SetupMask ( Convert.ToSingle(parameters[0]), Convert.ToSingle(parameters[1]), Convert.ToSingle(parameters[2]), Convert.ToSingle(parameters[3]) ); } else if (parameters.Length == 5) { TutorialManager.instance.SetupMask ( Convert.ToSingle(parameters[0]), Convert.ToSingle(parameters[1]), Convert.ToSingle(parameters[2]), Convert.ToSingle(parameters[3]), Convert.ToSingle(parameters[4]) ); } } #endregion #region SetForeground // DO: Setup the foreground sprite. // PARAMS: [0] - Sprite path, [1] - x, [2] - y, [3] - width, [4] - height. public static void SetForeground(string[] parameters) { if (parameters.Length != 5) return; string sprite = parameters[0]; Vector4 rect = new Vector4 ( Convert.ToSingle(parameters[1]), Convert.ToSingle(parameters[2]), Convert.ToSingle(parameters[3]), Convert.ToSingle(parameters[4]) ); TutorialManager.instance.SetForeground(sprite); TutorialManager.instance.SetForegroundRect(rect); } #endregion #region SetContent // DO: Setup the content. // PARAMS: [0] - LocID of the content, [1] - x, [2] - y, [3] - width, [4] - height. // REMARKS: If the LocID doesn't exist, the content of the LocID string will be displayed directly. public static void SetContent(string[] parameters) { if (parameters.Length != 5) return; string content = LocalizationManager.Get(parameters[0]); Vector4 rect = new Vector4 ( Convert.ToSingle(parameters[1]), Convert.ToSingle(parameters[2]), Convert.ToSingle(parameters[3]), Convert.ToSingle(parameters[4]) ); TutorialManager.instance.SetContent(content); TutorialManager.instance.SetContentRect(rect); } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class MultipleResponsesExtensions { /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model204NoModelDefaultError200Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model204NoModelDefaultError200ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model204NoModelDefaultError200ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model204NoModelDefaultError200ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model204NoModelDefaultError204Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model204NoModelDefaultError204ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model204NoModelDefaultError204ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model204NoModelDefaultError204ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model204NoModelDefaultError201Invalid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model204NoModelDefaultError201InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model204NoModelDefaultError201InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model204NoModelDefaultError201InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 202 response with no payload: /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model204NoModelDefaultError202None(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model204NoModelDefaultError202NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 202 response with no payload: /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model204NoModelDefaultError202NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model204NoModelDefaultError202NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with valid error payload: {'status': 400, 'message': /// 'client error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model204NoModelDefaultError400Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model204NoModelDefaultError400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid error payload: {'status': 400, 'message': /// 'client error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model204NoModelDefaultError400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model204NoModelDefaultError400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model201ModelDefaultError200Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model201ModelDefaultError200ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model201ModelDefaultError200ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model201ModelDefaultError200ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201', /// 'textStatusCode': 'Created'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model201ModelDefaultError201Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model201ModelDefaultError201ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 201 response with valid payload: {'statusCode': '201', /// 'textStatusCode': 'Created'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model201ModelDefaultError201ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model201ModelDefaultError201ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200Model201ModelDefaultError400Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200Model201ModelDefaultError400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200Model201ModelDefaultError400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200Model201ModelDefaultError400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static object Get200ModelA201ModelC404ModelDDefaultError200Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA201ModelC404ModelDDefaultError200ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> Get200ModelA201ModelC404ModelDDefaultError200ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA201ModelC404ModelDDefaultError200ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with valid payload: {'httpCode': '201'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static object Get200ModelA201ModelC404ModelDDefaultError201Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA201ModelC404ModelDDefaultError201ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'httpCode': '201'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> Get200ModelA201ModelC404ModelDDefaultError201ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA201ModelC404ModelDDefaultError201ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with valid payload: {'httpStatusCode': '404'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static object Get200ModelA201ModelC404ModelDDefaultError404Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA201ModelC404ModelDDefaultError404ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'httpStatusCode': '404'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> Get200ModelA201ModelC404ModelDDefaultError404ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA201ModelC404ModelDDefaultError404ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static object Get200ModelA201ModelC404ModelDDefaultError400Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA201ModelC404ModelDDefaultError400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> Get200ModelA201ModelC404ModelDDefaultError400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA201ModelC404ModelDDefaultError400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 202 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultError202None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultError202NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 202 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultError202NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultError202NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultError204None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultError204NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultError204NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultError204NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultError400Valid(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultError400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid payload: {'code': '400', 'message': 'client /// error'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultError400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultError400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 202 response with an unexpected payload {'property': 'value'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultNone202Invalid(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultNone202InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 202 response with an unexpected payload {'property': 'value'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultNone202InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultNone202InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultNone204None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultNone204NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 204 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultNone204NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultNone204NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultNone400None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultNone400NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultNone400NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultNone400NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 400 response with an unexpected payload {'property': 'value'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void Get202None204NoneDefaultNone400Invalid(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).Get202None204NoneDefaultNone400InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with an unexpected payload {'property': 'value'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task Get202None204NoneDefaultNone400InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get202None204NoneDefaultNone400InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A GetDefaultModelA200Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultModelA200ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with valid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> GetDefaultModelA200ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDefaultModelA200ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A GetDefaultModelA200None(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultModelA200NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> GetDefaultModelA200NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDefaultModelA200NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A GetDefaultModelA400Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultModelA400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> GetDefaultModelA400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDefaultModelA400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A GetDefaultModelA400None(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultModelA400NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> GetDefaultModelA400NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDefaultModelA400NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with invalid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void GetDefaultNone200Invalid(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultNone200InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with invalid payload: {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetDefaultNone200InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetDefaultNone200InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void GetDefaultNone200None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultNone200NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetDefaultNone200NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetDefaultNone200NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void GetDefaultNone400Invalid(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultNone400InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with valid payload: {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetDefaultNone400InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetDefaultNone400InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static void GetDefaultNone400None(this IMultipleResponses operations) { Task.Factory.StartNew(s => ((IMultipleResponses)s).GetDefaultNone400NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with no payload /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetDefaultNone400NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetDefaultNone400NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Send a 200 response with no payload, when a payload is expected - client /// should return a null object of thde type for model A /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA200None(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA200NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with no payload, when a payload is expected - client /// should return a null object of thde type for model A /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA200NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA200NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with payload {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA200Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA200ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with payload {'statusCode': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA200ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA200ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA200Invalid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA200InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': '200'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA200InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA200InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 400 response with no payload client should treat as an http error /// with no error model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA400None(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA400NoneAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 400 response with no payload client should treat as an http error /// with no error model /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA400NoneAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA400NoneWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with payload {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA400Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA400ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with payload {'statusCode': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA400ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA400ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA400Invalid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA400InvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 200 response with invalid payload {'statusCodeInvalid': '400'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA400InvalidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA400InvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Send a 202 response with payload {'statusCode': '202'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static A Get200ModelA202Valid(this IMultipleResponses operations) { return Task.Factory.StartNew(s => ((IMultipleResponses)s).Get200ModelA202ValidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Send a 202 response with payload {'statusCode': '202'} /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<A> Get200ModelA202ValidAsync( this IMultipleResponses operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.Get200ModelA202ValidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Notify.V1; namespace Twilio.Tests.Rest.Notify.V1 { [TestFixture] public class CredentialTest : TwilioTest { [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Notify, "/v1/Credentials", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { CredentialResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"credentials\": [{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://notify.twilio.com/v1/Credentials?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://notify.twilio.com/v1/Credentials?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"credentials\"}}" )); var response = CredentialResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"credentials\": [],\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://notify.twilio.com/v1/Credentials?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://notify.twilio.com/v1/Credentials?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"credentials\"}}" )); var response = CredentialResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestCreateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Notify, "/v1/Credentials", "" ); request.AddPostParam("Type", Serialize(CredentialResource.PushServiceEnum.Gcm)); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { CredentialResource.Create(CredentialResource.PushServiceEnum.Gcm, client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestCreateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.Created, "{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = CredentialResource.Create(CredentialResource.PushServiceEnum.Gcm, client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestFetchRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Notify, "/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { CredentialResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestFetchResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = CredentialResource.Fetch("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestUpdateRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Post, Twilio.Rest.Domain.Notify, "/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { CredentialResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestUpdateResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"sid\": \"CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"Test slow create\",\"type\": \"apn\",\"sandbox\": \"False\",\"date_created\": \"2015-10-07T17:50:01Z\",\"date_updated\": \"2015-10-07T17:50:01Z\",\"url\": \"https://notify.twilio.com/v1/Credentials/CRaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}" )); var response = CredentialResource.Update("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestDeleteRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Delete, Twilio.Rest.Domain.Notify, "/v1/Credentials/CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "" ); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { CredentialResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestDeleteResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.NoContent, "null" )); var response = CredentialResource.Delete("CRXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", client: twilioRestClient); Assert.NotNull(response); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Xml; using System.Security; namespace System.Runtime.Serialization { #if NET_NATIVE public abstract class PrimitiveDataContract : DataContract #else internal abstract class PrimitiveDataContract : DataContract #endif { internal static readonly PrimitiveDataContract NullContract = new NullPrimitiveDataContract(); [SecurityCritical] /// <SecurityNote> /// Critical - holds instance of CriticalHelper which keeps state that is cached statically for serialization. /// Static fields are marked SecurityCritical or readonly to prevent /// data from being modified or leaked to other components in appdomain. /// </SecurityNote> private PrimitiveDataContractCriticalHelper _helper; /// <SecurityNote> /// Critical - initializes SecurityCritical field 'helper' /// Safe - doesn't leak anything /// </SecurityNote> [SecuritySafeCritical] protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns)) { _helper = base.Helper as PrimitiveDataContractCriticalHelper; } static internal PrimitiveDataContract GetPrimitiveDataContract(Type type) { return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract; } static internal PrimitiveDataContract GetPrimitiveDataContract(string name, string ns) { return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract; } internal abstract string WriteMethodName { get; } internal abstract string ReadMethodName { get; } public override XmlDictionaryString TopLevelElementNamespace { /// <SecurityNote> /// Critical - for consistency with base class /// Safe - for consistency with base class /// </SecurityNote> [SecuritySafeCritical] get { return DictionaryGlobals.SerializationNamespace; } /// <SecurityNote> /// Critical - for consistency with base class /// </SecurityNote> [SecurityCritical] set { } } internal override bool CanContainReferences { get { return false; } } internal override bool IsPrimitive { get { return true; } } public override bool IsBuiltInDataContract { get { return true; } } internal MethodInfo XmlFormatWriterMethod { /// <SecurityNote> /// Critical - fetches the critical XmlFormatWriterMethod property /// Safe - XmlFormatWriterMethod only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.XmlFormatWriterMethod == null) { if (UnderlyingType.GetTypeInfo().IsValueType) _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); else _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); } return _helper.XmlFormatWriterMethod; } } internal MethodInfo XmlFormatContentWriterMethod { /// <SecurityNote> /// Critical - fetches the critical XmlFormatContentWriterMethod property /// Safe - XmlFormatContentWriterMethod only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.XmlFormatContentWriterMethod == null) { if (UnderlyingType.GetTypeInfo().IsValueType) _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType }); else _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType }); } return _helper.XmlFormatContentWriterMethod; } } internal MethodInfo XmlFormatReaderMethod { /// <SecurityNote> /// Critical - fetches the critical XmlFormatReaderMethod property /// Safe - XmlFormatReaderMethod only needs to be protected for write; initialized in getter if null /// </SecurityNote> [SecuritySafeCritical] get { if (_helper.XmlFormatReaderMethod == null) { _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers); } return _helper.XmlFormatReaderMethod; } } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { xmlWriter.WriteAnyType(obj); } protected object HandleReadValue(object obj, XmlObjectSerializerReadContext context) { context.AddNewObject(obj); return obj; } protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader) { Attributes attributes = new Attributes(); attributes.Read(reader); if (attributes.Ref != Globals.NewObjectId) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotDeserializeRefAtTopLevel, attributes.Ref))); if (attributes.XsiNil) { reader.Skip(); return true; } return false; } [SecurityCritical] /// <SecurityNote> /// Critical - holds all state used for (de)serializing primitives. /// since the data is cached statically, we lock down access to it. /// </SecurityNote> private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private MethodInfo _xmlFormatWriterMethod; private MethodInfo _xmlFormatContentWriterMethod; private MethodInfo _xmlFormatReaderMethod; internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type) { SetDataContractName(name, ns); } internal MethodInfo XmlFormatWriterMethod { get { return _xmlFormatWriterMethod; } set { _xmlFormatWriterMethod = value; } } internal MethodInfo XmlFormatContentWriterMethod { get { return _xmlFormatContentWriterMethod; } set { _xmlFormatContentWriterMethod = value; } } internal MethodInfo XmlFormatReaderMethod { get { return _xmlFormatReaderMethod; } set { _xmlFormatReaderMethod = value; } } } } #if NET_NATIVE public class CharDataContract : PrimitiveDataContract #else internal class CharDataContract : PrimitiveDataContract #endif { public CharDataContract() : this(DictionaryGlobals.CharLocalName, DictionaryGlobals.SerializationNamespace) { } internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(char), name, ns) { } internal override string WriteMethodName { get { return "WriteChar"; } } internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteChar((char)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsChar() : HandleReadValue(reader.ReadElementContentAsChar(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteChar((char)obj, name, ns); } } #if NET_NATIVE public class BooleanDataContract : PrimitiveDataContract #else internal class BooleanDataContract : PrimitiveDataContract #endif { public BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteBoolean"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBoolean((bool)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsBoolean() : HandleReadValue(reader.ReadElementContentAsBoolean(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteBoolean((bool)obj, name, ns); } } #if NET_NATIVE public class SignedByteDataContract : PrimitiveDataContract #else internal class SignedByteDataContract : PrimitiveDataContract #endif { public SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteSignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteSignedByte((sbyte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsSignedByte() : HandleReadValue(reader.ReadElementContentAsSignedByte(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteSignedByte((sbyte)obj, name, ns); } } #if NET_NATIVE public class UnsignedByteDataContract : PrimitiveDataContract #else internal class UnsignedByteDataContract : PrimitiveDataContract #endif { public UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.UnsignedByteLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedByte((byte)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedByte() : HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedByte((byte)obj, name, ns); } } #if NET_NATIVE public class ShortDataContract : PrimitiveDataContract #else internal class ShortDataContract : PrimitiveDataContract #endif { public ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteShort((short)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsShort() : HandleReadValue(reader.ReadElementContentAsShort(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteShort((short)obj, name, ns); } } #if NET_NATIVE public class UnsignedShortDataContract : PrimitiveDataContract #else internal class UnsignedShortDataContract : PrimitiveDataContract #endif { public UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.UnsignedShortLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedShort((ushort)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedShort() : HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedShort((ushort)obj, name, ns); } } internal class NullPrimitiveDataContract : PrimitiveDataContract { public NullPrimitiveDataContract() : base(typeof(NullPrimitiveDataContract), DictionaryGlobals.EmptyString, DictionaryGlobals.EmptyString) { } internal override string ReadMethodName { get { throw new NotImplementedException(); } } internal override string WriteMethodName { get { throw new NotImplementedException(); } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { throw new NotImplementedException(); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { throw new NotImplementedException(); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { throw new NotImplementedException(); } } #if NET_NATIVE public class IntDataContract : PrimitiveDataContract #else internal class IntDataContract : PrimitiveDataContract #endif { public IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteInt((int)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsInt() : HandleReadValue(reader.ReadElementContentAsInt(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteInt((int)obj, name, ns); } } #if NET_NATIVE public class UnsignedIntDataContract : PrimitiveDataContract #else internal class UnsignedIntDataContract : PrimitiveDataContract #endif { public UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.UnsignedIntLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedInt((uint)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedInt() : HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedInt((uint)obj, name, ns); } } #if NET_NATIVE public class LongDataContract : PrimitiveDataContract #else internal class LongDataContract : PrimitiveDataContract #endif { public LongDataContract() : this(DictionaryGlobals.LongLocalName, DictionaryGlobals.SchemaNamespace) { } internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(long), name, ns) { } internal override string WriteMethodName { get { return "WriteLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteLong((long)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsLong() : HandleReadValue(reader.ReadElementContentAsLong(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteLong((long)obj, name, ns); } } #if NET_NATIVE public class UnsignedLongDataContract : PrimitiveDataContract #else internal class UnsignedLongDataContract : PrimitiveDataContract #endif { public UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.UnsignedLongLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUnsignedLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUnsignedLong((ulong)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsUnsignedLong() : HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteUnsignedLong((ulong)obj, name, ns); } } #if NET_NATIVE public class FloatDataContract : PrimitiveDataContract #else internal class FloatDataContract : PrimitiveDataContract #endif { public FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteFloat"; } } internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteFloat((float)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsFloat() : HandleReadValue(reader.ReadElementContentAsFloat(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteFloat((float)obj, name, ns); } } #if NET_NATIVE public class DoubleDataContract : PrimitiveDataContract #else internal class DoubleDataContract : PrimitiveDataContract #endif { public DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDouble"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDouble((double)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDouble() : HandleReadValue(reader.ReadElementContentAsDouble(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDouble((double)obj, name, ns); } } #if NET_NATIVE public class DecimalDataContract : PrimitiveDataContract #else internal class DecimalDataContract : PrimitiveDataContract #endif { public DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDecimal"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDecimal((decimal)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDecimal() : HandleReadValue(reader.ReadElementContentAsDecimal(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDecimal((decimal)obj, name, ns); } } #if NET_NATIVE public class DateTimeDataContract : PrimitiveDataContract #else internal class DateTimeDataContract : PrimitiveDataContract #endif { public DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTimeLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteDateTime"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteDateTime((DateTime)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsDateTime() : HandleReadValue(reader.ReadElementContentAsDateTime(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteDateTime((DateTime)obj, name, ns); } } #if NET_NATIVE public class StringDataContract : PrimitiveDataContract #else internal class StringDataContract : PrimitiveDataContract #endif { public StringDataContract() : this(DictionaryGlobals.StringLocalName, DictionaryGlobals.SchemaNamespace) { } internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(string), name, ns) { } internal override string WriteMethodName { get { return "WriteString"; } } internal override string ReadMethodName { get { return "ReadElementContentAsString"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteString((string)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsString(); } else { return HandleReadValue(reader.ReadElementContentAsString(), context); } } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { context.WriteString(xmlWriter, (string)obj, name, ns); } } internal class HexBinaryDataContract : StringDataContract { internal HexBinaryDataContract() : base(DictionaryGlobals.hexBinaryLocalName, DictionaryGlobals.SchemaNamespace) { } } #if NET_NATIVE public class ByteArrayDataContract : PrimitiveDataContract #else internal class ByteArrayDataContract : PrimitiveDataContract #endif { public ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArrayLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteBase64"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteBase64((byte[])obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsBase64(); } else { return HandleReadValue(reader.ReadElementContentAsBase64(), context); } } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteStartElement(name, ns); xmlWriter.WriteBase64((byte[])obj); xmlWriter.WriteEndElement(); } } #if NET_NATIVE public class ObjectDataContract : PrimitiveDataContract #else internal class ObjectDataContract : PrimitiveDataContract #endif { public ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteAnyType"; } } internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { // write nothing } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { object obj; if (reader.IsEmptyElement) { reader.Skip(); obj = new object(); } else { string localName = reader.LocalName; string ns = reader.NamespaceURI; reader.Read(); try { reader.ReadEndElement(); obj = new object(); } catch (XmlException xes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlForObjectCannotHaveContent, localName, ns), xes)); } } return (context == null) ? obj : HandleReadValue(obj, context); } internal override bool CanContainReferences { get { return true; } } internal override bool IsPrimitive { get { return false; } } } #if NET_NATIVE public class TimeSpanDataContract : PrimitiveDataContract #else internal class TimeSpanDataContract : PrimitiveDataContract #endif { public TimeSpanDataContract() : this(DictionaryGlobals.TimeSpanLocalName, DictionaryGlobals.SerializationNamespace) { } internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(TimeSpan), name, ns) { } internal override string WriteMethodName { get { return "WriteTimeSpan"; } } internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteTimeSpan((TimeSpan)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsTimeSpan() : HandleReadValue(reader.ReadElementContentAsTimeSpan(), context); } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { writer.WriteTimeSpan((TimeSpan)obj, name, ns); } } #if NET_NATIVE public class GuidDataContract : PrimitiveDataContract #else internal class GuidDataContract : PrimitiveDataContract #endif { public GuidDataContract() : this(DictionaryGlobals.GuidLocalName, DictionaryGlobals.SerializationNamespace) { } internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : base(typeof(Guid), name, ns) { } internal override string WriteMethodName { get { return "WriteGuid"; } } internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteGuid((Guid)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { return (context == null) ? reader.ReadElementContentAsGuid() : HandleReadValue(reader.ReadElementContentAsGuid(), context); } public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { xmlWriter.WriteGuid((Guid)obj, name, ns); } } #if NET_NATIVE public class UriDataContract : PrimitiveDataContract #else internal class UriDataContract : PrimitiveDataContract #endif { public UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteUri"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteUri((Uri)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsUri(); } else { return HandleReadValue(reader.ReadElementContentAsUri(), context); } } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { writer.WriteUri((Uri)obj, name, ns); } } #if NET_NATIVE public class QNameDataContract : PrimitiveDataContract #else internal class QNameDataContract : PrimitiveDataContract #endif { public QNameDataContract() : base(typeof(XmlQualifiedName), DictionaryGlobals.QNameLocalName, DictionaryGlobals.SchemaNamespace) { } internal override string WriteMethodName { get { return "WriteQName"; } } internal override string ReadMethodName { get { return "ReadElementContentAsQName"; } } internal override bool IsPrimitive { get { return false; } } public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) { writer.WriteQName((XmlQualifiedName)obj); } public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) { if (context == null) { return TryReadNullAtTopLevel(reader) ? null : reader.ReadElementContentAsQName(); } else { return HandleReadValue(reader.ReadElementContentAsQName(), context); } } public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) { context.WriteQName(writer, (XmlQualifiedName)obj, name, ns); } internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace)) writer.WriteStartElement(Globals.SerPrefix, name, ns); else if (ns != null && ns.Value != null && ns.Value.Length > 0) writer.WriteStartElement(Globals.ElementPrefix, name, ns); else writer.WriteStartElement(name, ns); } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web.UI.WebControls; using Adxstudio.Xrm.Data; using Adxstudio.Xrm.Partner; using Adxstudio.Xrm.Web.UI.WebControls; using Microsoft.Xrm.Client; using Microsoft.Xrm.Sdk; using Site.Pages; using System.Web; namespace Site.Areas.AccountManagement.Pages { public partial class ManageParentAccount : PortalPage { private DataTable _contacts; protected string SortDirection { get { return ViewState["SortDirection"] as string ?? "ASC"; } set { ViewState["SortDirection"] = value; } } protected string SortExpression { get { return ViewState["SortExpression"] as string ?? "Accepted"; } set { ViewState["SortExpression"] = value; } } protected void Page_Load(object sender, EventArgs e) { RedirectToLoginIfAnonymous(); var parentAccount = Contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? null : ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == Contact.GetAttributeValue<EntityReference>("parentcustomerid").Id); var accountAccessPermissions = parentAccount == null ? new List<Entity>() : ServiceContext.GetAccountAccessByContact(Contact).ToList(); var accountAccessPermissionsForParentAccount = parentAccount == null ? new List<Entity>() : accountAccessPermissions.Where(a => a.GetAttributeValue<EntityReference>("adx_accountid") != null && a.GetAttributeValue<EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference())).ToList(); var contactAccessPermissions = parentAccount == null ? new List<Entity>() : ServiceContext.GetContactAccessByContact(Contact).ToList(); var contactAccessPermissionsForParentAccount = parentAccount == null ? new List<Entity>() : contactAccessPermissions.Where(c => c.GetAttributeValue<EntityReference>("adx_accountid") != null && c.GetAttributeValue<EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference()) && c.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)Enums.ContactAccessScope.Account).ToList(); var canReadAccount = false; var canEditAccount = false; var canCreateContacts = false; var canReadContacts = false; if (parentAccount == null) { AccountInformation.Visible = false; ContactsList.Visible = false; NoParentAccountError.Visible = true; return; } if (!accountAccessPermissions.Any()) { AccountInformation.Visible = false; ContactsList.Visible = false; NoAccountAccessPermissionsRecordError.Visible = true; return; } if (!accountAccessPermissionsForParentAccount.Any()) { AccountInformation.Visible = false; ContactsList.Visible = false; NoAccountAccessPermissionsForParentAccountError.Visible = true; return; } foreach (var access in accountAccessPermissionsForParentAccount) { if (access.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false)) { canEditAccount = true; canReadAccount = true; } if (access.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false)) { canReadAccount = true; } } foreach (var access in contactAccessPermissionsForParentAccount) { if (access.GetAttributeValue<bool?>("adx_create").GetValueOrDefault(false)) { canCreateContacts = true; canReadContacts = true; } if (access.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false)) { canReadContacts = true; } } if (!contactAccessPermissions.Any()) { NoContactAccessPermissionsRecordMessage.Visible = true; } else { if (!contactAccessPermissionsForParentAccount.Any()) { NoContactAccessPermissionsForParentAccountMessage.Visible = true; } } if (!canReadAccount) { AccountInformation.Visible = false; ContactsList.Visible = false; return; } if (!canEditAccount) { AccountEditForm.Visible = false; AccountReadOnlyForm.Visible = true; AccountAccessWritePermissionDeniedMessage.Visible = true; } if (!canReadContacts) { AccountContactsList.Visible = false; if (contactAccessPermissions.Any() && contactAccessPermissionsForParentAccount.Any()) { ContactAccessPermissionsMessage.Visible = true; } } CreateContactButton.Visible = canCreateContacts; var formViewDataSource = new CrmDataSource { ID = "WebFormDataSource", CrmDataContextName = AccountEditFormView.ContextName }; var fetchXml = string.Format("<fetch mapping='logical'><entity name='{0}'><all-attributes /><filter type='and'><condition attribute = '{1}' operator='eq' value='{{{2}}}'/></filter></entity></fetch>", "account", "accountid", parentAccount.GetAttributeValue<Guid>("accountid")); formViewDataSource.FetchXml = fetchXml; AccountInformation.Controls.Add(formViewDataSource); AccountEditFormView.DataSourceID = "WebFormDataSource"; AccountReadOnlyFormView.DataSourceID = "WebFormDataSource"; var contacts = ServiceContext.GetContactsForContact(Contact) .Where(c => c.GetAttributeValue<EntityReference>("parentcustomerid") != null && c.GetAttributeValue<EntityReference>("parentcustomerid").Equals(parentAccount.ToEntityReference())); _contacts = EnumerableExtensions.CopyToDataTable(contacts.Select(c => new { contactid = c.GetAttributeValue<Guid>("contactid"), ID = c.GetAttributeValue<string>("fullname"), CompanyName = c.GetRelatedEntity(ServiceContext, new Relationship("contact_customer_accounts")) == null ? string.Empty : c.GetRelatedEntity(ServiceContext, new Relationship("contact_customer_accounts")).GetAttributeValue<string>("name"), City = c.GetAttributeValue<string>("address1_city"), State = c.GetAttributeValue<string>("address1_stateorprovince"), Phone = c.GetAttributeValue<string>("address1_telephone1"), Email = c.GetAttributeValue<string>("emailaddress1"), }).OrderBy(opp => opp.CompanyName)); _contacts.Columns["City"].ColumnName = "City"; _contacts.Columns["State"].ColumnName = "State"; _contacts.Columns["Phone"].ColumnName = "Phone"; _contacts.Columns["Email"].ColumnName = "E-mail Address"; AccountContactsList.DataKeyNames = new[] { "contactid" }; AccountContactsList.DataSource = _contacts; AccountContactsList.DataBind(); } protected void UpdateAccountButton_Click(object sender, EventArgs e) { if (!Page.IsValid) { return; } AccountEditFormView.UpdateItem(); } protected void OnItemUpdating(object sender, CrmEntityFormViewUpdatingEventArgs e) { } protected void OnItemUpdated(object sender, CrmEntityFormViewUpdatedEventArgs e) { UpdateSuccessMessage.Visible = true; } protected void AccountContactsList_Sorting(object sender, GridViewSortEventArgs e) { SortDirection = e.SortExpression == SortExpression ? (SortDirection == "ASC" ? "DESC" : "ASC") : "ASC"; SortExpression = e.SortExpression; _contacts.DefaultView.Sort = string.Format("{0} {1}", SortExpression, SortDirection); AccountContactsList.DataSource = _contacts; AccountContactsList.DataBind(); } protected void AccountContactsList_OnRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].Visible = false; } if (e.Row.RowType != DataControlRowType.DataRow) { return; } var dataKey = AccountContactsList.DataKeys[e.Row.RowIndex].Value; e.Row.Cells[1].Text = string.Format(@"<a href=""{0}"">{1}</a>", HttpUtility.HtmlEncode(ContactDetailsUrl(dataKey)), HttpUtility.HtmlEncode(e.Row.Cells[1].Text)); e.Row.Cells[1].Attributes.Add("style", "white-space: nowrap;"); } protected string ContactDetailsUrl(object id) { var url = GetUrlForRequiredSiteMarker("Edit Portal User"); url.QueryString.Set("ContactID", id.ToString()); return url.PathWithQueryString; } protected void CreateContactButton_Click(object sender, EventArgs args) { var url = GetUrlForRequiredSiteMarker("Create Portal Contact"); Response.Redirect(url.PathWithQueryString); } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using SchoolBusAPI.Models; using SchoolBusAPI.ViewModels; using Microsoft.AspNetCore.Http; using AutoMapper; using SchoolBusAPI.Authorization; using Microsoft.AspNetCore.Mvc.ApiExplorer; namespace SchoolBusAPI.Services { /// <summary> /// /// </summary> public interface IRoleService { /// <summary> /// /// </summary> /// <response code="200">OK</response> IActionResult GetRoles(bool includeExpired = false); /// <summary> /// /// </summary> /// <param name="id">id of Role to delete</param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> IActionResult DeleteRole(int id); /// <summary> /// /// </summary> /// <param name="id">id of Role to fetch</param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> IActionResult GetRole(int id); /// <summary> /// /// </summary> /// <remarks>Get all the permissions for a role</remarks> /// <param name="id">id of Role to fetch</param> /// <response code="200">OK</response> IActionResult GetRolePermissions(int id); /// <summary> /// /// </summary> /// <remarks>Updates the permissions for a role</remarks> /// <param name="id">id of Role to update</param> /// <param name="items"></param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> IActionResult UpdateRolePermissions(int id, PermissionViewModel[] items); /// <summary> /// /// </summary> /// <param name="id">id of Role to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> IActionResult UpdateRole(int id, RoleViewModel item); /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">Role created</response> IActionResult CreateRole(RoleViewModel item); } /// <summary> /// /// </summary> public class RoleService : ServiceBase, IRoleService { private readonly DbAppContext _context; /// <summary> /// Create a service and set the database context /// </summary> public RoleService(DbAppContext context, IHttpContextAccessor httpContextAccessor, IMapper mapper) : base(httpContextAccessor, context, mapper) { _context = context; } /// <summary> /// /// </summary> /// <remarks>Returns a collection of active roles</remarks> /// <response code="200">OK</response> public virtual IActionResult GetRoles(bool includeExpired = false) { var data = _context.Roles .AsNoTracking(); if (!includeExpired) { data = data.Where(r => !r.ExpiryDate.HasValue || r.ExpiryDate == DateTime.MinValue || r.ExpiryDate > DateTime.Now); } var roles = Mapper.Map<List<RoleViewModel>>(data); if (User.IsSystemAdmin()) return new ObjectResult(roles); var count = roles.Count() - 1; for (var i = count; i >= 0; i--) { var role = roles[i]; if (!CurrentUserHasAllThePermissions(role.Id)) //return only the roles that the user has access. { roles.Remove(role); continue; } } return new ObjectResult(roles); } /// <summary> /// /// </summary> /// <param name="id">id of Role to delete</param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> public virtual IActionResult DeleteRole(int id) { var role = _context.Roles.FirstOrDefault(x => x.Id == id); if (role == null) { // Not Found return new StatusCodeResult(404); } if (role.Name.ToUpperInvariant() == Roles.SystemAdmininstrator.ToUpperInvariant()) { return new UnprocessableEntityObjectResult(new Error("Validation Error", 201, $"Role [{role.Name}] cannot be created or updated.")); } role.ExpiryDate = DateTime.Today; _context.SaveChanges(); return new ObjectResult(Mapper.Map<RoleViewModel>(role)); } /// <summary> /// /// </summary> /// <param name="id">id of Role to fetch</param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> public virtual IActionResult GetRole(int id) { var role = _context.Roles.AsNoTracking().FirstOrDefault(x => x.Id == id); if (role == null) { // Not Found return new StatusCodeResult(404); } return new ObjectResult(Mapper.Map<RoleViewModel>(role)); } /// <summary> /// /// </summary> /// <remarks>Get all the permissions for a role</remarks> /// <param name="id">id of Role to fetch</param> /// <response code="200">OK</response> public virtual IActionResult GetRolePermissions(int id) { // Eager loading of related data var role = _context.Roles.AsNoTracking() .Include(x => x.RolePermissions) .ThenInclude(rp => rp.Permission) .FirstOrDefault(x => x.Id == id); if (role == null) { // Not Found return new StatusCodeResult(404); } var permissions = role .RolePermissions .Where(rp => !rp.ExpiryDate.HasValue || rp.ExpiryDate == DateTime.MinValue || rp.ExpiryDate > DateTime.Now) .Select(rp => rp.Permission) .Where(p => !p.ExpiryDate.HasValue || p.ExpiryDate == DateTime.MinValue || p.ExpiryDate > DateTime.Now); return new ObjectResult(Mapper.Map<List<PermissionViewModel>>(permissions)); } /// <summary> /// /// </summary> /// <remarks>Updates the permissions for a role</remarks> /// <param name="id">id of Role to update</param> /// <param name="items"></param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> public virtual IActionResult UpdateRolePermissions(int id, PermissionViewModel[] items) { // Eager loading of related data var role = _context.Roles .Where(x => x.Id == id) .Include(x => x.RolePermissions) .ThenInclude(rolePerm => rolePerm.Permission) .FirstOrDefault(); if (role == null) { // Not Found return new StatusCodeResult(404); } var allPermissions = _context.Permissions.ToList(); var permissionIds = items.Select(x => x.Id).ToList(); var existingPermissionIds = role.RolePermissions.Select(x => x.Permission.Id).ToList(); var permissionIdsToAdd = permissionIds.Where(x => !existingPermissionIds.Contains((int)x)).ToList(); // Permissions to add foreach (var permissionId in permissionIdsToAdd) { var permToAdd = allPermissions.FirstOrDefault(x => x.Id == permissionId); if (permToAdd == null) { // TODO throw new BusinessLayerException(string.Format("Invalid Permission Code {0}", code)); } role.AddPermission(permToAdd); } // Permissions to remove List<RolePermission> permissionsToRemove = role.RolePermissions.Where(x => !permissionIds.Contains(x.Permission.Id)).ToList(); foreach (RolePermission perm in permissionsToRemove) { role.RemovePermission(perm.Permission); _context.RolePermissions.Remove(perm); } _context.Roles.Update(role); _context.SaveChanges(); var result = Mapper.Map<List<RolePermissionViewModel>>(role.RolePermissions); return new ObjectResult(result); } /// <summary> /// /// </summary> /// <param name="id">id of Role to update</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Role not found</response> public virtual IActionResult UpdateRole(int id, RoleViewModel item) { if (id != item.Id) { return new UnprocessableEntityObjectResult(new Error("Validation Error", 100, $"Id [{id}] mismatches [{item.Id}].")); } var role = _context.Roles.FirstOrDefault(x => x.Id == id); if (role == null) { // Not Found return new StatusCodeResult(404); } var (roleValid, roleNameError) = ValidateRoleName(item); if (!roleValid) { return roleNameError; } Mapper.Map(item, role); _context.SaveChanges(); return new ObjectResult(Mapper.Map<RoleViewModel>(role)); } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">Role created</response> public virtual IActionResult CreateRole(RoleViewModel item) { var (roleValid, roleNameError) = ValidateRoleName(item); if (!roleValid) { return roleNameError; } var role = new Role(); Mapper.Map(item, role); _context.Roles.Add(role); _context.SaveChanges(); return new ObjectResult(Mapper.Map<RoleViewModel>(role)); } private (bool success, UnprocessableEntityObjectResult errorResult) ValidateRoleName(RoleViewModel role) { if (role.Name.ToUpperInvariant() == Roles.SystemAdmininstrator.ToUpperInvariant()) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 201, $"Role [{role.Name}] cannot be created or updated."))); } if (role.Id > 0) { if (_context.Roles.Any(x => x.Id != role.Id && x.Name.ToUpper() == role.Name.ToUpper())) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 202, $"Role [{role.Name}] already exists."))); } } else { if (_context.Roles.Any(x => x.Name.ToUpper() == role.Name.ToUpper())) { return (false, new UnprocessableEntityObjectResult(new Error("Validation Error", 203, $"Role [{role.Name}] already exists."))); } } return (true, null); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Drawing.Imaging; using System.Runtime.Serialization; using System.Xml.Linq; using BASeCamp.BASeBlock.Particles; using BASeCamp.Elementizer; namespace BASeCamp.BASeBlock.Blocks { [Serializable()] [BlockDescription("Commonly used base class for blocks that are depicted using Image Data.")] public class ImageBlock : Block { private String _BlockImageKey = ""; [Editor(typeof(ImageKeyEditor), typeof(UITypeEditor))] public String BlockImageKey { get { return _BlockImageKey; } set { String oldval =_BlockImageKey; _BlockImageKey = value; OnImageKeySet(oldval, _BlockImageKey); } } public ImageAttributes DrawAttributes { get; set; } public Image BlockImage { get { if (BCBlockGameState.Imageman.Exists(BlockImageKey.ToUpper())) { return BCBlockGameState.Imageman[BlockImageKey.ToUpper()]; } else { return null; } } } protected virtual void OnImageKeySet(String oldkey,String newkey) { } public ImageBlock() : this(new RectangleF(0, 0, 32, 16), null) { } public ImageBlock(RectangleF blockrect) { BlockRectangle = blockrect; BlockImageKey = "bomb"; } public ImageBlock(RectangleF blockrect, String blockimagekey) { BlockRectangle = blockrect; BlockImageKey = blockimagekey; } public ImageBlock(ImageBlock clonethis) : base(clonethis) { BlockImageKey = clonethis.BlockImageKey; DrawAttributes = clonethis.DrawAttributes; BlockRectangle = clonethis.BlockRectangle; } protected ImageBlock(SerializationInfo info, StreamingContext context) : base(info, context) { //custom added code here... BlockImageKey = info.GetString("BlockImageKey"); // DrawAttributes = (ImageAttributes)info.GetValue("BlockImageAttributes", typeof(ImageAttributes)); } public ImageBlock(XElement Source,Object pPersistenceData):base(Source,pPersistenceData) { BlockImageKey = Source.GetAttributeString("BlockImageKey"); } public override XElement GetXmlData(String pNodeName,Object pPersistenceData) { XElement result = base.GetXmlData(pNodeName,pPersistenceData); result.Add(new XAttribute("BlockImageKey",BlockImageKey)); return result; } public override bool PerformBlockHit(BCBlockGameState parentstate, cBall ballhit) { return base.PerformBlockHit(parentstate, ballhit); } public override object Clone() { return new ImageBlock(this); } protected override void CreateOrbs(PointF Location, BCBlockGameState gstate) { //base.CreateOrbs(Location, gstate); } protected override Particle AddStandardSprayParticle(BCBlockGameState parentstate, cBall ballhit) { PointF middlespot; if (ballhit != null) middlespot = ballhit.Location; else { middlespot = CenterPoint(); } //return base.AddStandardSprayParticle(parentstate, ballhit); float useradius = Math.Min(BlockRectangle.Width , BlockRectangle.Height )/4; if (ballhit == null) return new PolyDebris(middlespot, 3, BlockImage,useradius-2,useradius+2,3,7); else { return new PolyDebris(ballhit.Location,3, BlockImage, useradius - 2, useradius + 2, 3, 7); } } public override void Draw(Graphics g) { if (Single.IsNaN(BlockRectangle.X) || Single.IsNaN(BlockRectangle.Y)) BlockRectangle = new RectangleF(0, 0, BlockRectangle.Width, BlockRectangle.Height); base.Draw(g); if (BlockImage != null) { bool error = true; while (error) { try { using (Image usedrawimage = (Image)BlockImage.Clone()) { if (DrawAttributes != null) { // g.DrawImage(BlockImage,BlockRectangle, g.DrawImage(usedrawimage, new Rectangle((int)BlockRectangle.Left, (int)BlockRectangle.Top, (int)BlockRectangle.Width, (int)BlockRectangle.Height), 0f, 0f, BlockImage.Width, BlockImage.Height, GraphicsUnit.Pixel, DrawAttributes); } else { g.DrawImage(usedrawimage, BlockRectangle); } } error = false; } catch { error = true; } //g.DrawString("test", new Font("Comic Sans MS", 8), new SolidBrush(Color.Black), BlockRectangle); } } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { //save the base class info... (rectangle... and whatever else) base.GetObjectData(info, context); //now, we save our fun stuff. info.AddValue("BlockImageKey", BlockImageKey); //ta DA! } } }
// Copyright 2020 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 // // 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 DebuggerApi; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; namespace YetiVSI.DebugEngine.Variables { /// <summary> /// Special purpose Natvis visualizers that are currently supported. /// </summary> public enum CustomVisualizer { None, SSE, SSE2, } public interface IVariableInformationFactory { /// <summary> /// Create an IVariableInformation object that will use the RemoteValue's real name. /// </summary> /// <param name="remoteValue"> /// Value to wrap.</param> /// <param name="displayName"> /// Name of the value as displayed in the UI. Uses the value's name if the parameter is not /// set. Useful when wrapping values that are the result of an expression valuation and may /// have a temporary name like "$1". /// </param> /// <param name="remoteValueFormat"> /// Remote value formatter. Uses the default value format if the parameter is not set. /// </param> /// <param name="customVisualizer"> /// Special purpose visualizer. /// </param> /// <returns> /// Wrapping IVariableInformation object /// </returns> IVariableInformation Create(RemoteValue remoteValue, string displayName = null, FormatSpecifier formatSpecifier = null, CustomVisualizer customVisualizer = CustomVisualizer.None); } /// <summary> /// Defines a concise representation of a variable. /// </summary> public interface IVariableInformation { RemoteValue GetRemoteValue(); /// <summary> /// Get the non-contextual name that can be evaluated within the scope of a stack frame. /// </summary> string Fullname(); // The Visual Studio display name of the variable. string DisplayName { get; } // String that the debugger can send to the built-in text visualizer. string StringView { get; } // String that can be used for assignment operations involving this variable. string AssignmentValue { get; } /// <summary> /// Get serialized representation of the underlying value asynchronously. /// </summary> Task<string> ValueAsync(); // Serialized representation of the variables type. string TypeName { get; } /// <summary> /// Gets the format specifier. /// </summary> string FormatSpecifier { get; } /// <summary> /// Value format used if no format specifier is defined. /// </summary> ValueFormat FallbackValueFormat { get; set; } /// <summary> /// Quick check to see if this might have children. MightHaveChildren() usually matches /// GetChildAdapter().CountChildren(1) != 0, but it is much quicker as it does not evaluate /// the first child. However, there might be false positives, e.g. if all children fail to /// evaluate or if all conditions evaluate to false, and possibly more. This is OK as this /// should be rare and the speed benefit can be significant. There should not be any false /// negatives. /// </summary> /// <returns>Returns true if this might have children.</returns> bool MightHaveChildren(); /// <summary> /// Gets an adapter for querying the children of this variable. /// </summary> IChildAdapter GetChildAdapter(); /// <summary> /// Special purpose Natvis visualizer. Used e.g. for some register sets. Mostly unused. /// </summary> CustomVisualizer CustomVisualizer { get; } /// <summary> /// Returns an enumerable of all ancestor data type names. The first element is the actual /// typename of this and the enumerable is ordered such that the closer ancestors are /// earlier in the enumerable than the more distant ancestors. Ordering of ancestors with /// the same distance is undefined. /// /// If the variable is a pointer or reference, the method returns all inherited types /// of the pointee. /// </summary> IEnumerable<SbType> GetAllInheritedTypes(); bool Error { get; } string ErrorMessage { get; } uint ErrorCode { get; } bool IsPointer { get; } bool IsReference { get; } bool IsTruthy { get; } string Id { get; } // Determine if the varInfo is a null pointer. Returns true if the varInfo // is a pointer and its value is a hex representation of zero, false otherwise. bool IsNullPointer(); /// <summary> /// Expands nested expressions like .a->b[0].c[1]->d. /// </summary> /// <param name="vsExpression">The expression path relative to this.</param> /// <returns>A new </returns> IVariableInformation GetValueForExpressionPath(VsExpression vsExpression); /// <summary> /// Evaluates an expression asynchronously in the same context as this variable. /// </summary> /// <param name="name">Display name of the resulting variable.</param> /// <param name="vsExpression">The expression to evaluate.</param> /// <returns></returns> Task<IVariableInformation> CreateValueFromExpressionAsync(string name, VsExpression vsExpression); /// <summary> /// Evaluates an expression asynchronously in the context of a variable. /// <param name="name">Display name of the resulting variable.</param> /// <param name="expression">The expression to evaluate.</param> /// <returns></returns> /// </summary> Task<IVariableInformation> EvaluateExpressionAsync(string displayName, VsExpression expression); /// <summary> /// Evaluates an expression asynchronously in the context of a variable using lldb-eval. /// </summary> /// <param name="displayName">Display name of the resulting variable.</param> /// <param name="expression">The expression to evaluate.</param> /// <returns></returns> Task<IVariableInformation> EvaluateExpressionLldbEvalAsync( string displayName, VsExpression expression, IDictionary<string, RemoteValue> contextVariables = null); /// <summary> /// Creates a copy of the value. /// </summary> /// <param name="formatSpecifier">Format specifier</param> /// <returns>Information of copied value.</returns> // TODO: Use format specifier from the variable information. Right now, variable // information contains a string representation instead of a `FormatSpecifier`, which isn't // enough for cloning a variable. VariableInformation should be refactored to use the // `FormatSpecifier` representation. IVariableInformation Clone(FormatSpecifier formatSpecifier); /// <summary> /// Dereferences a variable if it is a pointer. /// </summary> IVariableInformation Dereference(); /// <summary> /// Retrieves the child variable by |name|. /// </summary> /// <param name="name">The name of the child variable relative to this.</param> /// <returns>The child or null if it doesn't exist.</returns> IVariableInformation FindChildByName(string name); bool IsReadOnly { get; } /// <summary> /// Update the value of this variable. /// </summary> /// <param name="value">The new value.</param> /// <param name="error">An error description if unsuccessful.</param> /// <returns>True if successful.</returns> bool Assign(string value, out string error); /// <summary> /// Returns address of the memory context. This is used to display the relevant memory /// in Visual Studio's memory view. /// </summary> ulong ? GetMemoryContextAddress(); /// <summary> /// Gets the memory address as a hex string, e.g., "0x00c0ffee". /// The current format affects the formatting as follows: the uppercase number /// formats (e.g., 'X') cause the letters to be uppercase ("0x00C0FFEE"), /// the no-prefix formats (e.g., 'xb') remove the "0x" prefix ("00C0FFEE"). /// Returns the empty string if the value is not a pointer or reference. /// </summary> string GetMemoryAddressAsHex(); // TODO: Find a way to remove caching concerns from IVariableInformation. /// <summary> /// Get a new IVariableInformation that bulk prefetches its fields. /// </summary> /// <returns>The prefetched variable.</returns> IVariableInformation GetCachedView(); } // Decorator class that delegates all calls to the contained IVariableInformation instance. // Makes decorator subclassing easier. public abstract class VariableInformationDecorator : IVariableInformation { protected VariableInformationDecorator(IVariableInformation varInfo) { VarInfo = varInfo; } #region IVariableInformation public RemoteValue GetRemoteValue() => VarInfo.GetRemoteValue(); public bool Error => VarInfo.Error; public string ErrorMessage => VarInfo.ErrorMessage; public uint ErrorCode => VarInfo.ErrorCode; public bool IsReadOnly => VarInfo.IsReadOnly; public bool IsPointer => VarInfo.IsPointer; public bool IsReference => VarInfo.IsReference; public bool IsTruthy => VarInfo.IsTruthy; public virtual string DisplayName => VarInfo.DisplayName; public string TypeName => VarInfo.TypeName; public string AssignmentValue => VarInfo.AssignmentValue; public virtual async Task<string> ValueAsync() => await VarInfo.ValueAsync(); public virtual string StringView => VarInfo.StringView; public string FormatSpecifier => VarInfo.FormatSpecifier; public virtual ValueFormat FallbackValueFormat { get => VarInfo.FallbackValueFormat; set => VarInfo.FallbackValueFormat = value; } public CustomVisualizer CustomVisualizer => VarInfo.CustomVisualizer; public string Id => VarInfo.Id; public bool IsNullPointer() => VarInfo.IsNullPointer(); public virtual bool MightHaveChildren() => VarInfo.MightHaveChildren(); public virtual IChildAdapter GetChildAdapter() => VarInfo.GetChildAdapter(); public virtual IEnumerable<SbType> GetAllInheritedTypes() => VarInfo.GetAllInheritedTypes(); public IVariableInformation GetValueForExpressionPath(VsExpression vsExpression) => VarInfo.GetValueForExpressionPath(vsExpression); public async Task<IVariableInformation> CreateValueFromExpressionAsync( string name, VsExpression vsExpression) => await VarInfo.CreateValueFromExpressionAsync(name, vsExpression); public async Task<IVariableInformation> EvaluateExpressionAsync(string displayName, VsExpression expression) => await VarInfo.EvaluateExpressionAsync(displayName, expression); public async Task<IVariableInformation> EvaluateExpressionLldbEvalAsync( string displayName, VsExpression expression, IDictionary<string, RemoteValue> contextVariables = null) => await VarInfo.EvaluateExpressionLldbEvalAsync(displayName, expression, contextVariables); public IVariableInformation Clone(FormatSpecifier formatSpecifier) => VarInfo.Clone(formatSpecifier); public IVariableInformation Dereference() => VarInfo.Dereference(); public IVariableInformation FindChildByName(string name) => VarInfo.FindChildByName(name); public bool Assign(string value, out string error) => VarInfo.Assign(value, out error); public ulong? GetMemoryContextAddress() => VarInfo.GetMemoryContextAddress(); public virtual string Fullname() => VarInfo.Fullname(); public virtual string GetMemoryAddressAsHex() => VarInfo.GetMemoryAddressAsHex(); public abstract IVariableInformation GetCachedView(); #endregion protected IVariableInformation VarInfo { get; } } // Overrides the variable name of a wrapped IVariableInformation object. public class NamedVariableInformation : VariableInformationDecorator { string displayName; public NamedVariableInformation(IVariableInformation varInfo, string displayName) : base(varInfo) { this.displayName = displayName; } public override string DisplayName => displayName; public override IVariableInformation GetCachedView() => new NamedVariableInformation(VarInfo.GetCachedView(), displayName); } // IVariableInformation stub used for showing passive errors in the Visual Studio UI. public class ErrorVariableInformation : IVariableInformation { public string value; public ErrorVariableInformation(string displayName, string value) { DisplayName = displayName; this.value = value; } #region IVariableInformation public RemoteValue GetRemoteValue() => throw new NotImplementedException(); public bool Error => true; public string ErrorMessage => ""; public uint ErrorCode => 0; public bool IsReadOnly => true; public bool IsPointer => false; public bool IsReference => false; public bool IsTruthy => false; public string Id => ""; public string DisplayName { get; } public string Fullname() => null; public string TypeName => ""; public string AssignmentValue => value; public string Value => value; public Task<string> ValueAsync() => Task.FromResult(Value); public string FormatSpecifier => ""; public ValueFormat FallbackValueFormat { get => ValueFormat.Default; set { /* empty */ } } public CustomVisualizer CustomVisualizer => CustomVisualizer.None; public string StringView => ""; // TODO: In order to support aspect decorators we can't expose 'this'. public IVariableInformation GetCachedView() => this; public bool IsNullPointer() => false; public bool Assign(string value, out string error) => throw new NotImplementedException(); public IVariableInformation GetValueForExpressionPath(VsExpression vsExpression) => throw new NotImplementedException(); public Task<IVariableInformation> CreateValueFromExpressionAsync( string name, VsExpression vsExpression) => throw new NotImplementedException(); public Task<IVariableInformation> EvaluateExpressionAsync(string displayName, VsExpression expression) { throw new NotImplementedException(); } public Task<IVariableInformation> EvaluateExpressionLldbEvalAsync( string displayName, VsExpression expression, IDictionary<string, RemoteValue> conhtextVariables = null) { throw new NotImplementedException(); } public IVariableInformation Clone(FormatSpecifier formatSpecifier) => throw new NotImplementedException(); public IVariableInformation Dereference() { throw new NotImplementedException(); } public IVariableInformation FindChildByName(string name) => throw new NotImplementedException(); public IEnumerable<SbType> GetAllInheritedTypes() => throw new NotImplementedException(); public bool MightHaveChildren() => false; public IChildAdapter GetChildAdapter() => new ListChildAdapter.Factory().Create(new List<IVariableInformation>()); public ulong? GetMemoryContextAddress() => null; public string GetMemoryAddressAsHex() => ""; #endregion } // Creates simple IVariableInformation objects that wrap Debugger.RemoteValue objects. public class LLDBVariableInformationFactory : IVariableInformationFactory { readonly IRemoteValueChildAdapterFactory _childAdapterFactory; VarInfoBuilder _varInfoBuilder; public LLDBVariableInformationFactory(IRemoteValueChildAdapterFactory childAdapterFactory) { _childAdapterFactory = childAdapterFactory; } public void SetVarInfoBuilder(VarInfoBuilder varInfoBuilder) { _varInfoBuilder = varInfoBuilder; } #region IVariableInformationFactory public virtual IVariableInformation Create( RemoteValue remoteValue, string displayName = null, FormatSpecifier formatSpecifier = null, CustomVisualizer customVisualizer = CustomVisualizer .None) => new RemoteValueVariableInformation(_varInfoBuilder, formatSpecifier != null ? formatSpecifier.Expression : string.Empty, RemoteValueFormatProvider.Get( formatSpecifier?.Expression, formatSpecifier?.Size), ValueFormat.Default, remoteValue, displayName ?? remoteValue.GetName(), customVisualizer, _childAdapterFactory); #endregion } /// <summary> /// A simple IVariableInformation wrapper for DebuggerApi.RemoteValues. /// </summary> public class RemoteValueVariableInformation : IVariableInformation { readonly VarInfoBuilder _varInfoBuilder; readonly RemoteValue _remoteValue; readonly IRemoteValueFormat _remoteValueFormat; readonly IRemoteValueChildAdapterFactory _childAdapterFactory; public RemoteValueVariableInformation(VarInfoBuilder varInfoBuilder, string formatSpecifier, IRemoteValueFormat remoteValueFormat, ValueFormat fallbackValueFormat, RemoteValue remoteValue, string displayName, CustomVisualizer customVisualizer, IRemoteValueChildAdapterFactory childAdapterFactory) { _varInfoBuilder = varInfoBuilder; _remoteValueFormat = remoteValueFormat; _remoteValue = remoteValue; _childAdapterFactory = childAdapterFactory; DisplayName = displayName; FormatSpecifier = formatSpecifier; FallbackValueFormat = fallbackValueFormat; CustomVisualizer = customVisualizer; Id = Guid.NewGuid().ToString(); } public RemoteValue GetRemoteValue() => _remoteValue; public string Fullname() => _remoteValue.GetValueType() == DebuggerApi.ValueType.Register ? $"{ExpressionConstants.RegisterPrefix}{_remoteValue.GetName()}" : _remoteValue.GetFullName(); /// <summary> /// Context specific display name of the underlying variable. /// </summary> public string DisplayName { get; } public string AssignmentValue => _remoteValueFormat.GetValueForAssignment(_remoteValue, FallbackValueFormat); public string Value => GetErrorString() ?? _remoteValueFormat.FormatValue(_remoteValue, FallbackValueFormat); public Task<string> ValueAsync() => Task.FromResult(Value); public string StringView => !Error ? _remoteValueFormat.FormatStringView(_remoteValue, FallbackValueFormat) ?? "" : ""; public string TypeName => Error ? "" : _remoteValue.GetTypeName(); public string FormatSpecifier { get; } public ValueFormat FallbackValueFormat { get; set; } public CustomVisualizer CustomVisualizer { get; } public bool MightHaveChildren() => _remoteValueFormat.GetNumChildren(_remoteValue) != 0; public IChildAdapter GetChildAdapter() => _childAdapterFactory.Create(_remoteValue, _remoteValueFormat, _varInfoBuilder, FormatSpecifier); public IEnumerable<SbType> GetAllInheritedTypes() { SbType typeInfo = _remoteValue.GetTypeInfo(); if (typeInfo == null) { yield break; } TypeFlags typeFlags = typeInfo.GetTypeFlags(); if (typeFlags.HasFlag(TypeFlags.IS_POINTER) || typeFlags.HasFlag(TypeFlags.IS_REFERENCE)) { typeInfo = typeInfo.GetPointeeType(); if (typeInfo == null) { yield break; } } var typeQueue = new Queue<SbType>(); typeQueue.Enqueue(typeInfo); while (typeQueue.Count > 0) { SbType curType = typeQueue.Dequeue(); yield return curType; uint numDirectBaseClasses = curType.GetNumberOfDirectBaseClasses(); for (uint i = 0; i < numDirectBaseClasses; i++) { typeQueue.Enqueue(curType.GetDirectBaseClassAtIndex(i).GetTypeInfo()); } } } public bool Error => _remoteValue.GetError().Fail(); public string ErrorMessage => _remoteValue.GetError().GetCString() ?? ""; public uint ErrorCode => _remoteValue.GetError().GetError(); public bool IsPointer => _remoteValue.TypeIsPointerType(); public bool IsReference { get { TypeFlags typeFlags = _remoteValue.GetTypeInfo()?.GetTypeFlags() ?? TypeFlags.NONE; return typeFlags.HasFlag(TypeFlags.IS_REFERENCE); } } public bool IsTruthy { get { if (IsPointer) { return !IsNullPointer(); } // Check for bool "true". Do the type check only if the value is actually "true" // since GetTypeInfo() and GetCanonicalType() are potentially expensive (RPC call). // Be sure to use ValueFormat.Default here, double.TryParse below wouldn't work for // other formats like hex. string value = _remoteValue.GetValue(ValueFormat.Default); if (value == "true") { SbType canonicalType = _remoteValue.GetTypeInfo().GetCanonicalType(); return canonicalType.GetName() == "bool"; } double doubleResult; if (double.TryParse(value, out doubleResult)) { return doubleResult != 0; } return false; } } public string Id { get; } public bool IsNullPointer() { // Strip the hex prefix if it is present. // Be sure to use ValueFormat.Default here, just in case. string hexValue = _remoteValue.GetValue(ValueFormat.Default); if (hexValue.StartsWith("0x") || hexValue.StartsWith("0X")) { hexValue = hexValue.Substring(2); } int intVal; if (!int.TryParse(hexValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out intVal)) { return false; } return intVal == 0 && IsPointer; } public IVariableInformation GetValueForExpressionPath(VsExpression vsExpression) { RemoteValue expressionValue = _remoteValue.GetValueForExpressionPath(vsExpression.Value); if (expressionValue == null) { return null; } return _varInfoBuilder.Create(expressionValue, formatSpecifier: vsExpression.FormatSpecifier); } public async Task<IVariableInformation> CreateValueFromExpressionAsync(string displayName, VsExpression vsExpression) { RemoteValue expressionValue = await _remoteValue.CreateValueFromExpressionAsync(displayName, vsExpression.Value); if (expressionValue == null) { return null; } return _varInfoBuilder.Create(expressionValue, formatSpecifier: vsExpression.FormatSpecifier); } public async Task<IVariableInformation> EvaluateExpressionAsync(string displayName, VsExpression vsExpression) { RemoteValue resultValue = await _remoteValue.EvaluateExpressionAsync(vsExpression.Value); return resultValue == null ? null : _varInfoBuilder.Create(resultValue, displayName, formatSpecifier: vsExpression.FormatSpecifier); } public async Task<IVariableInformation> EvaluateExpressionLldbEvalAsync( string displayName, VsExpression vsExpression, IDictionary<string, RemoteValue> contextVariables = null) { RemoteValue resultValue = await _remoteValue.EvaluateExpressionLldbEvalAsync( vsExpression.Value, contextVariables); return resultValue == null ? null : _varInfoBuilder.Create(resultValue, displayName, formatSpecifier: vsExpression.FormatSpecifier); } public IVariableInformation Clone(FormatSpecifier formatSpecifier) { RemoteValue clonedValue = _remoteValue.Clone(); if (clonedValue == null) { return null; } IVariableInformation clonedVarInfo = _varInfoBuilder.Create(clonedValue, DisplayName, formatSpecifier); clonedVarInfo.FallbackValueFormat = FallbackValueFormat; return clonedVarInfo; } public IVariableInformation Dereference() { RemoteValue dereferencedValue = _remoteValue.Dereference(); return dereferencedValue == null ? null : _varInfoBuilder.Create(dereferencedValue); } public IVariableInformation FindChildByName(string name) { RemoteValue child = _remoteValue.GetChildMemberWithName(name); if (child == null) { return null; } return _varInfoBuilder.Create(child, name); } public bool IsReadOnly => _remoteValue.GetVariableAssignExpression() == null; public bool Assign(string expression, out string error) { if (IsReadOnly) { error = string.Format( "Attempted to assign a value to a read only variable with name '{0}'.", DisplayName); return false; } string cast = ""; if (_remoteValue.TypeIsPointerType() || _remoteValue.GetTypeInfo().GetTypeFlags().HasFlag(TypeFlags.IS_ENUMERATION)) { cast = $"({_remoteValue.GetTypeInfo().GetCanonicalType().GetName()})"; } expression = _remoteValueFormat.FormatExpressionForAssignment(_remoteValue, expression); // Avoid using parentheses to enclose registers because they can prevent assignments // involving initialization lists from succeeding. if (_remoteValue.GetValueType() != DebuggerApi.ValueType.Register) { expression = $"({expression})"; } RemoteValue tempValue = _remoteValue.CreateValueFromExpression( DisplayName, $"{_remoteValue.GetVariableAssignExpression()} = {cast}{expression}"); SbError sbError = tempValue.GetError(); error = sbError.Fail() ? sbError.GetCString() : null; return sbError.Success(); } public ulong? GetMemoryContextAddress() => _remoteValue.GetMemoryContextAddress(); public string GetMemoryAddressAsHex() => _remoteValueFormat.FormatValueAsAddress(_remoteValue); public IVariableInformation GetCachedView() => new RemoteValueVariableInformation( _varInfoBuilder, FormatSpecifier, _remoteValueFormat, FallbackValueFormat, _remoteValue.GetCachedView(_remoteValueFormat.GetValueFormat(FallbackValueFormat)), DisplayName, CustomVisualizer, _childAdapterFactory); /// <summary> /// Returns an error string if the _remoteValue's error is in fail state and null otherwise. /// </summary> string GetErrorString() { SbError error = _remoteValue.GetError(); if (!error.Fail()) { return null; } // TODO: Determine why we are suppressing error strings for REGISTER // ValueTypes. Add comments if needed or remove otherwise. string errorString = _remoteValue.GetValueType() == DebuggerApi.ValueType.Register ? "unavailable" : error.GetCString(); return $"<{errorString}>"; } } /// <summary> /// Represents "[More]" element used when a variable has more children than it is configured /// to return on expand. /// </summary> public class MoreVariableInformation : IVariableInformation { readonly IChildAdapter _childAdapter; public MoreVariableInformation(IChildAdapter childAdapter) { _childAdapter = childAdapter; } public RemoteValue GetRemoteValue() => throw new NotImplementedException(); public string Fullname() => "[More]"; public string DisplayName => "[More]"; public string StringView => ""; public string AssignmentValue => ""; // Returns empty value so that there is no preview for [More]. public string Value => " "; public Task<string> ValueAsync() => Task.FromResult(" "); public string TypeName => ""; public string FormatSpecifier => ""; public ValueFormat FallbackValueFormat { get => ValueFormat.Default; set { /* empty */ } } public bool Assign(string value, out string error) => throw new NotImplementedException(); public ulong? GetMemoryContextAddress() => null; public string GetMemoryAddressAsHex() => ""; public IVariableInformation GetCachedView() => this; public bool MightHaveChildren() => true; public IChildAdapter GetChildAdapter() => _childAdapter; public CustomVisualizer CustomVisualizer => CustomVisualizer.None; public IEnumerable<SbType> GetAllInheritedTypes() => Enumerable.Empty<SbType>(); public bool Error => false; public string ErrorMessage => null; public uint ErrorCode => 0; public bool IsPointer => false; public bool IsReference => false; public bool IsTruthy => false; public string Id => ""; public bool IsNullPointer() => false; public IVariableInformation GetValueForExpressionPath(VsExpression vsExpression) => throw new NotImplementedException(); public Task<IVariableInformation> CreateValueFromExpressionAsync( string name, VsExpression vsExpression) => throw new NotImplementedException(); public Task<IVariableInformation> EvaluateExpressionAsync( string displayName, VsExpression expression) => throw new NotImplementedException(); public Task<IVariableInformation> EvaluateExpressionLldbEvalAsync( string displayName, VsExpression expression, IDictionary<string, RemoteValue> contextVariables = null) => throw new NotImplementedException(); public IVariableInformation Clone(FormatSpecifier formatSpecifier) => throw new NotImplementedException(); public IVariableInformation Dereference() => throw new NotImplementedException(); public IVariableInformation FindChildByName(string name) => throw new NotImplementedException(); public bool IsReadOnly => true; } public class CachingVariableInformation : VariableInformationDecorator { IChildAdapter _cachedChildAdapter; IVariableInformation _cachedVarInfo; string _cachedStringView; public CachingVariableInformation(IVariableInformation varInfo) : base(varInfo) { } public override string StringView { get { if (_cachedStringView == null) { _cachedStringView = VarInfo.StringView; } return _cachedStringView; } } public override ValueFormat FallbackValueFormat { get => VarInfo.FallbackValueFormat; set { if (VarInfo.FallbackValueFormat != value) { InvalidateCaches(); } VarInfo.FallbackValueFormat = value; } } public override IChildAdapter GetChildAdapter() { if (_cachedChildAdapter == null) { _cachedChildAdapter = VarInfo.GetChildAdapter(); } return _cachedChildAdapter; } public override IVariableInformation GetCachedView() { if (_cachedVarInfo == null) { _cachedVarInfo = new CachingVariableInformation(VarInfo.GetCachedView()); } return _cachedVarInfo; } void InvalidateCaches() { _cachedChildAdapter = null; _cachedVarInfo = null; _cachedStringView = null; } } }
using System; using System.Collections.Generic; using System.Linq; using Duality.Resources; using OpenTK.Graphics.OpenGL; namespace Duality.Drawing { internal class DrawBatch<T> : IDrawBatch where T : struct, IVertexData { private static T[] uploadBuffer = null; private T[] vertices = null; private int vertexCount = 0; private int sortIndex = 0; private float zSortIndex = 0.0f; private VertexMode vertexMode = VertexMode.Points; private BatchInfo material = null; public int SortIndex { get { return this.sortIndex; } } public float ZSortIndex { get { return this.zSortIndex; } } public int VertexCount { get { return this.vertexCount; } } public VertexMode VertexMode { get { return this.vertexMode; } } public int VertexTypeIndex { get { return this.vertices[0].TypeIndex; } } public BatchInfo Material { get { return this.material; } } public DrawBatch(BatchInfo material, VertexMode vertexMode, T[] vertices, int vertexCount, float zSortIndex) { if (vertices == null || vertices.Length == 0) throw new ArgumentException("A zero-vertex DrawBatch is invalid."); // Assign data this.vertexCount = Math.Min(vertexCount, vertices.Length); this.vertices = vertices; this.material = material; this.vertexMode = vertexMode; this.zSortIndex = zSortIndex; // Determine sorting index for non-Z-Sort materials if (!this.material.Technique.Res.NeedsZSort) { int vTypeSI = vertices[0].TypeIndex; int matHash = this.material.GetHashCode() % (1 << 23); // Bit significancy is used to achieve sorting by multiple traits at once. // The higher a traits bit significancy, the higher its priority when sorting. this.sortIndex = (((int)vertexMode & 15) << 0) | // XXXX 4 Bit Vertex Mode Offset 4 ((matHash & 8388607) << 4) | // XXXXXXXXXXXXXXXXXXXXXXXaaaa 23 Bit Material Offset 27 ((vTypeSI & 15) << 27); // XXXbbbbbbbbbbbbbbbbbbbbbbbaaaa 4 Bit Vertex Type Offset 31 // Keep an eye on this. If for example two material hash codes randomly have the same 23 lower bits, they // will be sorted as if equal, resulting in blocking batch aggregation. } } public void SetupVBO() { // Set up VBO this.vertices[0].SetupVBO(this.material); } public void UploadToVBO(List<IDrawBatch> batches) { int vertexCount = 0; T[] vertexData = null; if (batches.Count == 1) { // Only one batch? Don't bother copying data DrawBatch<T> b = batches[0] as DrawBatch<T>; vertexData = b.vertices; vertexCount = b.vertices.Length; } else { // Check how many vertices we got vertexCount = batches.Sum(t => t.VertexCount); // Allocate a static / shared buffer for uploading vertices if (uploadBuffer == null) uploadBuffer = new T[Math.Max(vertexCount, 64)]; else if (uploadBuffer.Length < vertexCount) Array.Resize(ref uploadBuffer, Math.Max(vertexCount, uploadBuffer.Length * 2)); // Collect vertex data in one array int curVertexPos = 0; vertexData = uploadBuffer; for (int i = 0; i < batches.Count; i++) { DrawBatch<T> b = batches[i] as DrawBatch<T>; Array.Copy(b.vertices, 0, vertexData, curVertexPos, b.vertexCount); curVertexPos += b.vertexCount; } } // Submit vertex data to GPU this.vertices[0].UploadToVBO(vertexData, vertexCount); } public void FinishVBO() { // Finish VBO this.vertices[0].FinishVBO(this.material); } public void Render(IDrawDevice device, ref int vertexOffset, ref IDrawBatch lastBatchRendered) { if (lastBatchRendered == null || lastBatchRendered.Material != this.material) this.material.SetupForRendering(device, lastBatchRendered == null ? null : lastBatchRendered.Material); GL.DrawArrays((PrimitiveType)this.vertexMode, vertexOffset, this.vertexCount); vertexOffset += this.vertexCount; lastBatchRendered = this; } public void FinishRendering() { this.material.FinishRendering(); } public bool CanShareVBO(IDrawBatch other) { return other is DrawBatch<T>; } public bool CanAppendJIT<U>(float invZSortAccuracy, float zSortIndex, BatchInfo material, VertexMode vertexMode) where U : struct, IVertexData { if (invZSortAccuracy > 0.0f && this.material.Technique.Res.NeedsZSort) { if (Math.Abs(zSortIndex - this.ZSortIndex) > invZSortAccuracy) return false; } return vertexMode == this.vertexMode && this is DrawBatch<U> && IsVertexModeAppendable(this.VertexMode) && material == this.material; } public void AppendJIT(object vertexData, int length) { this.AppendJIT((T[])vertexData, length); } public void AppendJIT(T[] data, int length) { if (this.vertexCount + length > this.vertices.Length) { int newArrSize = MathF.Max(16, this.vertexCount * 2, this.vertexCount + length); Array.Resize(ref this.vertices, newArrSize); } Array.Copy(data, 0, this.vertices, this.vertexCount, length); this.vertexCount += length; if (this.material.Technique.Res.NeedsZSort) this.zSortIndex = CalcZSortIndex(this.vertices, this.vertexCount); } public bool CanAppend(IDrawBatch other) { return other.VertexMode == this.vertexMode && other is DrawBatch<T> && IsVertexModeAppendable(this.VertexMode) && other.Material == this.material; } public void Append(IDrawBatch other) { this.Append((DrawBatch<T>)other); } public float CalcZSortIndex() { this.zSortIndex = CalcZSortIndex(this.vertices, this.vertexCount); return this.zSortIndex; } public void Append(DrawBatch<T> other) { if (this.vertexCount + other.vertexCount > this.vertices.Length) { int newArrSize = MathF.Max(16, this.vertexCount * 2, this.vertexCount + other.vertexCount); Array.Resize(ref this.vertices, newArrSize); } Array.Copy(other.vertices, 0, this.vertices, this.vertexCount, other.vertexCount); this.vertexCount += other.vertexCount; if (this.material.Technique.Res.NeedsZSort) CalcZSortIndex(); } public static bool IsVertexModeAppendable(VertexMode mode) { return mode == VertexMode.Lines || mode == VertexMode.Points || mode == VertexMode.Quads || mode == VertexMode.Triangles; } public static float CalcZSortIndex(T[] vertices, int count = -1) { if (count < 0) count = vertices.Length; float zSortIndex = 0.0f; for (int i = 0; i < count; i++) { zSortIndex += vertices[i].Pos.Z; } return zSortIndex / count; } } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Windows.Forms; using Sce.Atf; using Sce.Sled.Shared.Services; namespace Sce.Sled { public partial class SledProjectModifiedForm : Form { public SledProjectModifiedForm() { InitializeComponent(); GridLines = true; m_lstChanges.BorderStyle = BorderStyle.Fixed3D; m_lstChanges.ForeColor = SystemColors.ControlText; m_lstChanges.BackColor = SystemColors.ControlLightLight; m_highlightTextColor = SystemColors.HighlightText; m_highlightBackColor = ((SolidBrush)SystemBrushes.Highlight).Color; m_categoryTextColor = SystemColors.ControlText; m_gridLinesColor = DefaultBackColor; m_lstChanges.ListViewItemSorter = new ChangeWrapperSorter(); // Add categories AddCategoryHeader("Pending", UserCategory.Pending); AddCategoryHeader("Accepted", UserCategory.Accepted); AddCategoryHeader("Ignored", UserCategory.Ignored); UpdateButtonStates(); } public new void Show() { if (!Visible) base.Show(); else Activate(); } public new void Show(IWin32Window owner) { if (!Visible) base.Show(owner); else Activate(); } public void ReportChanges(ICollection<SledModifiedProjectChange> changes) { // // If there are no changes already reported we can accept them all wholesale // // If there are changes reported it means the user has made repetitive changes outside of SLED to // the project and we need to do some additional processing. Specifically, we need to see if // any changes that were previously made have now been reverted. For instance, the user could // have removed a file then exported (which would make this dialog pop up with a file removal notice), // then added the file back and exported (which would mean the file removal is no longer valid). // // // Example reversions: // // If there was no guid change this update but there's a guid item on the list then we need to // remove it as the change was reverted. // // If there was no asset dir change this update but there's an asset dir item on the list then // we need to remove it as the change was reverted. // // etc. // lock (m_lock) { var existingChanges = new List<SledModifiedProjectChange>(Changes); var bAnyExistingChanges = existingChanges.Count > 0; try { m_lstChanges.BeginUpdate(); if (!bAnyExistingChanges) { // // If no existing items simply add everything // foreach (var change in changes) ReportNewOrUpdateExistingChange(change, null); } else { // // Previous changes have been made and therefore // we require more processing of these latest changes // var bReportedName = false; var existingName = FindWrapperByChangeType(SledModifiedProjectChangeType.Name); var bReportedGuid = false; var existingGuid = FindWrapperByChangeType(SledModifiedProjectChangeType.Guid); var bReportedAssetDir = false; var existingAssetDir = FindWrapperByChangeType(SledModifiedProjectChangeType.AssetDir); var lstExistingFileAdditions = new List<ChangeWrapper>(FindWrappersByChangeType(SledModifiedProjectChangeType.FileAdded)); var lstFileAdditionsUseThisIteration = new List<ChangeWrapper>(); var lstExistingFileRemovals = new List<ChangeWrapper>(FindWrappersByChangeType(SledModifiedProjectChangeType.FileRemoved)); var lstFileRemovalsUsedThisIteration = new List<ChangeWrapper>(); foreach (var change in changes) { if (change.ChangeType == SledModifiedProjectChangeType.Name) { bReportedName = true; ReportNewOrUpdateExistingChange(change, existingName); } if (change.ChangeType == SledModifiedProjectChangeType.Guid) { bReportedGuid = true; ReportNewOrUpdateExistingChange(change, existingGuid); } if (change.ChangeType == SledModifiedProjectChangeType.AssetDir) { bReportedAssetDir = true; ReportNewOrUpdateExistingChange(change, existingAssetDir); } if (change.ChangeType == SledModifiedProjectChangeType.FileAdded) { var fileThisAdded = ((SledModifiedProjectFileAddedChange)change).AbsolutePath; var existingFileAdded = lstExistingFileAdditions.Find( delegate(ChangeWrapper existingFileTemp) { var changeExistingFileAdded = (SledModifiedProjectFileAddedChange)existingFileTemp.Change; var iResult = string.Compare(fileThisAdded, changeExistingFileAdded.AbsolutePath, true); return iResult == 0; }); if (existingFileAdded != null) { if (!lstFileAdditionsUseThisIteration.Contains(existingFileAdded)) lstFileAdditionsUseThisIteration.Add(existingFileAdded); } ReportNewOrUpdateExistingChange(change, existingFileAdded); } if (change.ChangeType == SledModifiedProjectChangeType.FileRemoved) { var fileThisRemoved = ((SledModifiedProjectFileRemovedChange)change).AbsolutePath; var existingFileRemoved = lstExistingFileRemovals.Find( delegate(ChangeWrapper existingFileTemp) { var changeExistingFileRemoved = (SledModifiedProjectFileRemovedChange)existingFileTemp.Change; var iResult = string.Compare(fileThisRemoved, changeExistingFileRemoved.AbsolutePath, true); return iResult == 0; }); if (existingFileRemoved != null) { if (!lstFileRemovalsUsedThisIteration.Contains(existingFileRemoved)) lstFileRemovalsUsedThisIteration.Add(existingFileRemoved); } ReportNewOrUpdateExistingChange(change, existingFileRemoved); } } // Check if name got reverted if (!bReportedName && (existingName != null)) m_lstChanges.Items.Remove(existingName.Item); // Check if guid got reverted if (!bReportedGuid && (existingGuid != null)) m_lstChanges.Items.Remove(existingGuid.Item); // Check if asset dir got reverted if (!bReportedAssetDir && (existingAssetDir != null)) m_lstChanges.Items.Remove(existingAssetDir.Item); // Check file addition reversions { foreach (var wrapperExistingFileAddition in lstExistingFileAdditions) { if (lstFileAdditionsUseThisIteration.Contains(wrapperExistingFileAddition)) continue; if (wrapperExistingFileAddition.Item != null) m_lstChanges.Items.Remove(wrapperExistingFileAddition.Item); } } // Check file removal reversions { foreach (var wrapperExistingFileRemoval in lstExistingFileRemovals) { if (lstFileRemovalsUsedThisIteration.Contains(wrapperExistingFileRemoval)) continue; if (wrapperExistingFileRemoval.Item != null) m_lstChanges.Items.Remove(wrapperExistingFileRemoval.Item); } } } } finally { m_lstChanges.EndUpdate(); // Adjust column header width if (m_lstChanges.Items.Count > m_iCategoryCount) m_lstChanges.Columns[0].Width = -1; UpdateButtonStates(); } } } public IEnumerable<SledModifiedProjectChange> Changes { get { lock (m_lock) { foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; yield return wrapper.Change; } } } } public event EventHandler<SledModifiedProjectChangesEventArgs> ChangesSubmitted; /// <summary> /// Gets or sets the text color</summary> public Color TextColor { get { return m_textColor; } set { m_textColor = value; m_lstChanges.Invalidate(); } } /// <summary> /// Gets or sets the highlight text color</summary> public Color HighlightTextColor { get { return m_highlightTextColor; } set { m_highlightTextColor = value; m_lstChanges.Invalidate(); } } /// <summary> /// Gets or sets the highlight background color</summary> public Color HighlightBackColor { get { return m_highlightBackColor; } set { m_highlightBackColor = value; m_lstChanges.Invalidate(); } } /// <summary> /// Gets or sets the category text color</summary> public Color CategoryTextColor { get { return m_categoryTextColor; } set { m_categoryTextColor = value; m_lstChanges.Invalidate(); } } /// <summary> /// Gets or sets the grid lines color</summary> public Color GridLinesColor { get { return m_gridLinesColor; } set { m_gridLinesColor = value; m_lstChanges.Invalidate(); } } /// <summary> /// Gets or sets whether grid lines are visible</summary> public bool GridLines { get { return m_gridLines; } set { m_gridLines = value; m_lstChanges.Invalidate(); } } #region Form Events private void SledProjectModifiedFormFormClosing(object sender, FormClosingEventArgs e) { lock (m_lock) { e.Cancel = true; if ((m_lstChanges.Items.Count - m_iCategoryCount) <= 0) { Hide(); } else { MessageBox.Show( this, @"There are still pending changes! You must accept or " + @"or ignore them and then click submit before continuing.", Text, MessageBoxButtons.OK, MessageBoxIcon.Stop); } } } private void LstChangesSelectedIndexChanged(object sender, EventArgs e) { lock (m_lock) { UpdateButtonStates(); } } private void LstChangesDrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) { e.DrawDefault = true; } private void LstChangesDrawItem(object sender, DrawListViewItemEventArgs e) { e.DrawDefault = false; if (e.Item.Tag is UserCategory) DrawCategoryHeader(e, CategoryTextColor); } private void LstChangesDrawSubItem(object sender, DrawListViewSubItemEventArgs e) { e.DrawDefault = false; var wrapper = e.Item.Tag as ChangeWrapper; if (wrapper == null) return; var isLastColumn = (e.ColumnIndex == (m_lstChanges.Columns.Count - 1)); var isLastVisibleItem = e.ItemIndex == m_lstChanges.Items.Count - 1; DrawBackground(e.Graphics, e.Bounds, BackColor); if (GridLines) DrawGridLines(e.Graphics, e.Bounds, GridLinesColor); if (isLastColumn) { var extraneousFauxNonClientRect = new Rectangle( e.Bounds.Right, e.Bounds.Top, Bounds.Right - e.Bounds.Right, e.Bounds.Height); DrawBackground(e.Graphics, extraneousFauxNonClientRect, BackColor); if (isLastVisibleItem) { var rect = new Rectangle( e.Bounds.Right, e.Bounds.Y + e.Bounds.Height, Bounds.Right - e.Bounds.Right, Bounds.Bottom - e.Bounds.Bottom); DrawBackground(e.Graphics, rect, BackColor); } // continue grid lines out to 'infinity' horizontally if (GridLines) { var extraneousFauxNonClientGridLinesRect = extraneousFauxNonClientRect; extraneousFauxNonClientGridLinesRect.Inflate(1, 0); DrawGridLines(e.Graphics, extraneousFauxNonClientGridLinesRect, GridLinesColor); } } // Start formatting flags var flags = TextFormatFlags.VerticalCenter; // Add ellipsis if text is wider than bounds { var textSize = TextRenderer.MeasureText(e.Graphics, e.SubItem.Text, e.Item.Font); if (textSize.Width > e.Bounds.Width) flags |= TextFormatFlags.EndEllipsis; } // Highlight cells if item is selected if (e.Item.Selected) { using (Brush brush = new SolidBrush(HighlightBackColor)) e.Graphics.FillRectangle(brush, e.Bounds); } var textColor = e.Item.Selected ? HighlightTextColor : TextColor; TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.Item.Font, e.Bounds, textColor, flags); } private void LstChangesKeyUp(object sender, KeyEventArgs e) { if ((e.KeyCode == Keys.A) && (e.Modifiers == Keys.Control)) { foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; if (!lstItem.Selected) lstItem.Selected = true; } } if ((e.KeyCode == Keys.Delete) || (e.KeyCode == Keys.Space)) { var bAnyChanges = false; var category = e.KeyCode == Keys.Delete ? UserCategory.Ignored : UserCategory.Accepted; try { foreach (ListViewItem lstItem in m_lstChanges.SelectedItems) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; if (wrapper.Category == category) continue; wrapper.Category = category; if (!bAnyChanges) bAnyChanges = true; } } finally { if (bAnyChanges) m_lstChanges.Sort(); } } } private void BtnAcceptAllClick(object sender, EventArgs e) { lock (m_lock) { ChangeAllListViewItemsToCategory(UserCategory.Accepted); UpdateButtonStates(); } } private void BtnAcceptSelectedClick(object sender, EventArgs e) { lock (m_lock) { ChangeSelectedListViewItemsToCategory(UserCategory.Accepted); UpdateButtonStates(); } } private void BtnIgnoreSelectedClick(object sender, EventArgs e) { lock (m_lock) { ChangeSelectedListViewItemsToCategory(UserCategory.Ignored); UpdateButtonStates(); } } private void BtnIgnoreAllClick(object sender, EventArgs e) { lock (m_lock) { ChangeAllListViewItemsToCategory(UserCategory.Ignored); UpdateButtonStates(); } } private void BtnSubmitClick(object sender, EventArgs e) { lock (m_lock) { var lstAccepted = new List<SledModifiedProjectChange>(); var lstIgnored = new List<SledModifiedProjectChange>(); var lstRemoveItems = new List<ListViewItem>(); foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; if ((wrapper.Category != UserCategory.Accepted) && (wrapper.Category != UserCategory.Ignored)) continue; // Mark for deletion lstRemoveItems.Add(lstItem); // Add to proper list if (wrapper.Category == UserCategory.Accepted) lstAccepted.Add(wrapper.Change); else lstIgnored.Add(wrapper.Change); } // Fire event ChangesSubmitted.Raise(this, new SledModifiedProjectChangesEventArgs(lstAccepted, lstIgnored)); // Remove all submitted changes m_lstChanges.BeginUpdate(); foreach (var lstItem in lstRemoveItems) m_lstChanges.Items.Remove(lstItem); m_lstChanges.EndUpdate(); // Update UpdateButtonStates(); // Stop showing now that no more items exist if ((m_lstChanges.Items.Count - m_iCategoryCount) <= 0) Hide(); } } #endregion #region Member Methods private void AddCategoryHeader(string header, UserCategory category) { var lstItem = new ListViewItem(header) {Tag = category}; m_iCategoryCount++; m_lstChanges.Items.Add(lstItem); } private void ReportNewOrUpdateExistingChange(SledModifiedProjectChange change, ChangeWrapper existing) { var wrapper = new ChangeWrapper(change) { Category = UserCategory.Pending }; // Default category if (existing == null) { // Create node representing change var lstItem = new ListViewItem(wrapper.Change.ToString()) { Tag = wrapper }; // Set references wrapper.Item = lstItem; // Add to list m_lstChanges.Items.Add(lstItem); } else { // Update existing item existing.Update(change); } } private ChangeWrapper FindWrapperByChangeType(SledModifiedProjectChangeType changeType) { lock (m_lock) { return (from ListViewItem lstItem in m_lstChanges.Items where lstItem.Tag != null where (lstItem.Tag is ChangeWrapper) select lstItem.Tag as ChangeWrapper).FirstOrDefault(itemWrapper => itemWrapper.Change.ChangeType == changeType); } } private IEnumerable<ChangeWrapper> FindWrappersByChangeType(SledModifiedProjectChangeType changeType) { lock (m_lock) { foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var itemWrapper = lstItem.Tag as ChangeWrapper; if (itemWrapper.Change.ChangeType != changeType) continue; yield return itemWrapper; } } } private void ChangeAllListViewItemsToCategory(UserCategory category) { lock (m_lock) { var bChangedAnyItems = false; foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; if (wrapper.Category == category) continue; wrapper.Category = category; if (!bChangedAnyItems) bChangedAnyItems = true; } if (bChangedAnyItems) m_lstChanges.Sort(); } } private void ChangeSelectedListViewItemsToCategory(UserCategory category) { lock (m_lock) { var bChangedAnyItems = false; foreach (ListViewItem lstItem in m_lstChanges.SelectedItems) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; if (wrapper.Category == category) continue; wrapper.Category = category; if (!bChangedAnyItems) bChangedAnyItems = true; } if (bChangedAnyItems) m_lstChanges.Sort(); } } private void UpdateButtonStates() { var iPendingCount = 0; var iAcceptedCount = 0; var iIgnoredCount = 0; var iCountSelected = 0; foreach (ListViewItem lstItem in m_lstChanges.Items) { if (lstItem.Tag == null) continue; if (lstItem.Tag is UserCategory) continue; if (!(lstItem.Tag is ChangeWrapper)) continue; var wrapper = lstItem.Tag as ChangeWrapper; if (wrapper.Category == UserCategory.Pending) iPendingCount++; if (wrapper.Category == UserCategory.Accepted) iAcceptedCount++; if (wrapper.Category == UserCategory.Ignored) iIgnoredCount++; if (lstItem.Selected) iCountSelected++; } m_btnAcceptAll.Enabled = (m_lstChanges.Items.Count - m_iCategoryCount) > 0; m_btnAcceptSelected.Enabled = ((iIgnoredCount > 0) || (iPendingCount > 0)) && (iCountSelected > 0); m_btnIgnoreSelected.Enabled = ((iAcceptedCount > 0) || (iPendingCount > 0)) && (iCountSelected > 0); m_btnIgnoreAll.Enabled = (m_lstChanges.Items.Count - m_iCategoryCount) > 0; m_btnSubmit.Enabled = (iAcceptedCount > 0) || (iIgnoredCount > 0); } private static void DrawBackground(Graphics gfx, Rectangle bounds, Color color) { using (var brush = new SolidBrush(color)) gfx.FillRectangle(brush, bounds); } private static void DrawGridLines(Graphics gfx, Rectangle bounds, Color color) { using (var p = new Pen(color)) gfx.DrawRectangle(p, bounds); } private static void DrawCategoryHeader(DrawListViewItemEventArgs e, Color color) { using (var font = new Font(e.Item.Font, FontStyle.Bold)) { using (var sf = new StringFormat()) { sf.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.NoClip; using (var brush = new SolidBrush(color)) { e.Graphics.DrawString(e.Item.Text, font, brush, e.Item.Bounds.X, e.Item.Bounds.Y, sf); } } } } #endregion #region Private Classes private enum UserCategory { Pending = 1, Accepted = 2, Ignored = 3, } private class ChangeWrapper { public ChangeWrapper(SledModifiedProjectChange change) { Change = change; } public void Update(SledModifiedProjectChange change) { Change = change; if (Item != null) Item.Text = change.ToString(); } public ListViewItem Item; public UserCategory Category; public SledModifiedProjectChange Change; } private class ChangeWrapperSorter : IComparer { #region IComparer Interface public int Compare(object x, object y) { var lstX = x as ListViewItem; var lstY = y as ListViewItem; if ((lstX == null) && (lstY == null)) return 0; if (lstX == null) return -1; if (lstY == null) return 1; // Compare categories if ((lstX.Tag is UserCategory) && (lstY.Tag is UserCategory)) { return CompareCategories((UserCategory)lstX.Tag, (UserCategory)lstY.Tag); } // Compare category to wrapper if ((lstX.Tag is UserCategory) && (lstY.Tag is ChangeWrapper)) { return CompareCategoryToChangeWrapper((UserCategory)lstX.Tag, (ChangeWrapper)lstY.Tag); } // Compare wrapper to category if ((lstX.Tag is ChangeWrapper) && (lstY.Tag is UserCategory)) { return CompareCategoryToChangeWrapper((UserCategory)lstY.Tag, (ChangeWrapper)lstX.Tag) * -1; } // Compare wrapper to wrapper if ((lstX.Tag is ChangeWrapper) && (lstY.Tag is ChangeWrapper)) { return CompareChangeWrapperToChangeWrapper((ChangeWrapper)lstX.Tag, (ChangeWrapper)lstY.Tag); } return 0; } #endregion private static int CompareCategories(UserCategory cat1, UserCategory cat2) { if (cat1 == cat2) return 0; return cat1 < cat2 ? -1 : 1; } private static int CompareCategoryToChangeWrapper(UserCategory cat, ChangeWrapper wrapper) { if (cat == wrapper.Category) return -1; return CompareCategories(cat, wrapper.Category); } private static int CompareChangeWrapperToChangeWrapper(ChangeWrapper wrapper1, ChangeWrapper wrapper2) { // Check categories if (wrapper1.Category != wrapper2.Category) return CompareCategories(wrapper1.Category, wrapper2.Category); // Compare actual changes if (wrapper1.Change.ChangeType == wrapper2.Change.ChangeType) { var retval = 0; switch (wrapper1.Change.ChangeType) { case SledModifiedProjectChangeType.FileAdded: retval = CompareFileAddedChanges( wrapper1.Change as SledModifiedProjectFileAddedChange, wrapper2.Change as SledModifiedProjectFileAddedChange); break; case SledModifiedProjectChangeType.FileRemoved: retval = CompareFileRemovedChanges( wrapper1.Change as SledModifiedProjectFileRemovedChange, wrapper2.Change as SledModifiedProjectFileRemovedChange); break; } return retval; } return wrapper1.Change.ChangeType < wrapper2.Change.ChangeType ? -1 : 1; } private static int CompareFileAddedChanges(SledModifiedProjectFileAddedChange change1, SledModifiedProjectFileAddedChange change2) { return string.Compare(change1.AbsolutePath, change2.AbsolutePath); } private static int CompareFileRemovedChanges(SledModifiedProjectFileRemovedChange change1, SledModifiedProjectFileRemovedChange change2) { return string.Compare(change1.AbsolutePath, change2.AbsolutePath); } } #endregion private int m_iCategoryCount; private bool m_gridLines; private Color m_textColor; private Color m_highlightTextColor; private Color m_highlightBackColor; private Color m_categoryTextColor; private Color m_gridLinesColor; private volatile object m_lock = new object(); } }
//------------------------------------------------------------------------------ // <copyright file="Splitter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.Windows.Forms { using Microsoft.Win32; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Security; using System.Security.Permissions; using System.Windows.Forms; using System.Globalization; /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter"]/*' /> /// <devdoc> /// Provides user resizing of docked elements at run time. To use a Splitter you can /// dock any control to an edge of a container, and then dock the splitter to the same /// edge. The splitter will then resize the control that is previous in the docking /// order. /// </devdoc> [ ComVisible(true), ClassInterface(ClassInterfaceType.AutoDispatch), DefaultEvent("SplitterMoved"), DefaultProperty("Dock"), SRDescription(SR.DescriptionSplitter), Designer("System.Windows.Forms.Design.SplitterDesigner, " + AssemblyRef.SystemDesign) ] public class Splitter : Control { private const int DRAW_START = 1; private const int DRAW_MOVE = 2; private const int DRAW_END = 3; private const int defaultWidth = 3; private BorderStyle borderStyle = System.Windows.Forms.BorderStyle.None; private int minSize = 25; private int minExtra = 25; private Point anchor = Point.Empty; private Control splitTarget; private int splitSize = -1; private int splitterThickness = 3; private int initTargetSize; private int lastDrawSplit = -1; private int maxSize; private static readonly object EVENT_MOVING = new object(); private static readonly object EVENT_MOVED = new object(); // refer to VsWhidbey : 423553 (Cannot expose IMessageFilter.PreFilterMessage through this unsealed class) private SplitterMessageFilter splitterMessageFilter = null; /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Splitter"]/*' /> /// <devdoc> /// Creates a new Splitter. /// </devdoc> public Splitter() : base() { SetStyle(ControlStyles.Selectable, false); TabStop = false; minSize = 25; minExtra = 25; Dock = DockStyle.Left; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Anchor"]/*' /> /// <devdoc> /// The current value of the anchor property. The anchor property /// determines which edges of the control are anchored to the container's /// edges. /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DefaultValue(AnchorStyles.None)] public override AnchorStyles Anchor { get { return AnchorStyles.None; } set { // do nothing! } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.AllowDrop"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override bool AllowDrop { get { return base.AllowDrop; } set { base.AllowDrop = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.DefaultSize"]/*' /> /// <devdoc> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </devdoc> protected override Size DefaultSize { get { return new Size(defaultWidth, defaultWidth); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.DefaultCursor"]/*' /> protected override Cursor DefaultCursor { get { switch (Dock) { case DockStyle.Top: case DockStyle.Bottom: return Cursors.HSplit; case DockStyle.Left: case DockStyle.Right: return Cursors.VSplit; } return base.DefaultCursor; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ForeColor"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ForeColorChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler ForeColorChanged { add { base.ForeColorChanged += value; } remove { base.ForeColorChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.BackgroundImage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.BackgroundImageChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageChanged { add { base.BackgroundImageChanged += value; } remove { base.BackgroundImageChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.BackgroundImageLayout"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } set { base.BackgroundImageLayout = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.BackgroundImageLayoutChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler BackgroundImageLayoutChanged { add { base.BackgroundImageLayoutChanged += value; } remove { base.BackgroundImageLayoutChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Font"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public override Font Font { get { return base.Font; } set { base.Font = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.FontChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler FontChanged { add { base.FontChanged += value; } remove { base.FontChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.BorderStyle"]/*' /> /// <devdoc> /// Indicates what type of border the Splitter control has. This value /// comes from the System.Windows.Forms.BorderStyle enumeration. /// </devdoc> [ DefaultValue(BorderStyle.None), SRCategory(SR.CatAppearance), System.Runtime.InteropServices.DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE), SRDescription(SR.SplitterBorderStyleDescr) ] public BorderStyle BorderStyle { get { return borderStyle; } set { //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(value, (int)value, (int)BorderStyle.None, (int)BorderStyle.Fixed3D)){ throw new InvalidEnumArgumentException("value", (int)value, typeof(BorderStyle)); } if (borderStyle != value) { borderStyle = value; UpdateStyles(); } } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.CreateParams"]/*' /> /// <devdoc> /// Returns the parameters needed to create the handle. Inheriting classes /// can override this to provide extra functionality. They should not, /// however, forget to call base.getCreateParams() first to get the struct /// filled up with the basic info. /// </devdoc> protected override CreateParams CreateParams { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { CreateParams cp = base.CreateParams; cp.ExStyle &= (~NativeMethods.WS_EX_CLIENTEDGE); cp.Style &= (~NativeMethods.WS_BORDER); switch (borderStyle) { case BorderStyle.Fixed3D: cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE; break; case BorderStyle.FixedSingle: cp.Style |= NativeMethods.WS_BORDER; break; } return cp; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.DefaultImeMode"]/*' /> protected override ImeMode DefaultImeMode { get { return ImeMode.Disable; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Dock"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> [ Localizable(true), DefaultValue(DockStyle.Left) ] public override DockStyle Dock { get { return base.Dock;} set { if (!(value == DockStyle.Top || value == DockStyle.Bottom || value == DockStyle.Left || value == DockStyle.Right)) { throw new ArgumentException(SR.GetString(SR.SplitterInvalidDockEnum)); } int requestedSize = splitterThickness; base.Dock = value; switch (Dock) { case DockStyle.Top: case DockStyle.Bottom: if (splitterThickness != -1) { Height = requestedSize; } break; case DockStyle.Left: case DockStyle.Right: if (splitterThickness != -1) { Width = requestedSize; } break; } } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Horizontal"]/*' /> /// <devdoc> /// Determines if the splitter is horizontal. /// </devdoc> /// <internalonly/> private bool Horizontal { get { DockStyle dock = Dock; return dock == DockStyle.Left || dock == DockStyle.Right; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ImeMode"]/*' /> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public ImeMode ImeMode { get { return base.ImeMode; } set { base.ImeMode = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ImeModeChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ImeModeChanged { add { base.ImeModeChanged += value; } remove { base.ImeModeChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.MinExtra"]/*' /> /// <devdoc> /// The minExtra is this minimum size (in pixels) of the remaining /// area of the container. This area is center of the container that /// is not occupied by edge docked controls, this is the are that /// would be used for any fill docked control. /// </devdoc> [ SRCategory(SR.CatBehavior), Localizable(true), DefaultValue(25), SRDescription(SR.SplitterMinExtraDescr) ] public int MinExtra { get { return minExtra; } set { if (value < 0) value = 0; minExtra = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.MinSize"]/*' /> /// <devdoc> /// The minSize is the minimum size (in pixels) of the target of the /// splitter. The target of a splitter is always the control adjacent /// to the splitter, just prior in the dock order. /// </devdoc> [ SRCategory(SR.CatBehavior), Localizable(true), DefaultValue(25), SRDescription(SR.SplitterMinSizeDescr) ] public int MinSize { get { return minSize; } set { if (value < 0) value = 0; minSize = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitPosition"]/*' /> /// <devdoc> /// The position of the splitter. If the splitter is not bound /// to a control, SplitPosition will be -1. /// </devdoc> [ SRCategory(SR.CatLayout), Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), SRDescription(SR.SplitterSplitPositionDescr) ] public int SplitPosition { get { if (splitSize == -1) splitSize = CalcSplitSize(); return splitSize; } set { // calculate maxSize and other bounding conditions SplitData spd = CalcSplitBounds(); // this is not an else-if to handle the maxSize < minSize case... // ie. we give minSize priority over maxSize... if (value > maxSize) value = maxSize; if (value < minSize) value = minSize; // if (value == splitSize) return; -- do we need this check? splitSize = value; DrawSplitBar(DRAW_END); if (spd.target == null) { splitSize = -1; return; } Rectangle bounds = spd.target.Bounds; switch (Dock) { case DockStyle.Top: bounds.Height = value; break; case DockStyle.Bottom: bounds.Y += bounds.Height - splitSize; bounds.Height = value; break; case DockStyle.Left: bounds.Width = value; break; case DockStyle.Right: bounds.X += bounds.Width - splitSize; bounds.Width = value; break; } spd.target.Bounds = bounds; Application.DoEvents(); OnSplitterMoved(new SplitterEventArgs(Left, Top, (Left + bounds.Width / 2), (Top + bounds.Height / 2))); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.TabStop"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public bool TabStop { get { return base.TabStop; } set { base.TabStop = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.TabStopChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TabStopChanged { add { base.TabStopChanged += value; } remove { base.TabStopChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Text"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [ Browsable(false), EditorBrowsable(EditorBrowsableState.Never), Bindable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public override string Text { get { return base.Text; } set { base.Text = value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.TextChanged"]/*' /> /// <internalonly/> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] new public event EventHandler TextChanged { add { base.TextChanged += value; } remove { base.TextChanged -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Enter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Enter { add { base.Enter += value; } remove { base.Enter -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.KeyUp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyUp { add { base.KeyUp += value; } remove { base.KeyUp -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.KeyDown"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyDown { add { base.KeyDown += value; } remove { base.KeyDown -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.KeyPress"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event KeyPressEventHandler KeyPress { add { base.KeyPress += value; } remove { base.KeyPress -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.Leave"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Leave { add { base.Leave += value; } remove { base.Leave -= value; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitterMoving"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SRCategory(SR.CatBehavior), SRDescription(SR.SplitterSplitterMovingDescr)] public event SplitterEventHandler SplitterMoving { add { Events.AddHandler(EVENT_MOVING, value); } remove { Events.RemoveHandler(EVENT_MOVING, value); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitterMoved"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [SRCategory(SR.CatBehavior), SRDescription(SR.SplitterSplitterMovedDescr)] public event SplitterEventHandler SplitterMoved { add { Events.AddHandler(EVENT_MOVED, value); } remove { Events.RemoveHandler(EVENT_MOVED, value); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.DrawSplitBar"]/*' /> /// <devdoc> /// Draws the splitter bar at the current location. Will automatically /// cleanup anyplace the splitter was drawn previously. /// </devdoc> /// <internalonly/> private void DrawSplitBar(int mode) { if (mode != DRAW_START && lastDrawSplit != -1) { DrawSplitHelper(lastDrawSplit); lastDrawSplit = -1; } // Bail if drawing with no old point... // else if (mode != DRAW_START && lastDrawSplit == -1) { return; } if (mode != DRAW_END) { DrawSplitHelper(splitSize); lastDrawSplit = splitSize; } else { if (lastDrawSplit != -1) { DrawSplitHelper(lastDrawSplit); } lastDrawSplit = -1; } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.CalcSplitLine"]/*' /> /// <devdoc> /// Calculates the bounding rect of the split line. minWeight refers /// to the minimum height or width of the splitline. /// </devdoc> private Rectangle CalcSplitLine(int splitSize, int minWeight) { Rectangle r = Bounds; Rectangle bounds = splitTarget.Bounds; switch (Dock) { case DockStyle.Top: if (r.Height < minWeight) r.Height = minWeight; r.Y = bounds.Y + splitSize; break; case DockStyle.Bottom: if (r.Height < minWeight) r.Height = minWeight; r.Y = bounds.Y + bounds.Height - splitSize - r.Height; break; case DockStyle.Left: if (r.Width < minWeight) r.Width = minWeight; r.X = bounds.X + splitSize; break; case DockStyle.Right: if (r.Width < minWeight) r.Width = minWeight; r.X = bounds.X + bounds.Width - splitSize - r.Width; break; } return r; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.CalcSplitSize"]/*' /> /// <devdoc> /// Calculates the current size of the splitter-target. /// </devdoc> /// <internalonly/> private int CalcSplitSize() { Control target = FindTarget(); if (target == null) return -1; Rectangle r = target.Bounds; switch (Dock) { case DockStyle.Top: case DockStyle.Bottom: return r.Height; case DockStyle.Left: case DockStyle.Right: return r.Width; default: return -1; // belts & braces } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.CalcSplitBounds"]/*' /> /// <devdoc> /// Calculates the bounding criteria for the splitter. /// </devdoc> /// <internalonly/> private SplitData CalcSplitBounds() { SplitData spd = new SplitData(); Control target = FindTarget(); spd.target = target; if (target != null) { switch (target.Dock) { case DockStyle.Left: case DockStyle.Right: initTargetSize = target.Bounds.Width; break; case DockStyle.Top: case DockStyle.Bottom: initTargetSize = target.Bounds.Height; break; } Control parent = ParentInternal; Control.ControlCollection children = parent.Controls; int count = children.Count; int dockWidth = 0, dockHeight = 0; for (int i = 0; i < count; i++) { Control ctl = children[i]; if (ctl != target) { switch (((Control)ctl).Dock) { case DockStyle.Left: case DockStyle.Right: dockWidth += ctl.Width; break; case DockStyle.Top: case DockStyle.Bottom: dockHeight += ctl.Height; break; } } } Size clientSize = parent.ClientSize; if (Horizontal) { maxSize = clientSize.Width - dockWidth - minExtra; } else { maxSize = clientSize.Height - dockHeight - minExtra; } spd.dockWidth = dockWidth; spd.dockHeight = dockHeight; } return spd; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.DrawSplitHelper"]/*' /> /// <devdoc> /// Draws the splitter line at the requested location. Should only be called /// by drawSpltBar. /// </devdoc> /// <internalonly/> private void DrawSplitHelper(int splitSize) { if (splitTarget == null) { return; } Rectangle r = CalcSplitLine(splitSize, 3); IntPtr parentHandle = ParentInternal.Handle; IntPtr dc = UnsafeNativeMethods.GetDCEx(new HandleRef(ParentInternal, parentHandle), NativeMethods.NullHandleRef, NativeMethods.DCX_CACHE | NativeMethods.DCX_LOCKWINDOWUPDATE); IntPtr halftone = ControlPaint.CreateHalftoneHBRUSH(); IntPtr saveBrush = SafeNativeMethods.SelectObject(new HandleRef(ParentInternal, dc), new HandleRef(null, halftone)); SafeNativeMethods.PatBlt(new HandleRef(ParentInternal, dc), r.X, r.Y, r.Width, r.Height, NativeMethods.PATINVERT); SafeNativeMethods.SelectObject(new HandleRef(ParentInternal, dc), new HandleRef(null, saveBrush)); SafeNativeMethods.DeleteObject(new HandleRef(null, halftone)); UnsafeNativeMethods.ReleaseDC(new HandleRef(ParentInternal, parentHandle), new HandleRef(null, dc)); } /// <devdoc> /// Raises a splitter event /// </devdoc> /// <internalonly/> /* No one seems to be calling this, so it is okay to comment it out private void RaiseSplitterEvent(object key, SplitterEventArgs spevent) { SplitterEventHandler handler = (SplitterEventHandler)Events[key]; if (handler != null) handler(this, spevent); } */ /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.FindTarget"]/*' /> /// <devdoc> /// Finds the target of the splitter. The target of the splitter is the /// control that is "outside" or the splitter. For example, if the splitter /// is docked left, the target is the control that is just to the left /// of the splitter. /// </devdoc> /// <internalonly/> private Control FindTarget() { Control parent = ParentInternal; if (parent == null) return null; Control.ControlCollection children = parent.Controls; int count = children.Count; DockStyle dock = Dock; for (int i = 0; i < count; i++) { Control target = children[i]; if (target != this) { switch (dock) { case DockStyle.Top: if (target.Bottom == Top) return(Control)target; break; case DockStyle.Bottom: if (target.Top == Bottom) return(Control)target; break; case DockStyle.Left: if (target.Right == Left) return(Control)target; break; case DockStyle.Right: if (target.Left == Right) return(Control)target; break; } } } return null; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.GetSplitSize"]/*' /> /// <devdoc> /// Calculates the split size based on the mouse position (x, y). /// </devdoc> /// <internalonly/> private int GetSplitSize(int x, int y) { int delta; if (Horizontal) { delta = x - anchor.X; } else { delta = y - anchor.Y; } int size = 0; switch (Dock) { case DockStyle.Top: size = splitTarget.Height + delta; break; case DockStyle.Bottom: size = splitTarget.Height - delta; break; case DockStyle.Left: size = splitTarget.Width + delta; break; case DockStyle.Right: size = splitTarget.Width - delta; break; } return Math.Max(Math.Min(size, maxSize), minSize); } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnKeyDown"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (splitTarget != null && e.KeyCode == Keys.Escape) { SplitEnd(false); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnMouseDown"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left && e.Clicks == 1) { SplitBegin(e.X, e.Y); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnMouseMove"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (splitTarget != null) { int x = e.X + Left; int y = e.Y + Top; Rectangle r = CalcSplitLine(GetSplitSize(e.X, e.Y), 0); int xSplit = r.X; int ySplit = r.Y; OnSplitterMoving(new SplitterEventArgs(x, y, xSplit, ySplit)); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnMouseUp"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (splitTarget != null) { int x = e.X + Left; int y = e.Y + Top; Rectangle r = CalcSplitLine(GetSplitSize(e.X, e.Y), 0); int xSplit = r.X; int ySplit = r.Y; SplitEnd(true); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnSplitterMoving"]/*' /> /// <devdoc> /// Inherriting classes should override this method to respond to the /// splitterMoving event. This event occurs while the splitter is /// being moved by the user. /// </devdoc> protected virtual void OnSplitterMoving(SplitterEventArgs sevent) { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVING]; if (handler != null) handler(this,sevent); if (splitTarget != null) { SplitMove(sevent.SplitX, sevent.SplitY); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.OnSplitterMoved"]/*' /> /// <devdoc> /// Inherriting classes should override this method to respond to the /// splitterMoved event. This event occurs when the user finishes /// moving the splitter. /// </devdoc> protected virtual void OnSplitterMoved(SplitterEventArgs sevent) { SplitterEventHandler handler = (SplitterEventHandler)Events[EVENT_MOVED]; if (handler != null) handler(this,sevent); if (splitTarget != null) { SplitMove(sevent.SplitX, sevent.SplitY); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SetBoundsCore"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if (Horizontal) { if (width < 1) { width = 3; } splitterThickness = width; } else { if (height < 1) { height = 3; } splitterThickness = height; } base.SetBoundsCore(x, y, width, height, specified); } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitBegin"]/*' /> /// <devdoc> /// Begins the splitter moving. /// </devdoc> /// <internalonly/> private void SplitBegin(int x, int y) { SplitData spd = CalcSplitBounds(); if (spd.target != null && (minSize < maxSize)) { anchor = new Point(x, y); splitTarget = spd.target; splitSize = GetSplitSize(x, y); // SECREVIEW : We need a message filter to capture the ESC key // : to cancel the split action. // : The method PreFilterMessage is adorned with a LinkDemand. // IntSecurity.UnmanagedCode.Assert(); try { if (splitterMessageFilter != null) { splitterMessageFilter = new SplitterMessageFilter(this); } Application.AddMessageFilter(splitterMessageFilter); } finally { CodeAccessPermission.RevertAssert(); } CaptureInternal = true; DrawSplitBar(DRAW_START); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitEnd"]/*' /> /// <devdoc> /// Finishes the split movement. /// </devdoc> /// <internalonly/> private void SplitEnd(bool accept) { DrawSplitBar(DRAW_END); splitTarget = null; CaptureInternal = false; if (splitterMessageFilter != null) { Application.RemoveMessageFilter(splitterMessageFilter); splitterMessageFilter = null; } if (accept) { ApplySplitPosition(); } else if (splitSize != initTargetSize) { SplitPosition = initTargetSize; } anchor = Point.Empty; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ApplySplitPosition"]/*' /> /// <devdoc> /// Sets the split position to be the current split size. This is called /// by splitEdit /// </devdoc> /// <internalonly/> private void ApplySplitPosition() { SplitPosition = splitSize; } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitMove"]/*' /> /// <devdoc> /// Moves the splitter line to the splitSize for the mouse position /// (x, y). /// </devdoc> /// <internalonly/> private void SplitMove(int x, int y) { int size = GetSplitSize(x-Left+anchor.X, y-Top+anchor.Y); if (splitSize != size) { splitSize = size; DrawSplitBar(DRAW_MOVE); } } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.ToString"]/*' /> /// <devdoc> /// Returns a string representation for this control. /// </devdoc> /// <internalonly/> public override string ToString() { string s = base.ToString(); return s + ", MinExtra: " + MinExtra.ToString(CultureInfo.CurrentCulture) + ", MinSize: " + MinSize.ToString(CultureInfo.CurrentCulture); } /// <include file='doc\Splitter.uex' path='docs/doc[@for="Splitter.SplitData"]/*' /> /// <devdoc> /// Return value holder... /// </devdoc> private class SplitData { public int dockWidth = -1; public int dockHeight = -1; internal Control target; } private class SplitterMessageFilter : IMessageFilter { private Splitter owner = null; public SplitterMessageFilter(Splitter splitter) { this.owner = splitter; } /// <include file='doc\SplitterMessageFilter.uex' path='docs/doc[@for="SplitterMessageFilter.PreFilterMessage"]/*' /> /// <devdoc> /// </devdoc> /// <internalonly/> [ System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode), ] public bool PreFilterMessage(ref Message m) { if (m.Msg >= NativeMethods.WM_KEYFIRST && m.Msg <= NativeMethods.WM_KEYLAST) { if (m.Msg == NativeMethods.WM_KEYDOWN && unchecked((int)(long)m.WParam) == (int)Keys.Escape) { owner.SplitEnd(false); } return true; } return false; } } } }