context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace PdfSharp.Pdf.Filters
{
/// <summary>
/// Implements the ASCII85Decode filter.
/// </summary>
public class Ascii85Decode : Filter
{
// Reference: 3.3.2 ASCII85Decode Filter / Page 69
/// <summary>
/// Encodes the specified data.
/// </summary>
public override byte[] Encode(byte[] data)
{
if (data == null)
throw new ArgumentNullException("data");
int length = data.Length; // length == 0 is must not be treated as a special case.
int words = length / 4;
int rest = length - (words * 4);
byte[] result = new byte[words * 5 + (rest == 0 ? 0 : rest + 1) + 2];
int idxIn = 0, idxOut = 0;
int wCount = 0;
while (wCount < words)
{
uint val = ((uint)data[idxIn++] << 24) + ((uint)data[idxIn++] << 16) + ((uint)data[idxIn++] << 8) + data[idxIn++];
if (val == 0)
{
result[idxOut++] = (byte)'z';
}
else
{
byte c5 = (byte)(val % 85 + '!');
val /= 85;
byte c4 = (byte)(val % 85 + '!');
val /= 85;
byte c3 = (byte)(val % 85 + '!');
val /= 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
result[idxOut++] = c1;
result[idxOut++] = c2;
result[idxOut++] = c3;
result[idxOut++] = c4;
result[idxOut++] = c5;
}
wCount++;
}
if (rest == 1)
{
uint val = (uint)data[idxIn] << 24;
val /= 85 * 85 * 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
result[idxOut++] = c1;
result[idxOut++] = c2;
}
else if (rest == 2)
{
uint val = ((uint)data[idxIn++] << 24) + ((uint)data[idxIn] << 16);
val /= 85 * 85;
byte c3 = (byte)(val % 85 + '!');
val /= 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
result[idxOut++] = c1;
result[idxOut++] = c2;
result[idxOut++] = c3;
}
else if (rest == 3)
{
uint val = ((uint)data[idxIn++] << 24) + ((uint)data[idxIn++] << 16) + ((uint)data[idxIn] << 8);
val /= 85;
byte c4 = (byte)(val % 85 + '!');
val /= 85;
byte c3 = (byte)(val % 85 + '!');
val /= 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
result[idxOut++] = c1;
result[idxOut++] = c2;
result[idxOut++] = c3;
result[idxOut++] = c4;
}
result[idxOut++] = (byte)'~';
result[idxOut++] = (byte)'>';
if (idxOut < result.Length)
Array.Resize(ref result, idxOut);
return result;
}
/// <summary>
/// Decodes the specified data.
/// </summary>
public override byte[] Decode(byte[] data, FilterParms parms)
{
if (data == null)
throw new ArgumentNullException("data");
int idx;
int length = data.Length;
int zCount = 0;
int idxOut = 0;
for (idx = 0; idx < length; idx++)
{
char ch = (char)data[idx];
if (ch >= '!' && ch <= 'u')
data[idxOut++] = (byte)ch;
else if (ch == 'z')
{
data[idxOut++] = (byte)ch;
zCount++;
}
else if (ch == '~')
{
if ((char)data[idx + 1] != '>')
throw new ArgumentException("Illegal character.", "data");
break;
}
// ingnore unknown character
}
// Loop not ended with break?
if (idx == length)
throw new ArgumentException("Illegal character.", "data");
length = idxOut;
int nonZero = length - zCount;
int byteCount = 4 * (zCount + (nonZero / 5)); // full 4 byte blocks
int remainder = nonZero % 5;
if (remainder == 1)
throw new InvalidOperationException("Illegal character.");
if (remainder != 0)
byteCount += remainder - 1;
byte[] output = new byte[byteCount];
idxOut = 0;
idx = 0;
while (idx + 4 < length)
{
char ch = (char)data[idx];
if (ch == 'z')
{
idx++;
idxOut += 4;
}
else
{
// TODO: check
long value =
(long)(data[idx++] - '!') * (85 * 85 * 85 * 85) +
(uint)(data[idx++] - '!') * (85 * 85 * 85) +
(uint)(data[idx++] - '!') * (85 * 85) +
(uint)(data[idx++] - '!') * 85 +
(uint)(data[idx++] - '!');
if (value > UInt32.MaxValue)
throw new InvalidOperationException("Value of group greater than 2 power 32 - 1.");
output[idxOut++] = (byte)(value >> 24);
output[idxOut++] = (byte)(value >> 16);
output[idxOut++] = (byte)(value >> 8);
output[idxOut++] = (byte)value;
}
}
// I have found no appropriate algorithm, so I write my own. In some rare cases the value must not
// increased by one, but I cannot found a general formula or a proof.
// All possible cases are tested programmatically.
if (remainder == 2) // one byte
{
uint value =
(uint)(data[idx++] - '!') * (85 * 85 * 85 * 85) +
(uint)(data[idx] - '!') * (85 * 85 * 85);
// Always increase if not zero (tried out).
if (value != 0)
value += 0x01000000;
output[idxOut] = (byte)(value >> 24);
}
else if (remainder == 3) // two bytes
{
int idxIn = idx;
uint value =
(uint)(data[idx++] - '!') * (85 * 85 * 85 * 85) +
(uint)(data[idx++] - '!') * (85 * 85 * 85) +
(uint)(data[idx] - '!') * (85 * 85);
if (value != 0)
{
value &= 0xFFFF0000;
uint val = value / (85 * 85);
byte c3 = (byte)(val % 85 + '!');
val /= 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
if (c1 != data[idxIn] || c2 != data[idxIn + 1] || c3 != data[idxIn + 2])
{
value += 0x00010000;
//Count2++;
}
}
output[idxOut++] = (byte)(value >> 24);
output[idxOut] = (byte)(value >> 16);
}
else if (remainder == 4) // three bytes
{
int idxIn = idx;
uint value =
(uint)(data[idx++] - '!') * (85 * 85 * 85 * 85) +
(uint)(data[idx++] - '!') * (85 * 85 * 85) +
(uint)(data[idx++] - '!') * (85 * 85) +
(uint)(data[idx] - '!') * 85;
if (value != 0)
{
value &= 0xFFFFFF00;
uint val = value / 85;
byte c4 = (byte)(val % 85 + '!');
val /= 85;
byte c3 = (byte)(val % 85 + '!');
val /= 85;
byte c2 = (byte)(val % 85 + '!');
val /= 85;
byte c1 = (byte)(val + '!');
if (c1 != data[idxIn] || c2 != data[idxIn + 1] || c3 != data[idxIn + 2] || c4 != data[idxIn + 3])
{
value += 0x00000100;
//Count3++;
}
}
output[idxOut++] = (byte)(value >> 24);
output[idxOut++] = (byte)(value >> 16);
output[idxOut] = (byte)(value >> 8);
}
return output;
}
}
}
| |
//
// TrackInfoDisplay.cs
//
// Author:
// Aaron Bockover <[email protected]>
// Larry Ewing <[email protected]> (Is my hero)
//
// Copyright (C) 2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using Mono.Unix;
using Gtk;
using Cairo;
using Hyena;
using Hyena.Gui;
using Hyena.Gui.Theatrics;
using Banshee.Base;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.ServiceStack;
using Banshee.MediaEngine;
namespace Banshee.Gui.Widgets
{
public abstract class TrackInfoDisplay : Widget
{
private string current_artwork_id;
private ArtworkManager artwork_manager;
protected ArtworkManager ArtworkManager {
get { return artwork_manager; }
}
private ImageSurface current_image;
protected ImageSurface CurrentImage {
get { return current_image; }
}
private ImageSurface incoming_image;
protected ImageSurface IncomingImage {
get { return incoming_image; }
}
protected string MissingAudioIconName { get; set; }
protected string MissingVideoIconName { get; set; }
private ImageSurface missing_audio_image;
protected ImageSurface MissingAudioImage {
get { return missing_audio_image ?? (missing_audio_image
= PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingAudioIconName), true)); }
}
private ImageSurface missing_video_image;
protected ImageSurface MissingVideoImage {
get { return missing_video_image ?? (missing_video_image
= PixbufImageSurface.Create (IconThemeUtils.LoadIcon (MissingIconSizeRequest, MissingVideoIconName), true)); }
}
protected virtual Cairo.Color BackgroundColor { get; set; }
private Cairo.Color text_color;
protected virtual Cairo.Color TextColor {
get { return text_color; }
}
private Cairo.Color text_light_color;
protected virtual Cairo.Color TextLightColor {
get { return text_light_color; }
}
private TrackInfo current_track;
protected TrackInfo CurrentTrack {
get { return current_track; }
}
private TrackInfo incoming_track;
protected TrackInfo IncomingTrack {
get { return incoming_track; }
}
private uint idle_timeout_id = 0;
private SingleActorStage stage = new SingleActorStage ();
protected TrackInfoDisplay (IntPtr native) : base (native)
{
}
public TrackInfoDisplay ()
{
MissingAudioIconName = "audio-x-generic";
MissingVideoIconName = "video-x-generic";
stage.Iteration += OnStageIteration;
if (ServiceManager.Contains<ArtworkManager> ()) {
artwork_manager = ServiceManager.Get<ArtworkManager> ();
}
Connected = true;
WidgetFlags |= WidgetFlags.NoWindow;
}
private bool connected;
public bool Connected {
get { return connected; }
set {
if (value == connected)
return;
if (ServiceManager.PlayerEngine != null) {
connected = value;
if (value) {
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent,
PlayerEvent.StartOfStream |
PlayerEvent.TrackInfoUpdated |
PlayerEvent.StateChange);
} else {
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
}
}
}
}
public static Widget GetEditable (TrackInfoDisplay display)
{
return CoverArtEditor.For (display,
(x, y) => display.IsWithinCoverart (x, y),
() => display.CurrentTrack,
() => {}
);
}
public override void Dispose ()
{
if (idle_timeout_id > 0) {
GLib.Source.Remove (idle_timeout_id);
}
Connected = false;
stage.Iteration -= OnStageIteration;
stage = null;
InvalidateCache ();
base.Dispose ();
}
protected override void OnRealized ()
{
GdkWindow = Parent.GdkWindow;
base.OnRealized ();
}
protected override void OnUnrealized ()
{
base.OnUnrealized ();
InvalidateCache ();
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
ResetMissingImages ();
if (current_track == null) {
LoadCurrentTrack ();
} else {
Invalidate ();
}
}
protected override void OnStyleSet (Style previous)
{
base.OnStyleSet (previous);
text_color = CairoExtensions.GdkColorToCairoColor (Style.Foreground (StateType.Normal));
BackgroundColor = CairoExtensions.GdkColorToCairoColor (Style.Background (StateType.Normal));
text_light_color = Hyena.Gui.Theming.GtkTheme.GetCairoTextMidColor (this);
ResetMissingImages ();
OnThemeChanged ();
}
private void ResetMissingImages ()
{
if (missing_audio_image != null) {
((IDisposable)missing_audio_image).Dispose ();
var disposed = missing_audio_image;
missing_audio_image = null;
if (current_image == disposed) {
current_image = MissingAudioImage;
}
if (incoming_image == disposed) {
incoming_image = MissingAudioImage;
}
}
if (missing_video_image != null) {
((IDisposable)missing_video_image).Dispose ();
var disposed = missing_video_image;
missing_video_image = null;
if (current_image == disposed) {
current_image = MissingVideoImage;
}
if (incoming_image == disposed) {
incoming_image = MissingVideoImage;
}
}
}
protected virtual void OnThemeChanged ()
{
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
bool idle = incoming_track == null && current_track == null;
if (!Visible || !IsMapped || (idle && !CanRenderIdle)) {
return true;
}
Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window);
foreach (Gdk.Rectangle damage in evnt.Region.GetRectangles ()) {
cr.Rectangle (damage.X, damage.Y, damage.Width, damage.Height);
cr.Clip ();
if (idle) {
RenderIdle (cr);
} else {
RenderAnimation (cr);
}
cr.ResetClip ();
}
CairoExtensions.DisposeContext (cr);
return true;
}
protected virtual bool CanRenderIdle {
get { return false; }
}
protected virtual void RenderIdle (Cairo.Context cr)
{
}
private void RenderAnimation (Cairo.Context cr)
{
if (stage.Actor == null) {
// We are not in a transition, just render
RenderStage (cr, current_track, current_image);
return;
}
if (current_track == null) {
// Fade in the whole stage, nothing to fade out
CairoExtensions.PushGroup (cr);
RenderStage (cr, incoming_track, incoming_image);
CairoExtensions.PopGroupToSource (cr);
cr.PaintWithAlpha (stage.Actor.Percent);
return;
}
// Draw the old cover art more and more translucent
CairoExtensions.PushGroup (cr);
RenderCoverArt (cr, current_image);
CairoExtensions.PopGroupToSource (cr);
cr.PaintWithAlpha (1.0 - stage.Actor.Percent);
// Draw the new cover art more and more opaque
CairoExtensions.PushGroup (cr);
RenderCoverArt (cr, incoming_image);
CairoExtensions.PopGroupToSource (cr);
cr.PaintWithAlpha (stage.Actor.Percent);
bool same_artist_album = incoming_track != null ? incoming_track.ArtistAlbumEqual (current_track) : false;
bool same_track = incoming_track != null ? incoming_track.Equals (current_track) : false;
if (same_artist_album) {
RenderTrackInfo (cr, incoming_track, same_track, true);
}
// Don't xfade the text since it'll look bad (overlapping words); instead, fade
// the old out, and then the new in
if (stage.Actor.Percent <= 0.5) {
// Fade out old text
CairoExtensions.PushGroup (cr);
RenderTrackInfo (cr, current_track, !same_track, !same_artist_album);
CairoExtensions.PopGroupToSource (cr);
cr.PaintWithAlpha (1.0 - (stage.Actor.Percent * 2.0));
} else {
// Fade in new text
CairoExtensions.PushGroup (cr);
RenderTrackInfo (cr, incoming_track, !same_track, !same_artist_album);
CairoExtensions.PopGroupToSource (cr);
cr.PaintWithAlpha ((stage.Actor.Percent - 0.5) * 2.0);
}
}
private void RenderStage (Cairo.Context cr, TrackInfo track, ImageSurface image)
{
RenderCoverArt (cr, image);
RenderTrackInfo (cr, track, true, true);
}
protected virtual void RenderCoverArt (Cairo.Context cr, ImageSurface image)
{
ArtworkRenderer.RenderThumbnail (cr, image, false,
Allocation.X, Allocation.Y + ArtworkOffset,
ArtworkSizeRequest, ArtworkSizeRequest,
!IsMissingImage (image), 0.0,
IsMissingImage (image), BackgroundColor);
}
protected virtual bool IsWithinCoverart (int x, int y)
{
return x >= 0 &&
y >= ArtworkOffset &&
x <= ArtworkSizeRequest &&
y <= (ArtworkOffset + ArtworkSizeRequest);
}
protected bool IsMissingImage (ImageSurface pb)
{
return pb == missing_audio_image || pb == missing_video_image;
}
protected virtual void InvalidateCache ()
{
}
protected abstract void RenderTrackInfo (Cairo.Context cr, TrackInfo track, bool renderTrack, bool renderArtistAlbum);
private int ArtworkOffset {
get { return (Allocation.Height - ArtworkSizeRequest) / 2; }
}
protected virtual int ArtworkSizeRequest {
get { return Allocation.Height; }
}
protected virtual int MissingIconSizeRequest {
get { return ArtworkSizeRequest; }
}
private void OnPlayerEvent (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.StartOfStream) {
LoadCurrentTrack ();
} else if (args.Event == PlayerEvent.TrackInfoUpdated) {
LoadCurrentTrack (true);
} else if (args.Event == PlayerEvent.StateChange && (incoming_track != null || incoming_image != null)) {
PlayerEventStateChangeArgs state = (PlayerEventStateChangeArgs)args;
if (state.Current == PlayerState.Idle) {
if (idle_timeout_id > 0) {
GLib.Source.Remove (idle_timeout_id);
} else {
GLib.Timeout.Add (100, IdleTimeout);
}
}
}
}
private bool IdleTimeout ()
{
if (ServiceManager.PlayerEngine == null ||
ServiceManager.PlayerEngine.CurrentTrack == null ||
ServiceManager.PlayerEngine.CurrentState == PlayerState.Idle) {
incoming_track = null;
incoming_image = null;
current_artwork_id = null;
if (stage != null && stage.Actor == null) {
stage.Reset ();
}
}
idle_timeout_id = 0;
return false;
}
private void LoadCurrentTrack ()
{
LoadCurrentTrack (false);
}
private void LoadCurrentTrack (bool force_reload)
{
TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack;
if (track == current_track && !IsMissingImage (current_image) && !force_reload) {
return;
} else if (track == null) {
incoming_track = null;
incoming_image = null;
return;
}
incoming_track = track;
LoadImage (track, force_reload);
if (stage.Actor == null) {
stage.Reset ();
}
}
private void LoadImage (TrackInfo track, bool force)
{
LoadImage (track.MediaAttributes, track.ArtworkId, force);
if (track == current_track) {
if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) {
((IDisposable)current_image).Dispose ();
}
current_image = incoming_image;
}
}
protected void LoadImage (TrackMediaAttributes attr, string artwork_id, bool force)
{
if (current_artwork_id != artwork_id || force) {
current_artwork_id = artwork_id;
if (incoming_image != null && current_image != incoming_image && !IsMissingImage (incoming_image)) {
((IDisposable)incoming_image).Dispose ();
}
incoming_image = artwork_manager.LookupScaleSurface (artwork_id, ArtworkSizeRequest);
}
if (incoming_image == null) {
incoming_image = MissingImage ((attr & TrackMediaAttributes.VideoStream) != 0);
}
}
private ImageSurface MissingImage (bool is_video)
{
return is_video ? MissingVideoImage : MissingAudioImage;
}
private double last_fps = 0.0;
private void OnStageIteration (object o, EventArgs args)
{
Invalidate ();
if (stage.Actor != null) {
last_fps = stage.Actor.FramesPerSecond;
return;
}
InvalidateCache ();
if (ApplicationContext.Debugging) {
Log.DebugFormat ("TrackInfoDisplay RenderAnimation: {0:0.00} FPS", last_fps);
}
if (current_image != null && current_image != incoming_image && !IsMissingImage (current_image)) {
((IDisposable)current_image).Dispose ();
}
current_image = incoming_image;
current_track = incoming_track;
incoming_track = null;
OnArtworkChanged ();
}
protected virtual void Invalidate ()
{
QueueDraw ();
}
protected virtual void OnArtworkChanged ()
{
}
protected virtual string GetFirstLineText (TrackInfo track)
{
return String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (track.DisplayTrackTitle));
}
protected virtual string GetSecondLineText (TrackInfo track)
{
string markup = null;
Banshee.Streaming.RadioTrackInfo radio_track = track as Banshee.Streaming.RadioTrackInfo;
if ((track.MediaAttributes & TrackMediaAttributes.Podcast) != 0) {
// Translators: {0} and {1} are for markup so ignore them, {2} and {3}
// are Podcast Name and Published Date, respectively;
// e.g. 'from BBtv published 7/26/2007'
markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2} {0}published{1} {3}"),
track.DisplayAlbumTitle, track.ReleaseDate.ToShortDateString ());
} else if (radio_track != null && radio_track.ParentTrack != null) {
// This is complicated because some radio streams send tags when the song changes, and we
// want to display them if they do. But if they don't, we want it to look good too, so we just
// display the station name for the second line.
string by_from = GetByFrom (
track.ArtistName == radio_track.ParentTrack.ArtistName ? null : track.ArtistName, track.DisplayArtistName,
track.AlbumTitle == radio_track.ParentTrack.AlbumTitle ? null : track.AlbumTitle, track.DisplayAlbumTitle, false
);
if (String.IsNullOrEmpty (by_from)) {
// simply: "Chicago Public Radio" or whatever the artist name is
markup = GLib.Markup.EscapeText (radio_track.ParentTrack.ArtistName ?? Catalog.GetString ("Unknown Stream"));
} else {
// Translators: {0} and {1} are markup so ignore them, {2} is the name of the radio station
string on = MarkupFormat (Catalog.GetString ("{0}on{1} {2}"), radio_track.ParentTrack.TrackTitle);
// Translators: {0} is the "from {album} by {artist}" type string, and {1} is the "on {radio station name}" string
markup = String.Format (Catalog.GetString ("{0} {1}"), by_from, on);
}
} else {
markup = GetByFrom (track.ArtistName, track.DisplayArtistName, track.AlbumTitle, track.DisplayAlbumTitle, true);
}
return String.Format ("<span color=\"{0}\">{1}</span>",
CairoExtensions.ColorGetHex (TextColor, false),
markup);
}
private string MarkupFormat (string fmt, params string [] args)
{
string [] new_args = new string [args.Length + 2];
new_args[0] = String.Format ("<span color=\"{0}\" size=\"small\">",
CairoExtensions.ColorGetHex (TextLightColor, false));
new_args[1] = "</span>";
for (int i = 0; i < args.Length; i++) {
new_args[i + 2] = GLib.Markup.EscapeText (args[i]);
}
return String.Format (fmt, new_args);
}
private string GetByFrom (string artist, string display_artist, string album, string display_album, bool unknown_ok)
{
bool has_artist = !String.IsNullOrEmpty (artist);
bool has_album = !String.IsNullOrEmpty (album);
string markup = null;
if (has_artist && has_album) {
// Translators: {0} and {1} are for markup so ignore them, {2} and {3}
// are Artist Name and Album Title, respectively;
// e.g. 'by Parkway Drive from Killing with a Smile'
markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2} {0}from{1} {3}"), display_artist, display_album);
} else if (has_album) {
// Translators: {0} and {1} are for markup so ignore them, {2} is for Album Title;
// e.g. 'from Killing with a Smile'
markup = MarkupFormat (Catalog.GetString ("{0}from{1} {2}"), display_album);
} else if (has_artist || unknown_ok) {
// Translators: {0} and {1} are for markup so ignore them, {2} is for Artist Name;
// e.g. 'by Parkway Drive'
markup = MarkupFormat (Catalog.GetString ("{0}by{1} {2}"), display_artist);
}
return markup;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Xml;
using System.Text;
using System.Linq;
namespace UnityEditor.FacebookEditor
{
public class ManifestMod
{
public const string DeepLinkingActivityName = "com.facebook.unity.FBUnityDeepLinkingActivity";
public const string LoginActivityName = "com.facebook.LoginActivity";
public const string UnityLoginActivityName = "com.facebook.unity.FBUnityLoginActivity";
public const string ApplicationIdMetaDataName = "com.facebook.sdk.ApplicationId";
public static void GenerateManifest()
{
var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
// only copy over a fresh copy of the AndroidManifest if one does not exist
if (!File.Exists(outputFile))
{
var inputFile = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines/androidplayer/AndroidManifest.xml");
File.Copy(inputFile, outputFile);
}
UpdateManifest(outputFile);
}
public static bool CheckManifest()
{
bool result = true;
var outputFile = Path.Combine(Application.dataPath, "Plugins/Android/AndroidManifest.xml");
if (!File.Exists(outputFile))
{
Debug.LogError("An android manifest must be generated for the Facebook SDK to work. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\"");
return false;
}
XmlDocument doc = new XmlDocument();
doc.Load(outputFile);
if (doc == null)
{
Debug.LogError("Couldn't load " + outputFile);
return false;
}
XmlNode manNode = FindChildNode(doc, "manifest");
XmlNode dict = FindChildNode(manNode, "application");
if (dict == null)
{
Debug.LogError("Error parsing " + outputFile);
return false;
}
string ns = dict.GetNamespaceOfPrefix("android");
XmlElement loginElement = FindElementWithAndroidName("activity", "name", ns, UnityLoginActivityName, dict);
if (loginElement == null)
{
Debug.LogError(string.Format("{0} is missing from your android manifest. Go to Facebook->Edit Settings and press \"Regenerate Android Manifest\"", LoginActivityName));
result = false;
}
var deprecatedMainActivityName = "com.facebook.unity.FBUnityPlayerActivity";
XmlElement deprecatedElement = FindElementWithAndroidName("activity", "name", ns, deprecatedMainActivityName, dict);
if (deprecatedElement != null)
{
Debug.LogWarning(string.Format("{0} is deprecated and no longer needed for the Facebook SDK. Feel free to use your own main activity or use the default \"com.unity3d.player.UnityPlayerNativeActivity\"", deprecatedMainActivityName));
}
return result;
}
private static XmlNode FindChildNode(XmlNode parent, string name)
{
XmlNode curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(name))
{
return curr;
}
curr = curr.NextSibling;
}
return null;
}
private static XmlElement FindElementWithAndroidName(string name, string androidName, string ns, string value, XmlNode parent)
{
var curr = parent.FirstChild;
while (curr != null)
{
if (curr.Name.Equals(name) && curr is XmlElement && ((XmlElement)curr).GetAttribute(androidName, ns) == value)
{
return curr as XmlElement;
}
curr = curr.NextSibling;
}
return null;
}
public static void UpdateManifest(string fullPath)
{
string appId = FBSettings.AppId;
if (!FBSettings.IsValidAppId)
{
Debug.LogError("You didn't specify a Facebook app ID. Please add one using the Facebook menu in the main Unity editor.");
return;
}
XmlDocument doc = new XmlDocument();
doc.Load(fullPath);
if (doc == null)
{
Debug.LogError("Couldn't load " + fullPath);
return;
}
XmlNode manNode = FindChildNode(doc, "manifest");
XmlNode dict = FindChildNode(manNode, "application");
if (dict == null)
{
Debug.LogError("Error parsing " + fullPath);
return;
}
string ns = dict.GetNamespaceOfPrefix("android");
//add the unity login activity
XmlElement unityLoginElement = FindElementWithAndroidName("activity", "name", ns, UnityLoginActivityName, dict);
if (unityLoginElement == null)
{
unityLoginElement = CreateUnityLoginElement(doc, ns);
dict.AppendChild(unityLoginElement);
}
//add the login activity
XmlElement loginElement = FindElementWithAndroidName("activity", "name", ns, LoginActivityName, dict);
if (loginElement == null)
{
loginElement = CreateLoginElement(doc, ns);
dict.AppendChild(loginElement);
}
//add deep linking activity
XmlElement deepLinkingElement = FindElementWithAndroidName("activity", "name", ns, DeepLinkingActivityName, dict);
if (deepLinkingElement == null)
{
deepLinkingElement = CreateDeepLinkingElement(doc, ns);
dict.AppendChild(deepLinkingElement);
}
//add the app id
//<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="\ 409682555812308" />
XmlElement appIdElement = FindElementWithAndroidName("meta-data", "name", ns, ApplicationIdMetaDataName, dict);
if (appIdElement == null)
{
appIdElement = doc.CreateElement("meta-data");
appIdElement.SetAttribute("name", ns, ApplicationIdMetaDataName);
dict.AppendChild(appIdElement);
}
appIdElement.SetAttribute("value", ns, "\\ " + appId); //stupid hack so that the id comes out as a string
doc.Save(fullPath);
}
private static XmlElement CreateLoginElement(XmlDocument doc, string ns)
{
//<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
//</activity>
XmlElement activityElement = doc.CreateElement("activity");
activityElement.SetAttribute("name", ns, LoginActivityName);
activityElement.SetAttribute("screenOrientation", ns, "portrait");
activityElement.SetAttribute("configChanges", ns, "keyboardHidden|orientation");
activityElement.SetAttribute("theme", ns, "@android:style/Theme.Translucent.NoTitleBar.Fullscreen");
activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy
return activityElement;
}
private static XmlElement CreateDeepLinkingElement(XmlDocument doc, string ns)
{
//<activity android:name="com.facebook.unity.FBDeepLinkingActivity" android:exported="true">
//</activity>
XmlElement activityElement = doc.CreateElement("activity");
activityElement.SetAttribute("name", ns, DeepLinkingActivityName);
activityElement.SetAttribute("exported", ns, "true");
activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy
return activityElement;
}
private static XmlElement CreateUnityLoginElement(XmlDocument doc, string ns)
{
//<activity android:name="com.facebook.unity.FBUnityLoginActivity" android:configChanges="all|of|them" android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen">
//</activity>
XmlElement activityElement = doc.CreateElement("activity");
activityElement.SetAttribute("name", ns, UnityLoginActivityName);
activityElement.SetAttribute("configChanges", ns, "fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen");
activityElement.SetAttribute("theme", ns, "@android:style/Theme.Translucent.NoTitleBar.Fullscreen");
activityElement.InnerText = "\n "; //be extremely anal to make diff tools happy
return activityElement;
}
}
}
| |
//
// Mono.System.Xml.XmlParserInput
//
// Author:
// Atsushi Enomoto ([email protected])
//
// (C)2003 Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Text;
using Mono.System.Xml;
using System.Globalization;
using Mono.Xml;
namespace Mono.System.Xml
{
internal class XmlParserInput
{
class XmlParserInputSource
{
public readonly string BaseURI;
readonly TextReader reader;
public int state;
public bool isPE;
int line;
int column;
public XmlParserInputSource (
TextReader reader, string baseUri, bool pe,
int line, int column)
{
BaseURI = baseUri;
this.reader = reader;
this.isPE = pe;
this.line = line;
this.column = column;
}
public int LineNumber {
get { return line; }
}
public int LinePosition {
get { return column; }
}
public void Close ()
{
reader.Close ();
}
public int Read ()
{
if (state == 2)
return -1;
if (isPE && state == 0) {
state = 1;
return ' ';
}
int v = reader.Read ();
if (v == '\n') {
line++;
column = 1;
} else if (v >= 0) {
column++;
}
if (v < 0 && state == 1) {
state = 2;
return ' ';
}
return v;
}
}
#region ctor
public XmlParserInput (TextReader reader, string baseURI)
: this (reader, baseURI, 1, 0)
{
}
public XmlParserInput (TextReader reader, string baseURI, int line, int column)
{
this.source = new XmlParserInputSource (reader, baseURI, false, line, column);
}
#endregion
#region Public Methods
// Read the next character and compare it against the
// specified character.
public void Close ()
{
while (sourceStack.Count > 0)
((XmlParserInputSource) sourceStack.Pop ()).Close ();
source.Close ();
}
public void Expect (int expected)
{
int ch = ReadChar ();
if (ch != expected) {
throw ReaderError (
String.Format (CultureInfo.InvariantCulture,
"expected '{0}' ({1:X}) but found '{2}' ({3:X})",
(char)expected,
expected,
(char)ch,
ch));
}
}
public void Expect (string expected)
{
int len = expected.Length;
for(int i=0; i< len; i++)
Expect (expected[i]);
}
public void PushPEBuffer (DTDParameterEntityDeclaration pe)
{
sourceStack.Push (source);
source = new XmlParserInputSource (
new StringReader (pe.ReplacementText),
pe.ActualUri, true, 1, 0);
}
private int ReadSourceChar ()
{
int v = source.Read ();
while (v < 0 && sourceStack.Count > 0) {
source = sourceStack.Pop () as XmlParserInputSource;
v = source.Read ();
}
return v;
}
public int PeekChar ()
{
if (has_peek)
return peek_char;
peek_char = ReadSourceChar ();
if (peek_char >= 0xD800 && peek_char <= 0xDBFF) {
peek_char = 0x10000+((peek_char-0xD800)<<10);
int i = ReadSourceChar ();
if (i >= 0xDC00 && i <= 0xDFFF)
peek_char += (i-0xDC00);
}
has_peek = true;
return peek_char;
}
public int ReadChar ()
{
int ch;
ch = PeekChar ();
has_peek = false;
return ch;
}
#endregion
#region Public Properties
public string BaseURI {
get { return source.BaseURI; }
}
public bool HasPEBuffer {
get { return sourceStack.Count > 0; }
}
public int LineNumber {
get { return source.LineNumber; }
}
public int LinePosition {
get { return source.LinePosition; }
}
public bool AllowTextDecl {
get { return allowTextDecl; }
set { allowTextDecl = value; }
}
#endregion
#region Privates
Stack sourceStack = new Stack ();
XmlParserInputSource source;
bool has_peek;
int peek_char;
bool allowTextDecl = true;
private XmlException ReaderError (string message)
{
return new XmlException (message, null, LineNumber, LinePosition);
}
#endregion
}
}
| |
//
// Mono.Xml.XPath.XPathEditableDocument
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// (C)2004 Novell Inc.
//
// Yet another implementation of editable XPathNavigator.
// (Even runnable under MS.NET 2.0)
//
// By rewriting XPathEditableDocument.CreateNavigator() as just to
// create XmlDocumentNavigator, XmlDocumentEditableNavigator could be used
// as to implement XmlDocument.CreateNavigator().
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Serialization;
namespace Mono.Xml.XPath
{
internal class XPathEditableDocument : IXPathNavigable
{
XmlNode node;
public XPathEditableDocument (XmlNode node)
{
this.node = node;
}
public XmlNode Node {
get { return node; }
}
public XPathNavigator CreateNavigator ()
{
return new XmlDocumentEditableNavigator (this);
}
}
internal delegate void XmlWriterClosedEventHandler (
XmlWriter writer);
internal class XmlDocumentInsertionWriter : XmlWriter
{
XmlNode parent;
XmlNode current;
XmlNode nextSibling;
WriteState state;
XmlAttribute attribute;
public XmlDocumentInsertionWriter (XmlNode owner, XmlNode nextSibling)
{
this.parent = (XmlNode) owner;
if (parent == null)
throw new InvalidOperationException ();
switch (parent.NodeType) {
case XmlNodeType.Document:
current = ((XmlDocument) parent).CreateDocumentFragment ();
break;
case XmlNodeType.DocumentFragment:
case XmlNodeType.Element:
current = parent.OwnerDocument.CreateDocumentFragment ();
break;
default:
throw new InvalidOperationException (String.Format ("Insertion into {0} node is not allowed.", parent.NodeType));
}
this.nextSibling = nextSibling;
state = WriteState.Content;
}
public override WriteState WriteState {
get { return state; }
}
public override void Close ()
{
while (current.ParentNode != null)
current = current.ParentNode;
parent.InsertBefore ((XmlDocumentFragment) current, nextSibling);
if (Closed != null)
Closed (this);
}
internal event XmlWriterClosedEventHandler Closed;
public override void Flush ()
{
}
public override string LookupPrefix (string ns)
{
return current.GetPrefixOfNamespace (ns);
}
public override void WriteStartAttribute (string prefix, string name, string ns)
{
if (state != WriteState.Content)
throw new InvalidOperationException ("Current state is not inside element. Cannot start attribute.");
if (prefix == null && ns != null && ns.Length > 0)
prefix = LookupPrefix (ns);
attribute = current.OwnerDocument.CreateAttribute (prefix, name, ns);
state = WriteState.Attribute;
}
public override void WriteProcessingInstruction (string name, string value)
{
XmlProcessingInstruction pi = current.OwnerDocument.CreateProcessingInstruction (name, value);
current.AppendChild (pi);
}
public override void WriteComment (string text)
{
XmlComment comment = current.OwnerDocument.CreateComment (text);
current.AppendChild (comment);
}
public override void WriteCData (string text)
{
XmlCDataSection cdata = current.OwnerDocument.CreateCDataSection (text);
current.AppendChild (cdata);
}
public override void WriteStartElement (string prefix, string name, string ns)
{
if (prefix == null && ns != null && ns.Length > 0)
prefix = LookupPrefix (ns);
XmlElement el = current.OwnerDocument.CreateElement (prefix, name, ns);
current.AppendChild (el);
current = el;
}
public override void WriteEndElement ()
{
current = current.ParentNode;
if (current == null)
throw new InvalidOperationException ("No element is opened.");
}
public override void WriteFullEndElement ()
{
XmlElement el = current as XmlElement;
if (el != null)
el.IsEmpty = false;
WriteEndElement ();
}
public override void WriteDocType (string name, string pubid, string systemId, string intsubset)
{
throw new NotSupportedException ();
}
public override void WriteStartDocument ()
{
throw new NotSupportedException ();
}
public override void WriteStartDocument (bool standalone)
{
throw new NotSupportedException ();
}
public override void WriteEndDocument ()
{
throw new NotSupportedException ();
}
public override void WriteBase64 (byte [] data, int start, int length)
{
WriteString (Convert.ToBase64String (data, start, length));
}
public override void WriteRaw (char [] raw, int start, int length)
{
throw new NotSupportedException ();
}
public override void WriteRaw (string raw)
{
XmlReader reader = new XmlTextReader(new System.IO.StringReader(raw));
WriteRaw(reader);
}
private void WriteRaw(XmlReader reader)
{
if (reader != null && reader.NodeType == XmlNodeType.Element)
{
WriteStartElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
WriteAttributes (reader, true);
WriteRaw (reader.ReadSubtree ());
WriteEndElement ();
}
}
public override void WriteSurrogateCharEntity (char msb, char lsb)
{
throw new NotSupportedException ();
}
public override void WriteCharEntity (char c)
{
throw new NotSupportedException ();
}
public override void WriteEntityRef (string entname)
{
if (state != WriteState.Attribute)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot write attribute value.");
attribute.AppendChild (attribute.OwnerDocument.CreateEntityReference (entname));
}
public override void WriteChars (char [] data, int start, int length)
{
WriteString (new string (data, start, length));
}
public override void WriteString (string text)
{
if (attribute != null)
attribute.Value += text;
else {
XmlText t = current.OwnerDocument.CreateTextNode (text);
current.AppendChild (t);
}
}
public override void WriteWhitespace (string text)
{
if (state != WriteState.Attribute)
current.AppendChild (current.OwnerDocument.CreateTextNode (text));
else if (attribute.ChildNodes.Count == 0)
attribute.AppendChild (attribute.OwnerDocument.CreateWhitespace (text));
else
attribute.Value += text;
}
public override void WriteEndAttribute ()
{
// when the writer is for AppendChild() and the root
// node is element, it allows to write attributes
// (IMHO incorrectly: isn't it append "child" ???)
XmlElement element = (current as XmlElement) ?? (nextSibling == null ? parent as XmlElement : null);
if (state != WriteState.Attribute || element == null)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot close attribute.");
element.SetAttributeNode (attribute);
attribute = null;
state = WriteState.Content;
}
}
internal class XmlDocumentAttributeWriter : XmlWriter
{
XmlElement element;
WriteState state;
XmlAttribute attribute;
public XmlDocumentAttributeWriter (XmlNode owner)
{
element = owner as XmlElement;
if (element == null)
throw new ArgumentException ("To write attributes, current node must be an element.");
state = WriteState.Content;
}
public override WriteState WriteState {
get { return state; }
}
public override void Close ()
{
}
public override void Flush ()
{
}
public override string LookupPrefix (string ns)
{
return element.GetPrefixOfNamespace (ns);
}
public override void WriteStartAttribute (string prefix, string name, string ns)
{
if (state != WriteState.Content)
throw new InvalidOperationException ("Current state is not inside element. Cannot start attribute.");
if (prefix == null && ns != null && ns.Length > 0)
prefix = LookupPrefix (ns);
attribute = element.OwnerDocument.CreateAttribute (prefix, name, ns);
state = WriteState.Attribute;
}
public override void WriteProcessingInstruction (string name, string value)
{
throw new NotSupportedException ();
}
public override void WriteComment (string text)
{
throw new NotSupportedException ();
}
public override void WriteCData (string text)
{
throw new NotSupportedException ();
}
public override void WriteStartElement (string prefix, string name, string ns)
{
throw new NotSupportedException ();
}
public override void WriteEndElement ()
{
throw new NotSupportedException ();
}
public override void WriteFullEndElement ()
{
throw new NotSupportedException ();
}
public override void WriteDocType (string name, string pubid, string systemId, string intsubset)
{
throw new NotSupportedException ();
}
public override void WriteStartDocument ()
{
throw new NotSupportedException ();
}
public override void WriteStartDocument (bool standalone)
{
throw new NotSupportedException ();
}
public override void WriteEndDocument ()
{
throw new NotSupportedException ();
}
public override void WriteBase64 (byte [] data, int start, int length)
{
throw new NotSupportedException ();
}
public override void WriteRaw (char [] raw, int start, int length)
{
throw new NotSupportedException ();
}
public override void WriteRaw (string raw)
{
throw new NotSupportedException ();
}
public override void WriteSurrogateCharEntity (char msb, char lsb)
{
throw new NotSupportedException ();
}
public override void WriteCharEntity (char c)
{
throw new NotSupportedException ();
}
public override void WriteEntityRef (string entname)
{
if (state != WriteState.Attribute)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot write attribute value.");
attribute.AppendChild (attribute.OwnerDocument.CreateEntityReference (entname));
}
public override void WriteChars (char [] data, int start, int length)
{
WriteString (new string (data, start, length));
}
public override void WriteString (string text)
{
if (state != WriteState.Attribute)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot write attribute value.");
attribute.Value += text;
}
public override void WriteWhitespace (string text)
{
if (state != WriteState.Attribute)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot write attribute value.");
if (attribute.ChildNodes.Count == 0)
attribute.AppendChild (attribute.OwnerDocument.CreateWhitespace (text));
else
attribute.Value += text;
}
public override void WriteEndAttribute ()
{
if (state != WriteState.Attribute)
throw new InvalidOperationException ("Current state is not inside attribute. Cannot close attribute.");
element.SetAttributeNode (attribute);
attribute = null;
state = WriteState.Content;
}
}
internal class XmlDocumentEditableNavigator : XPathNavigator, IHasXmlNode
{
static readonly bool isXmlDocumentNavigatorImpl;
static XmlDocumentEditableNavigator ()
{
isXmlDocumentNavigatorImpl =
(typeof (XmlDocumentEditableNavigator).Assembly
== typeof (XmlDocument).Assembly);
}
XPathEditableDocument document;
XPathNavigator navigator;
public XmlDocumentEditableNavigator (XPathEditableDocument doc)
{
document = doc;
if (isXmlDocumentNavigatorImpl)
navigator = new XmlDocumentNavigator (doc.Node);
else
navigator = doc.CreateNavigator ();
}
public XmlDocumentEditableNavigator (XmlDocumentEditableNavigator nav)
{
document = nav.document;
navigator = nav.navigator.Clone ();
}
public override string BaseURI {
get { return navigator.BaseURI; }
}
public override bool CanEdit {
get { return true; }
}
public override bool IsEmptyElement {
get { return navigator.IsEmptyElement; }
}
public override string LocalName {
get { return navigator.LocalName; }
}
public override XmlNameTable NameTable {
get { return navigator.NameTable; }
}
public override string Name {
get { return navigator.Name; }
}
public override string NamespaceURI {
get { return navigator.NamespaceURI; }
}
public override XPathNodeType NodeType {
get { return navigator.NodeType; }
}
public override string Prefix {
get { return navigator.Prefix; }
}
public override IXmlSchemaInfo SchemaInfo {
get { return navigator.SchemaInfo; }
}
public override object UnderlyingObject {
get { return navigator.UnderlyingObject; }
}
public override string Value {
get { return navigator.Value; }
}
public override string XmlLang {
get { return navigator.XmlLang; }
}
public override bool HasChildren {
get { return navigator.HasChildren; }
}
public override bool HasAttributes {
get { return navigator.HasAttributes; }
}
public override XPathNavigator Clone ()
{
return new XmlDocumentEditableNavigator (this);
}
public override XPathNavigator CreateNavigator ()
{
return Clone ();
}
public XmlNode GetNode ()
{
return ((IHasXmlNode) navigator).GetNode ();
}
public override bool IsSamePosition (XPathNavigator other)
{
XmlDocumentEditableNavigator nav = other as XmlDocumentEditableNavigator;
if (nav != null)
return navigator.IsSamePosition (nav.navigator);
else
return navigator.IsSamePosition (nav);
}
public override bool MoveTo (XPathNavigator other)
{
XmlDocumentEditableNavigator nav = other as XmlDocumentEditableNavigator;
if (nav != null)
return navigator.MoveTo (nav.navigator);
else
return navigator.MoveTo (nav);
}
public override bool MoveToFirstAttribute ()
{
return navigator.MoveToFirstAttribute ();
}
public override bool MoveToFirstChild ()
{
return navigator.MoveToFirstChild ();
}
public override bool MoveToFirstNamespace (XPathNamespaceScope scope)
{
return navigator.MoveToFirstNamespace (scope);
}
public override bool MoveToId (string id)
{
return navigator.MoveToId (id);
}
public override bool MoveToNext ()
{
return navigator.MoveToNext ();
}
public override bool MoveToNextAttribute ()
{
return navigator.MoveToNextAttribute ();
}
public override bool MoveToNextNamespace (XPathNamespaceScope scope)
{
return navigator.MoveToNextNamespace (scope);
}
public override bool MoveToParent ()
{
return navigator.MoveToParent ();
}
public override bool MoveToPrevious ()
{
return navigator.MoveToPrevious ();
}
public override XmlWriter AppendChild ()
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
if (n == null)
throw new InvalidOperationException ("Should not happen.");
return new XmlDocumentInsertionWriter (n, null);
}
public override void DeleteRange (XPathNavigator lastSiblingToDelete)
{
if (lastSiblingToDelete == null)
throw new ArgumentNullException ();
XmlNode start = ((IHasXmlNode) navigator).GetNode ();
XmlNode end = null;
if (lastSiblingToDelete is IHasXmlNode)
end = ((IHasXmlNode) lastSiblingToDelete).GetNode ();
// After removal, it moves to parent node.
if (!navigator.MoveToParent ())
throw new InvalidOperationException ("There is no parent to remove current node.");
if (end == null || start.ParentNode != end.ParentNode)
throw new InvalidOperationException ("Argument XPathNavigator has different parent node.");
XmlNode parent = start.ParentNode;
XmlNode next;
bool loop = true;
for (XmlNode n = start; loop; n = next) {
loop = n != end;
next = n.NextSibling;
parent.RemoveChild (n);
}
}
public override XmlWriter ReplaceRange (XPathNavigator nav)
{
if (nav == null)
throw new ArgumentNullException ();
XmlNode start = ((IHasXmlNode) navigator).GetNode ();
XmlNode end = null;
if (nav is IHasXmlNode)
end = ((IHasXmlNode) nav).GetNode ();
if (end == null || start.ParentNode != end.ParentNode)
throw new InvalidOperationException ("Argument XPathNavigator has different parent node.");
XmlDocumentInsertionWriter w =
(XmlDocumentInsertionWriter) InsertBefore ();
// local variables to anonymous delegate
XPathNavigator prev = Clone ();
if (!prev.MoveToPrevious ())
prev = null;
XPathNavigator parentNav = Clone ();
parentNav.MoveToParent ();
w.Closed += delegate (XmlWriter writer) {
XmlNode parent = start.ParentNode;
XmlNode next;
bool loop = true;
for (XmlNode n = start; loop; n = next) {
loop = n != end;
next = n.NextSibling;
parent.RemoveChild (n);
}
if (prev != null) {
MoveTo (prev);
MoveToNext ();
} else {
MoveTo (parentNav);
MoveToFirstChild ();
}
};
return w;
}
public override XmlWriter InsertBefore ()
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
return new XmlDocumentInsertionWriter (n.ParentNode, n);
}
public override XmlWriter CreateAttributes ()
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
return new XmlDocumentAttributeWriter (n);
}
public override void DeleteSelf ()
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
XmlAttribute a = n as XmlAttribute;
if (a != null) {
if (a.OwnerElement == null)
throw new InvalidOperationException ("This attribute node cannot be removed since it has no owner element.");
navigator.MoveToParent ();
a.OwnerElement.RemoveAttributeNode (a);
} else {
if (n.ParentNode == null)
throw new InvalidOperationException ("This node cannot be removed since it has no parent.");
navigator.MoveToParent ();
n.ParentNode.RemoveChild (n);
}
}
public override void ReplaceSelf (XmlReader reader)
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
XmlNode p = n.ParentNode;
if (p == null)
throw new InvalidOperationException ("This node cannot be removed since it has no parent.");
bool movenext = false;
if (!MoveToPrevious ())
MoveToParent ();
else
movenext = true;
XmlDocument doc = p.NodeType == XmlNodeType.Document ?
p as XmlDocument : p.OwnerDocument;
bool error = false;
if (reader.ReadState == ReadState.Initial) {
reader.Read ();
if (reader.EOF)
error = true;
else
while (!reader.EOF)
p.AppendChild (doc.ReadNode (reader));
} else {
if (reader.EOF)
error = true;
else
p.AppendChild (doc.ReadNode (reader));
}
if (error)
throw new InvalidOperationException ("Content is required in argument XmlReader to replace current node.");
p.RemoveChild (n);
if (movenext)
MoveToNext ();
else
MoveToFirstChild ();
}
public override void SetValue (string value)
{
XmlNode n = ((IHasXmlNode) navigator).GetNode ();
while (n.FirstChild != null)
n.RemoveChild (n.FirstChild);
n.InnerText = value;
}
public override void MoveToRoot ()
{
navigator.MoveToRoot ();
}
public override bool MoveToNamespace (string name)
{
return navigator.MoveToNamespace (name);
}
public override bool MoveToFirst ()
{
return navigator.MoveToFirst ();
}
public override bool MoveToAttribute (string localName, string namespaceURI)
{
return navigator.MoveToAttribute (localName, namespaceURI);
}
public override bool IsDescendant (XPathNavigator nav)
{
XmlDocumentEditableNavigator e = nav as XmlDocumentEditableNavigator;
if (e != null)
return navigator.IsDescendant (e.navigator);
else
return navigator.IsDescendant (nav);
}
public override string GetNamespace (string name)
{
return navigator.GetNamespace (name);
}
public override string GetAttribute (string localName, string namespaceURI)
{
return navigator.GetAttribute (localName, namespaceURI);
}
public override XmlNodeOrder ComparePosition (XPathNavigator nav)
{
XmlDocumentEditableNavigator e = nav as XmlDocumentEditableNavigator;
if (e != null)
return navigator.ComparePosition (e.navigator);
else
return navigator.ComparePosition (nav);
}
}
}
#endif
| |
namespace System.IO.Compression {
using System;
using System.Diagnostics;
internal class FastEncoderWindow {
private byte[] window; // complete bytes window
private int bufPos; // the start index of uncompressed bytes
private int bufEnd; // the end index of uncompressed bytes
// Be very careful about increasing the window size; the code tables will have to
// be updated, since they assume that extra_distance_bits is never larger than a
// certain size.
const int FastEncoderHashShift = 4;
const int FastEncoderHashtableSize = 2048;
const int FastEncoderHashMask = FastEncoderHashtableSize-1;
const int FastEncoderWindowSize = 8192;
const int FastEncoderWindowMask = FastEncoderWindowSize - 1;
const int FastEncoderMatch3DistThreshold = 16384;
internal const int MaxMatch = 258;
internal const int MinMatch = 3;
// Following constants affect the search,
// they should be modifiable if we support different compression levels in future.
const int SearchDepth = 32;
const int GoodLength = 4;
const int NiceLength = 32;
const int LazyMatchThreshold = 6;
// Hashtable structure
private ushort[] prev; // next most recent occurance of chars with same hash value
private ushort[] lookup; // hash table to find most recent occurance of chars with same hash value
public FastEncoderWindow() {
ResetWindow();
}
public int BytesAvailable { // uncompressed bytes
get {
Debug.Assert(bufEnd - bufPos >= 0, "Ending pointer can't be in front of starting pointer!");
return bufEnd - bufPos;
}
}
public DeflateInput UnprocessedInput {
get {
DeflateInput input = new DeflateInput();
input.Buffer = window;
input.StartIndex = bufPos;
input.Count = bufEnd - bufPos;
return input;
}
}
public void FlushWindow() {
ResetWindow();
}
private void ResetWindow() {
window = new byte[2 * FastEncoderWindowSize + MaxMatch + 4];
prev = new ushort[FastEncoderWindowSize + MaxMatch];
lookup = new ushort[FastEncoderHashtableSize];
bufPos = FastEncoderWindowSize;
bufEnd = bufPos;
}
public int FreeWindowSpace { // Free space in the window
get {
return 2 * FastEncoderWindowSize - bufEnd;
}
}
// copy bytes from input buffer into window
public void CopyBytes(byte[] inputBuffer, int startIndex, int count) {
Array.Copy(inputBuffer, startIndex, window, bufEnd, count);
bufEnd += count;
}
// slide the history window to the left by FastEncoderWindowSize bytes
public void MoveWindows() {
int i;
Debug.Assert(bufPos == 2*FastEncoderWindowSize, "only call this at the end of the window");
// verify that the hash table is correct
VerifyHashes(); // Debug only code
Array.Copy(window, bufPos - FastEncoderWindowSize, window, 0, FastEncoderWindowSize);
// move all the hash pointers back
for (i = 0; i < FastEncoderHashtableSize; i++) {
int val = ((int) lookup[i]) - FastEncoderWindowSize;
if (val <= 0) { // too far away now? then set to zero
lookup[i] = (ushort) 0;
} else {
lookup[i] = (ushort) val;
}
}
// prev[]'s are absolute pointers, not relative pointers, so we have to move them back too
// making prev[]'s into relative pointers poses problems of its own
for (i = 0; i < FastEncoderWindowSize; i++) {
long val = ((long) prev[i]) - FastEncoderWindowSize;
if (val <= 0) {
prev[i] = (ushort) 0;
} else {
prev[i] = (ushort) val;
}
}
#if DEBUG
// For debugging, wipe the window clean, so that if there is a bug in our hashing,
// the hash pointers will now point to locations which are not valid for the hash value
// (and will be caught by our ASSERTs).
Array.Clear(window, FastEncoderWindowSize, window.Length - FastEncoderWindowSize);
#endif
VerifyHashes(); // debug: verify hash table is correct
bufPos = FastEncoderWindowSize;
bufEnd = bufPos;
}
private uint HashValue(uint hash, byte b) {
return(hash << FastEncoderHashShift) ^ b;
}
// insert string into hash table and return most recent location of same hash value
private uint InsertString(ref uint hash) {
// Note we only use the lowest 11 bits of the hash vallue (hash table size is 11).
// This enables fast calculation of hash value for the input string.
// If we want to get the next hash code starting at next position,
// we can just increment bufPos and call this function.
hash = HashValue( hash, window[bufPos+2] );
// Need to assert the hash value
uint search = lookup[hash & FastEncoderHashMask];
lookup[hash & FastEncoderHashMask] = (ushort) bufPos;
prev[bufPos & FastEncoderWindowMask] = (ushort) search;
return search;
}
//
// insert strings into hashtable
// Arguments:
// hash : intial hash value
// matchLen : 1 + number of strings we need to insert.
//
private void InsertStrings(ref uint hash, int matchLen) {
Debug.Assert(matchLen > 0, "Invalid match Len!");
if (bufEnd - bufPos <= matchLen) {
bufPos += (matchLen-1);
}
else {
while (--matchLen > 0) {
InsertString(ref hash);
bufPos++;
}
}
}
//
// Find out what we should generate next. It can be a symbol, a distance/length pair
// or a symbol followed by distance/length pair
//
internal bool GetNextSymbolOrMatch(Match match) {
Debug.Assert(bufPos >= FastEncoderWindowSize && bufPos < (2*FastEncoderWindowSize), "Invalid Buffer Position!");
// initialise the value of the hash, no problem if locations bufPos, bufPos+1
// are invalid (not enough data), since we will never insert using that hash value
uint hash = HashValue( 0 , window[bufPos]);
hash = HashValue( hash , window[bufPos + 1]);
int matchLen;
int matchPos = 0;
VerifyHashes(); // Debug only code
if (bufEnd - bufPos <= 3) {
// The hash value becomes corrupt when we get within 3 characters of the end of the
// input window, since the hash value is based on 3 characters. We just stop
// inserting into the hash table at this point, and allow no matches.
matchLen = 0;
}
else {
// insert string into hash table and return most recent location of same hash value
int search = (int)InsertString(ref hash);
// did we find a recent location of this hash value?
if (search != 0) {
// yes, now find a match at what we'll call position X
matchLen = FindMatch(search, out matchPos, SearchDepth, NiceLength);
// truncate match if we're too close to the end of the input window
if (bufPos + matchLen > bufEnd)
matchLen = bufEnd - bufPos;
}
else {
// no most recent location found
matchLen = 0;
}
}
if (matchLen < MinMatch) {
// didn't find a match, so output unmatched char
match.State = MatchState.HasSymbol;
match.Symbol = window[bufPos];
bufPos++;
}
else {
// bufPos now points to X+1
bufPos++;
// is this match so good (long) that we should take it automatically without
// checking X+1 ?
if (matchLen <= LazyMatchThreshold) {
int nextMatchLen;
int nextMatchPos = 0;
// search at position X+1
int search = (int)InsertString(ref hash);
// no, so check for a better match at X+1
if (search != 0) {
nextMatchLen = FindMatch(search, out nextMatchPos,
matchLen < GoodLength ? SearchDepth : (SearchDepth >> 2),NiceLength);
// truncate match if we're too close to the end of the window
// note: nextMatchLen could now be < MinMatch
if (bufPos + nextMatchLen > bufEnd) {
nextMatchLen = bufEnd - bufPos;
}
} else {
nextMatchLen = 0;
}
// right now X and X+1 are both inserted into the search tree
if (nextMatchLen > matchLen) {
// since nextMatchLen > matchLen, it can't be < MinMatch here
// match at X+1 is better, so output unmatched char at X
match.State = MatchState.HasSymbolAndMatch;
match.Symbol = window[bufPos-1];
match.Position = nextMatchPos;
match.Length = nextMatchLen;
// insert remainder of second match into search tree
// example: (*=inserted already)
//
// X X+1 X+2 X+3 X+4
// * *
// nextmatchlen=3
// bufPos
//
// If nextMatchLen == 3, we want to perform 2
// insertions (at X+2 and X+3). However, first we must
// inc bufPos.
//
bufPos++; // now points to X+2
matchLen = nextMatchLen;
InsertStrings(ref hash, matchLen);
} else {
// match at X is better, so take it
match.State = MatchState.HasMatch;
match.Position = matchPos;
match.Length = matchLen;
// Insert remainder of first match into search tree, minus the first
// two locations, which were inserted by the FindMatch() calls.
//
// For example, if matchLen == 3, then we've inserted at X and X+1
// already (and bufPos is now pointing at X+1), and now we need to insert
// only at X+2.
//
matchLen--;
bufPos++; // now bufPos points to X+2
InsertStrings(ref hash, matchLen);
}
} else { // match_length >= good_match
// in assertion: bufPos points to X+1, location X inserted already
// first match is so good that we're not even going to check at X+1
match.State = MatchState.HasMatch;
match.Position = matchPos;
match.Length = matchLen;
// insert remainder of match at X into search tree
InsertStrings(ref hash, matchLen);
}
}
if (bufPos == 2*FastEncoderWindowSize) {
MoveWindows();
}
return true;
}
//
// Find a match starting at specified position and return length of match
// Arguments:
// search : where to start searching
// matchPos : return match position here
// searchDepth : # links to traverse
// NiceLength : stop immediately if we find a match >= NiceLength
//
int FindMatch(int search, out int matchPos, int searchDepth, int niceLength ) {
Debug.Assert(bufPos >= 0 && bufPos < 2*FastEncoderWindowSize, "Invalid Buffer position!");
Debug.Assert(search < bufPos, "Invalid starting search point!");
Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos));
int bestMatch = 0; // best match length found so far
int bestMatchPos = 0; // absolute match position of best match found
// the earliest we can look
int earliest = bufPos - FastEncoderWindowSize;
Debug.Assert(earliest >= 0, "bufPos is less than FastEncoderWindowSize!");
byte wantChar = window[bufPos];
while (search > earliest) {
// make sure all our hash links are valid
Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos), "Corrupted hash link!");
// Start by checking the character that would allow us to increase the match
// length by one. This improves performance quite a bit.
if (window[search + bestMatch] == wantChar) {
int j;
// Now make sure that all the other characters are correct
for (j = 0; j < MaxMatch; j++) {
if (window[bufPos+j] != window[search+j])
break;
}
if (j > bestMatch) {
bestMatch = j;
bestMatchPos = search; // absolute position
if (j > NiceLength) break;
wantChar = window[bufPos+j];
}
}
if (--searchDepth == 0) {
break;
}
Debug.Assert(prev[search & FastEncoderWindowMask] < search, "we should always go backwards!");
search = prev[search & FastEncoderWindowMask];
}
// doesn't necessarily mean we found a match; bestMatch could be > 0 and < MinMatch
matchPos = bufPos - bestMatchPos - 1; // convert absolute to relative position
// don't allow match length 3's which are too far away to be worthwhile
if (bestMatch == 3 && matchPos >= FastEncoderMatch3DistThreshold) {
return 0;
}
Debug.Assert(bestMatch < MinMatch || matchPos < FastEncoderWindowSize, "Only find match inside FastEncoderWindowSize");
return bestMatch;
}
[Conditional("DEBUG")]
void VerifyHashes() {
for (int i = 0; i < FastEncoderHashtableSize; i++) {
ushort where = lookup[i];
ushort nextWhere;
while (where != 0 && bufPos - where < FastEncoderWindowSize) {
Debug.Assert(RecalculateHash(where) == i, "Incorrect Hashcode!");
nextWhere = prev[where & FastEncoderWindowMask];
if (bufPos - nextWhere >= FastEncoderWindowSize) {
break;
}
Debug.Assert(nextWhere < where, "pointer is messed up!");
where = nextWhere;
}
}
}
// can't use conditional attribute here.
uint RecalculateHash(int position) {
return (uint)(((window[position] << (2*FastEncoderHashShift)) ^
(window[position+1] << FastEncoderHashShift) ^
(window[position+2])) & FastEncoderHashMask);
}
}
}
| |
using System;
using System.Collections.Generic;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// ProductTypeColl (editable root list).<br/>
/// This is a generated base class of <see cref="ProductTypeColl"/> business object.
/// </summary>
/// <remarks>
/// The items of the collection are <see cref="ProductTypeItem"/> objects.
/// </remarks>
[Serializable]
#if WINFORMS
public partial class ProductTypeColl : BusinessBindingListBase<ProductTypeColl, ProductTypeItem>
#else
public partial class ProductTypeColl : BusinessListBase<ProductTypeColl, ProductTypeItem>
#endif
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="ProductTypeItem"/> item from the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to be removed.</param>
public void Remove(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
Remove(productTypeItem);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int productTypeId)
{
foreach (var productTypeItem in this)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="ProductTypeItem"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="productTypeId">The ProductTypeId of the item to search for.</param>
/// <returns><c>true</c> if the ProductTypeItem is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int productTypeId)
{
foreach (var productTypeItem in DeletedList)
{
if (productTypeItem.ProductTypeId == productTypeId)
{
return true;
}
}
return false;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl NewProductTypeColl()
{
return DataPortal.Create<ProductTypeColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <returns>A reference to the fetched <see cref="ProductTypeColl"/> collection.</returns>
public static ProductTypeColl GetProductTypeColl()
{
return DataPortal.Fetch<ProductTypeColl>();
}
/// <summary>
/// Factory method. Asynchronously creates a new <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void NewProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginCreate<ProductTypeColl>(callback);
}
/// <summary>
/// Factory method. Asynchronously loads a <see cref="ProductTypeColl"/> collection.
/// </summary>
/// <param name="callback">The completion callback method.</param>
public static void GetProductTypeColl(EventHandler<DataPortalResult<ProductTypeColl>> callback)
{
DataPortal.BeginFetch<ProductTypeColl>(callback);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="ProductTypeColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public ProductTypeColl()
{
// Use factory methods and do not use direct creation.
Saved += OnProductTypeCollSaved;
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Cache Invalidation
// TODO: edit "ProductTypeColl.cs", uncomment the "OnDeserialized" method and add the following line:
// TODO: Saved += OnProductTypeCollSaved;
private void OnProductTypeCollSaved(object sender, Csla.Core.SavedEventArgs e)
{
// this runs on the client
ProductTypeCachedList.InvalidateCache();
ProductTypeCachedNVL.InvalidateCache();
}
/// <summary>
/// Called by the server-side DataPortal after calling the requested DataPortal_XYZ method.
/// </summary>
/// <param name="e">The DataPortalContext object passed to the DataPortal.</param>
protected override void DataPortal_OnDataPortalInvokeComplete(Csla.DataPortalEventArgs e)
{
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Server &&
e.Operation == DataPortalOperations.Update)
{
// this runs on the server
ProductTypeCachedNVL.InvalidateCache();
}
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="ProductTypeColl"/> collection from the database.
/// </summary>
protected void DataPortal_Fetch()
{
var args = new DataPortalHookArgs();
OnFetchPre(args);
using (var dalManager = DalFactoryInvoices.GetManager())
{
var dal = dalManager.GetProvider<IProductTypeCollDal>();
var data = dal.Fetch();
Fetch(data);
}
OnFetchPost(args);
}
/// <summary>
/// Loads all <see cref="ProductTypeColl"/> collection items from the given list of ProductTypeItemDto.
/// </summary>
/// <param name="data">The list of <see cref="ProductTypeItemDto"/>.</param>
private void Fetch(List<ProductTypeItemDto> data)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
foreach (var dto in data)
{
Add(DataPortal.FetchChild<ProductTypeItem>(dto));
}
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Updates in the database all changes made to the <see cref="ProductTypeColl"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
using (var dalManager = DalFactoryInvoices.GetManager())
{
base.Child_Update();
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.AspNetCore.StaticFiles;
using OrchardCore.Modules;
namespace OrchardCore.FileStorage.AzureBlob
{
/// <summary>
/// Provides an <see cref="IFileStore"/> implementation that targets an underlying Azure Blob Storage account.
/// </summary>
/// <remarks>
/// Azure Blob Storage has very different semantics for directories compared to a local file system, and
/// some special consideration is required for make this provider conform to the semantics of the
/// <see cref="IFileStore"/> interface and behave in an expected way.
///
/// Directories have no physical manifestation in blob storage; we can obtain a reference to them, but
/// that reference can be created regardless of whether the directory exists, and it can only be used
/// as a scoping container to operate on blobs within that directory namespace.
///
/// As a consequence, this provider generally behaves as if any given directory always exists. To
/// simulate "creating" a directory (which cannot technically be done in blob storage) this provider creates
/// a marker file inside the directory, which makes the directory "exist" and appear when listing contents
/// subsequently. This marker file is ignored (excluded) when listing directory contents.
///
/// Note that the Blob Container is not created automatically, and existence of the Container is not verified.
///
/// Create the Blob Container before enabling a Blob File Store.
///
/// Azure Blog Storage will create the BasePath inside the container during the upload of the first file.
/// </remarks>
public class BlobFileStore : IFileStore
{
private const string _directoryMarkerFileName = "OrchardCore.Media.txt";
private readonly BlobStorageOptions _options;
private readonly IClock _clock;
private readonly BlobContainerClient _blobContainer;
private readonly IContentTypeProvider _contentTypeProvider;
private readonly string _basePrefix = null;
public BlobFileStore(BlobStorageOptions options, IClock clock, IContentTypeProvider contentTypeProvider)
{
_options = options;
_clock = clock;
_contentTypeProvider = contentTypeProvider;
_blobContainer = new BlobContainerClient(_options.ConnectionString, _options.ContainerName);
if (!String.IsNullOrEmpty(_options.BasePath))
{
_basePrefix = NormalizePrefix(_options.BasePath);
}
}
public async Task<IFileStoreEntry> GetFileInfoAsync(string path)
{
try
{
var blob = GetBlobReference(path);
var properties = await blob.GetPropertiesAsync();
return new BlobFile(path, properties.Value.ContentLength, properties.Value.LastModified);
}
catch (RequestFailedException ex) when (ex.ErrorCode == BlobErrorCode.BlobNotFound)
{
// Instead of ExistsAsync() check which is 'slow' if we're expecting to find the blob we rely on the exception
return null;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot get file info with path '{path}'.", ex);
}
}
public async Task<IFileStoreEntry> GetDirectoryInfoAsync(string path)
{
try
{
if (path == String.Empty)
{
return new BlobDirectory(path, _clock.UtcNow);
}
var blobDirectory = await GetBlobDirectoryReference(path);
if (blobDirectory != null)
{
return new BlobDirectory(path, _clock.UtcNow);
}
return null;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot get directory info with path '{path}'.", ex);
}
}
public IAsyncEnumerable<IFileStoreEntry> GetDirectoryContentAsync(string path = null, bool includeSubDirectories = false)
{
try
{
if (includeSubDirectories)
{
return GetDirectoryContentFlatAsync(path);
}
else
{
return GetDirectoryContentByHierarchyAsync(path);
}
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot get directory content with path '{path}'.", ex);
}
}
private async IAsyncEnumerable<IFileStoreEntry> GetDirectoryContentByHierarchyAsync(string path = null)
{
var prefix = this.Combine(_basePrefix, path);
prefix = NormalizePrefix(prefix);
var page = _blobContainer.GetBlobsByHierarchyAsync(BlobTraits.Metadata, BlobStates.None, "/", prefix);
await foreach (var blob in page)
{
if (blob.IsPrefix)
{
var folderPath = blob.Prefix;
if (!String.IsNullOrEmpty(_basePrefix))
{
folderPath = folderPath.Substring(_basePrefix.Length - 1);
}
folderPath = folderPath.Trim('/');
yield return new BlobDirectory(folderPath, _clock.UtcNow);
}
else
{
var itemName = Path.GetFileName(WebUtility.UrlDecode(blob.Blob.Name)).Trim('/');
// Ignore directory marker files.
if (itemName != _directoryMarkerFileName)
{
var itemPath = this.Combine(path?.Trim('/'), itemName);
yield return new BlobFile(itemPath, blob.Blob.Properties.ContentLength, blob.Blob.Properties.LastModified);
}
}
}
}
private async IAsyncEnumerable<IFileStoreEntry> GetDirectoryContentFlatAsync(string path = null)
{
// Folders are considered case sensitive in blob storage.
var directories = new HashSet<string>();
var prefix = this.Combine(_basePrefix, path);
prefix = NormalizePrefix(prefix);
var page = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix);
await foreach (var blob in page)
{
var name = WebUtility.UrlDecode(blob.Name);
// A flat blob listing does not return a folder hierarchy.
// We can infer a hierarchy by examining the paths returned for the file contents
// and evaluate whether a directory exists and should be added to the results listing.
var directory = Path.GetDirectoryName(name);
// Strip base folder from directory name.
if (!String.IsNullOrEmpty(_basePrefix))
{
directory = directory.Substring(_basePrefix.Length - 1);
}
// Do not include root folder, or current path, or multiple folders in folder listing.
if (!String.IsNullOrEmpty(directory) && !directories.Contains(directory) && (String.IsNullOrEmpty(path) ? true : !directory.EndsWith(path)))
{
directories.Add(directory);
yield return new BlobDirectory(directory, _clock.UtcNow);
}
// Ignore directory marker files.
if (!name.EndsWith(_directoryMarkerFileName))
{
if (!String.IsNullOrEmpty(_basePrefix))
{
name = name.Substring(_basePrefix.Length - 1);
}
yield return new BlobFile(name.Trim('/'), blob.Properties.ContentLength, blob.Properties.LastModified);
}
}
}
public async Task<bool> TryCreateDirectoryAsync(string path)
{
// Since directories are only created implicitly when creating blobs, we
// simply pretend like we created the directory, unless there is already
// a blob with the same path.
try
{
var blobFile = GetBlobReference(path);
if (await blobFile.ExistsAsync())
{
throw new FileStoreException($"Cannot create directory because the path '{path}' already exists and is a file.");
}
var blobDirectory = await GetBlobDirectoryReference(path);
if (blobDirectory == null)
{
await CreateDirectoryAsync(path);
}
return true;
}
catch (FileStoreException)
{
throw;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot create directory '{path}'.", ex);
}
}
public async Task<bool> TryDeleteFileAsync(string path)
{
try
{
var blob = GetBlobReference(path);
return await blob.DeleteIfExistsAsync();
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot delete file '{path}'.", ex);
}
}
public async Task<bool> TryDeleteDirectoryAsync(string path)
{
try
{
if (String.IsNullOrEmpty(path))
{
throw new FileStoreException("Cannot delete the root directory.");
}
var blobsWereDeleted = false;
var prefix = this.Combine(_basePrefix, path);
prefix = this.NormalizePrefix(prefix);
var page = _blobContainer.GetBlobsAsync(BlobTraits.Metadata, BlobStates.None, prefix);
await foreach (var blob in page)
{
var blobReference = _blobContainer.GetBlobClient(blob.Name);
await blobReference.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots);
blobsWereDeleted = true;
}
return blobsWereDeleted;
}
catch (FileStoreException)
{
throw;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot delete directory '{path}'.", ex);
}
}
public async Task MoveFileAsync(string oldPath, string newPath)
{
try
{
await CopyFileAsync(oldPath, newPath);
await TryDeleteFileAsync(oldPath);
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot move file '{oldPath}' to '{newPath}'.", ex);
}
}
public async Task CopyFileAsync(string srcPath, string dstPath)
{
try
{
if (srcPath == dstPath)
{
throw new ArgumentException($"The values for {nameof(srcPath)} and {nameof(dstPath)} must not be the same.");
}
var oldBlob = GetBlobReference(srcPath);
var newBlob = GetBlobReference(dstPath);
if (!await oldBlob.ExistsAsync())
{
throw new FileStoreException($"Cannot copy file '{srcPath}' because it does not exist.");
}
if (await newBlob.ExistsAsync())
{
throw new FileStoreException($"Cannot copy file '{srcPath}' because a file already exists in the new path '{dstPath}'.");
}
await newBlob.StartCopyFromUriAsync(oldBlob.Uri);
await Task.Delay(250);
var properties = await newBlob.GetPropertiesAsync();
while (properties.Value.CopyStatus == CopyStatus.Pending)
{
await Task.Delay(250);
// Need to fetch properties or CopyStatus will never update.
properties = await newBlob.GetPropertiesAsync();
}
if (properties.Value.CopyStatus != CopyStatus.Success)
{
throw new FileStoreException($"Error while copying file '{srcPath}'; copy operation failed with status {properties.Value.CopyStatus} and description {properties.Value.CopyStatusDescription}.");
}
}
catch (FileStoreException)
{
throw;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot copy file '{srcPath}' to '{dstPath}'.", ex);
}
}
public async Task<Stream> GetFileStreamAsync(string path)
{
try
{
var blob = GetBlobReference(path);
if (!await blob.ExistsAsync())
{
throw new FileStoreException($"Cannot get file stream because the file '{path}' does not exist.");
}
return (await blob.DownloadAsync()).Value.Content;
}
catch (FileStoreException)
{
throw;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot get file stream of the file '{path}'.", ex);
}
}
// Reduces the need to call blob.FetchAttributes, and blob.ExistsAsync,
// as Azure Storage Library will perform these actions on OpenReadAsync().
public Task<Stream> GetFileStreamAsync(IFileStoreEntry fileStoreEntry)
{
return GetFileStreamAsync(fileStoreEntry.Path);
}
public async Task<string> CreateFileFromStreamAsync(string path, Stream inputStream, bool overwrite = false)
{
try
{
var blob = GetBlobReference(path);
if (!overwrite && await blob.ExistsAsync())
{
throw new FileStoreException($"Cannot create file '{path}' because it already exists.");
}
_contentTypeProvider.TryGetContentType(path, out var contentType);
var headers = new BlobHttpHeaders
{
ContentType = contentType ?? "application/octet-stream"
};
await blob.UploadAsync(inputStream, headers);
return path;
}
catch (FileStoreException)
{
throw;
}
catch (Exception ex)
{
throw new FileStoreException($"Cannot create file '{path}'.", ex);
}
}
private BlobClient GetBlobReference(string path)
{
var blobPath = this.Combine(_options.BasePath, path);
var blob = _blobContainer.GetBlobClient(blobPath);
return blob;
}
private async Task<BlobHierarchyItem> GetBlobDirectoryReference(string path)
{
var prefix = this.Combine(_basePrefix, path);
prefix = NormalizePrefix(prefix);
// Directory exists if path contains any files.
var page = _blobContainer.GetBlobsByHierarchyAsync(BlobTraits.Metadata, BlobStates.None, "/", prefix);
var enumerator = page.GetAsyncEnumerator();
var result = await enumerator.MoveNextAsync();
if (result)
{
return enumerator.Current;
}
return null;
}
private async Task CreateDirectoryAsync(string path)
{
var placeholderBlob = GetBlobReference(this.Combine(path, _directoryMarkerFileName));
// Create a directory marker file to make this directory appear when listing directories.
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("This is a directory marker file created by Orchard Core. It is safe to delete it.")))
{
await placeholderBlob.UploadAsync(stream);
}
}
/// <summary>
/// Blob prefix requires a trailing slash except when loading the root of the container.
/// </summary>
private string NormalizePrefix(string prefix)
{
prefix = prefix.Trim('/') + '/';
if (prefix.Length == 1)
{
return String.Empty;
}
else
{
return prefix;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Security.Principal
{
[Flags]
internal enum PolicyRights
{
POLICY_VIEW_LOCAL_INFORMATION = 0x00000001,
POLICY_VIEW_AUDIT_INFORMATION = 0x00000002,
POLICY_GET_PRIVATE_INFORMATION = 0x00000004,
POLICY_TRUST_ADMIN = 0x00000008,
POLICY_CREATE_ACCOUNT = 0x00000010,
POLICY_CREATE_SECRET = 0x00000020,
POLICY_CREATE_PRIVILEGE = 0x00000040,
POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080,
POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100,
POLICY_AUDIT_LOG_ADMIN = 0x00000200,
POLICY_SERVER_ADMIN = 0x00000400,
POLICY_LOOKUP_NAMES = 0x00000800,
POLICY_NOTIFICATION = 0x00001000,
}
internal static class Win32
{
internal const int FALSE = 0;
internal const int TRUE = 1;
//
// Wrapper around advapi32.LsaOpenPolicy
//
internal static SafeLsaPolicyHandle LsaOpenPolicy(
string systemName,
PolicyRights rights)
{
uint ReturnCode;
SafeLsaPolicyHandle Result;
Interop.LSA_OBJECT_ATTRIBUTES Loa;
Loa.Length = Marshal.SizeOf<Interop.LSA_OBJECT_ATTRIBUTES>();
Loa.RootDirectory = IntPtr.Zero;
Loa.ObjectName = IntPtr.Zero;
Loa.Attributes = 0;
Loa.SecurityDescriptor = IntPtr.Zero;
Loa.SecurityQualityOfService = IntPtr.Zero;
if (0 == (ReturnCode = Interop.mincore.LsaOpenPolicy(systemName, ref Loa, (int)rights, out Result)))
{
return Result;
}
else if (ReturnCode == Interop.StatusOptions.STATUS_ACCESS_DENIED)
{
throw new UnauthorizedAccessException();
}
else if (ReturnCode == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES ||
ReturnCode == Interop.StatusOptions.STATUS_NO_MEMORY)
{
throw new OutOfMemoryException();
}
else
{
int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(unchecked((int)ReturnCode));
throw new Win32Exception(win32ErrorCode);
}
}
internal static byte[] ConvertIntPtrSidToByteArraySid(IntPtr binaryForm)
{
byte[] ResultSid;
//
// Verify the revision (just sanity, should never fail to be 1)
//
byte Revision = Marshal.ReadByte(binaryForm, 0);
if (Revision != SecurityIdentifier.Revision)
{
throw new ArgumentException(SR.IdentityReference_InvalidSidRevision, nameof(binaryForm));
}
//
// Need the subauthority count in order to figure out how many bytes to read
//
byte SubAuthorityCount = Marshal.ReadByte(binaryForm, 1);
if (SubAuthorityCount < 0 ||
SubAuthorityCount > SecurityIdentifier.MaxSubAuthorities)
{
throw new ArgumentException(SR.Format(SR.IdentityReference_InvalidNumberOfSubauthorities, SecurityIdentifier.MaxSubAuthorities), nameof(binaryForm));
}
//
// Compute the size of the binary form of this SID and allocate the memory
//
int BinaryLength = 1 + 1 + 6 + SubAuthorityCount * 4;
ResultSid = new byte[BinaryLength];
//
// Extract the data from the returned pointer
//
Marshal.Copy(binaryForm, ResultSid, 0, BinaryLength);
return ResultSid;
}
//
// Wrapper around advapi32.ConvertStringSidToSidW
//
internal static int CreateSidFromString(
string stringSid,
out byte[] resultSid
)
{
int ErrorCode;
IntPtr ByteArray = IntPtr.Zero;
try
{
if (TRUE != Interop.mincore.ConvertStringSidToSid(stringSid, out ByteArray))
{
ErrorCode = Marshal.GetLastWin32Error();
goto Error;
}
resultSid = ConvertIntPtrSidToByteArraySid(ByteArray);
}
finally
{
//
// Now is a good time to get rid of the returned pointer
//
Interop.mincore_obsolete.LocalFree(ByteArray);
}
//
// Now invoke the SecurityIdentifier factory method to create the result
//
return Interop.mincore.Errors.ERROR_SUCCESS;
Error:
resultSid = null;
return ErrorCode;
}
//
// Wrapper around advapi32.CreateWellKnownSid
//
internal static int CreateWellKnownSid(
WellKnownSidType sidType,
SecurityIdentifier domainSid,
out byte[] resultSid
)
{
//
// Passing an array as big as it can ever be is a small price to pay for
// not having to P/Invoke twice (once to get the buffer, once to get the data)
//
uint length = (uint)SecurityIdentifier.MaxBinaryLength;
resultSid = new byte[length];
if (FALSE != Interop.mincore.CreateWellKnownSid((int)sidType, domainSid == null ? null : domainSid.BinaryForm, resultSid, ref length))
{
return Interop.mincore.Errors.ERROR_SUCCESS;
}
else
{
resultSid = null;
return Marshal.GetLastWin32Error();
}
}
//
// Wrapper around advapi32.EqualDomainSid
//
internal static bool IsEqualDomainSid(SecurityIdentifier sid1, SecurityIdentifier sid2)
{
if (sid1 == null || sid2 == null)
{
return false;
}
else
{
bool result;
byte[] BinaryForm1 = new Byte[sid1.BinaryLength];
sid1.GetBinaryForm(BinaryForm1, 0);
byte[] BinaryForm2 = new Byte[sid2.BinaryLength];
sid2.GetBinaryForm(BinaryForm2, 0);
return (Interop.mincore.IsEqualDomainSid(BinaryForm1, BinaryForm2, out result) == FALSE ? false : result);
}
}
/// <summary>
/// Setup the size of the buffer Windows provides for an LSA_REFERENCED_DOMAIN_LIST
/// </summary>
internal static void InitializeReferencedDomainsPointer(SafeLsaMemoryHandle referencedDomains)
{
Debug.Assert(referencedDomains != null, "referencedDomains != null");
// We don't know the real size of the referenced domains yet, so we need to set an initial
// size based on the LSA_REFERENCED_DOMAIN_LIST structure, then resize it to include all of
// the domains.
referencedDomains.Initialize((uint)Marshal.SizeOf<Interop.LSA_REFERENCED_DOMAIN_LIST>());
Interop.LSA_REFERENCED_DOMAIN_LIST domainList = referencedDomains.Read<Interop.LSA_REFERENCED_DOMAIN_LIST>(0);
unsafe
{
byte* pRdl = null;
try
{
referencedDomains.AcquirePointer(ref pRdl);
// If there is a trust information list, then the buffer size is the end of that list minus
// the beginning of the domain list. Otherwise, then the buffer is just the size of the
// referenced domain list structure, which is what we defaulted to.
if (domainList.Domains != IntPtr.Zero)
{
Interop.LSA_TRUST_INFORMATION* pTrustInformation = (Interop.LSA_TRUST_INFORMATION*)domainList.Domains;
pTrustInformation = pTrustInformation + domainList.Entries;
long bufferSize = (byte*)pTrustInformation - pRdl;
Debug.Assert(bufferSize > 0, "bufferSize > 0");
referencedDomains.Initialize((ulong)bufferSize);
}
}
finally
{
if (pRdl != null)
referencedDomains.ReleasePointer();
}
}
}
//
// Wrapper around avdapi32.GetWindowsAccountDomainSid
//
internal static int GetWindowsAccountDomainSid(
SecurityIdentifier sid,
out SecurityIdentifier resultSid
)
{
//
// Passing an array as big as it can ever be is a small price to pay for
// not having to P/Invoke twice (once to get the buffer, once to get the data)
//
byte[] BinaryForm = new Byte[sid.BinaryLength];
sid.GetBinaryForm(BinaryForm, 0);
uint sidLength = (uint)SecurityIdentifier.MaxBinaryLength;
byte[] resultSidBinary = new byte[sidLength];
if (FALSE != Interop.mincore.GetWindowsAccountDomainSid(BinaryForm, resultSidBinary, ref sidLength))
{
resultSid = new SecurityIdentifier(resultSidBinary, 0);
return Interop.mincore.Errors.ERROR_SUCCESS;
}
else
{
resultSid = null;
return Marshal.GetLastWin32Error();
}
}
//
// Wrapper around advapi32.IsWellKnownSid
//
internal static bool IsWellKnownSid(
SecurityIdentifier sid,
WellKnownSidType type
)
{
byte[] BinaryForm = new byte[sid.BinaryLength];
sid.GetBinaryForm(BinaryForm, 0);
if (FALSE == Interop.mincore.IsWellKnownSid(BinaryForm, (int)type))
{
return false;
}
else
{
return true;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Comm.SimpleInMem
{
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Bond.Comm.Layers;
using Bond.Comm.Service;
using Bond.Comm.SimpleInMem.Processor;
public enum ConnectionType
{
Client,
Server
}
[Flags]
public enum CnxState
{
Created = 0x01,
Connected = 0x02,
SendProtocolError = 0x04,
Disconnecting = 0x08,
Disconnected = 0x10,
}
public class SimpleInMemConnection : Connection, IRequestResponseConnection, IEventConnection
{
private readonly ConnectionType connectionType;
private readonly SimpleInMemListener parentListener;
private readonly ServiceHost serviceHost;
private readonly SimpleInMemTransport transport;
private InMemFrameQueue pairedReadQueue = null;
private readonly InMemFrameQueue writeQueue;
private long prevConversationId;
private CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
private CnxState state;
private object stateLock = new object();
private readonly Logger logger;
private readonly Metrics metrics;
internal SimpleInMemConnection(
SimpleInMemListener parentListener, ConnectionType connectionType,
ServiceHost serviceHost, SimpleInMemTransport transport,
Logger logger, Metrics metrics)
{
if (parentListener == null) throw new ArgumentNullException(nameof(parentListener));
if (serviceHost == null) throw new ArgumentNullException(nameof(serviceHost));
if (transport == null) throw new ArgumentNullException(nameof(transport));
this.parentListener = parentListener;
this.connectionType = connectionType;
this.serviceHost = serviceHost;
this.transport = transport;
writeQueue = new InMemFrameQueue();
// start at -1 or 0 so the first conversation ID is 1 or 2.
prevConversationId = (connectionType == ConnectionType.Client) ? -1 : 0;
state = CnxState.Created;
this.logger = logger;
this.metrics = metrics;
}
public CnxState State
{
get
{
return state;
}
}
public ConnectionType ConnectionType
{
get
{
return connectionType;
}
}
public bool IsConnected
{
get
{
return ((state & CnxState.Connected) != 0);
}
}
public bool IsPaired
{
get
{
return pairedReadQueue != null;
}
}
internal InMemFrameQueue WriteQueue
{
get
{
return writeQueue;
}
}
internal InMemFrameQueue ReadQueue
{
get
{
return pairedReadQueue;
}
}
public override string ToString()
{
return $"{nameof(SimpleInMemConnection)}({Id})";
}
public override Task StopAsync()
{
bool connected = false;
lock (stateLock)
{
if (connected = ((state & CnxState.Connected) != 0))
{
state = CnxState.Disconnecting;
cancelTokenSource.Cancel();
}
}
if (connected)
{
OnDisconnect();
writeQueue.Clear();
pairedReadQueue = null;
lock (stateLock)
{
state = CnxState.Disconnected;
}
}
return TaskExt.CompletedTask;
}
internal static ConnectionPair Pair(SimpleInMemConnection client, SimpleInMemConnection server)
{
ConnectionPair pair = new ConnectionPair(client, server);
server.pairedReadQueue = client.writeQueue;
client.pairedReadQueue = server.writeQueue;
server.Start();
client.Start();
return pair;
}
public async Task<IMessage<TResponse>> RequestResponseAsync<TRequest, TResponse>(string methodName, IMessage<TRequest> message, CancellationToken ct)
{
EnsureCorrectState(CnxState.Connected);
IMessage response = await SendRequestAsync(methodName, message);
return response.Convert<TResponse>();
}
public Task FireEventAsync<TPayload>(string methodName, IMessage<TPayload> message)
{
EnsureCorrectState(CnxState.Connected);
SendEventAsync(methodName, message);
return TaskExt.CompletedTask;
}
private void Start()
{
if (!IsPaired)
{
var message = $"{ToString()} - Connection cannot be started without pairing first.";
throw new InvalidOperationException(message);
}
lock (stateLock)
{
EnsureCorrectState(CnxState.Created);
var batchProcessor = new BatchProcessor(this, serviceHost, transport, logger);
Task.Run(() => batchProcessor.ProcessAsync(cancelTokenSource.Token));
state = CnxState.Connected;
}
}
private Task<IMessage> SendRequestAsync(string methodName, IMessage request)
{
var requestMetrics = Metrics.StartRequestMetrics(ConnectionMetrics);
var conversationId = AllocateNextConversationId();
var sendContext = new SimpleInMemSendContext(this, ConnectionMetrics, requestMetrics);
IBonded layerData = null;
ILayerStack layerStack;
Error layerError = transport.GetLayerStack(requestMetrics.request_id, out layerStack);
if (layerError == null)
{
layerError = LayerStackUtils.ProcessOnSend(layerStack, MessageType.Request, sendContext, out layerData, logger);
}
if (layerError != null)
{
logger.Site().Error("{0}: Sending request {1}/{2} failed due to layer error (Code: {3}, Message: {4}).",
this, conversationId, methodName, layerError.error_code, layerError.message);
return Task.FromResult<IMessage>(Message.FromError(layerError));
}
// Pass the layer stack instance as state in response task completion source.
var responseCompletionSource = new TaskCompletionSource<IMessage>(layerStack);
var payload = Util.NewPayLoad(conversationId, PayloadType.Request, layerData, request, responseCompletionSource);
payload.headers.method_name = methodName;
writeQueue.Enqueue(payload);
return payload.outstandingRequest.Task;
}
private void SendEventAsync(string methodName, IMessage message)
{
var requestMetrics = Metrics.StartRequestMetrics(ConnectionMetrics);
var conversationId = AllocateNextConversationId();
var sendContext = new SimpleInMemSendContext(this, ConnectionMetrics, requestMetrics);
IBonded layerData = null;
ILayerStack layerStack;
Error layerError = transport.GetLayerStack(requestMetrics.request_id, out layerStack);
if (layerError == null)
{
layerError = LayerStackUtils.ProcessOnSend(layerStack, MessageType.Event, sendContext, out layerData, logger);
}
if (layerError != null)
{
logger.Site().Error("{0}: Sending event {1}/{2} failed due to layer error (Code: {3}, Message: {4}).",
this, conversationId, methodName, layerError.error_code, layerError.message);
return;
}
var payload = Util.NewPayLoad(conversationId, PayloadType.Event, layerData, message, null);
payload.headers.method_name = methodName;
writeQueue.Enqueue(payload);
}
private ulong AllocateNextConversationId()
{
// Interlocked.Add() handles overflow by wrapping, not throwing.
var newConversationId = Interlocked.Add(ref prevConversationId, 2);
if (newConversationId < 0)
{
throw new SimpleInMemProtocolErrorException("Exhausted conversation IDs");
}
return unchecked((ulong)newConversationId);
}
private void OnDisconnect()
{
logger.Site().Debug("{0}: Disconnecting.", this);
var args = new DisconnectedEventArgs(this, null);
if (connectionType == ConnectionType.Client)
{
parentListener.InvokeOnDisconnected(args);
}
metrics.Emit(ConnectionMetrics);
}
private void EnsureCorrectState(CnxState allowedStates, [CallerMemberName] string methodName = "<unknown>")
{
if ((state & allowedStates) == 0)
{
var message = $"Connection (${this}) is not in the correct state for the requested operation (${methodName}). Current state: ${state} Allowed states: ${allowedStates}";
throw new InvalidOperationException(message);
}
}
}
/// <summary>
/// Maintains a pair of Client-Server Connection instances.
/// <see cref="Id">Id</see> uniquely identifies a connected pair.
/// </summary>
internal class ConnectionPair
{
private readonly Guid id = Guid.NewGuid();
private readonly SimpleInMemConnection server;
private readonly SimpleInMemConnection client;
internal ConnectionPair(SimpleInMemConnection client, SimpleInMemConnection server)
{
if (server == null) throw new ArgumentNullException(nameof(server));
if (client == null) throw new ArgumentNullException(nameof(client));
if (server.ConnectionType != ConnectionType.Server) throw new ArgumentException($"{server.ToString()} - Invalid Server connection type: {server.ConnectionType}");
if (client.ConnectionType != ConnectionType.Client) throw new ArgumentException($"{client.ToString()} - Invalid Client connection type: {client.ConnectionType}");
if (server.IsPaired)
{
throw new ArgumentException($"{server.ToString()} - already paired connection.");
}
if (client.IsPaired)
{
throw new ArgumentException($"{client.ToString()} - already paired connection.");
}
this.server = server;
this.client = client;
}
internal Guid Id { get { return id; } }
internal SimpleInMemConnection Server { get { return server; } }
internal SimpleInMemConnection Client { get { return client; } }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace TimeForInsurance.Backend.API.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace Game_IfreannCorp
{
/// <summary>
/// This is a game component that implements IUpdateable.
/// </summary>
public class TankGame : Entity
{
Menu.MenuBody _Menu;
bool _MuteActive, _GameCommence, _LeftSide, _StageComplete;
Level _CurrentStage;
bool[] _Build;
int _StagePosition;
int _TotalScore;
bool _GameComplete;
Ending _Credits;
Intro _StageOpen;
bool _Introduction = true;
bool _Prepare = false;
public TankGame()
{
_GameComplete = false;
_TotalScore = 0;
_StagePosition = 0;
_Build = new bool[6];
_GameCommence = false;
_StageComplete = false;
}
public override void LoadContent()
{
_Menu = new Menu.MenuBody();
_Menu.LoadContent();
for (int i = 0; i < 5; i++)
{
_Build[i] = false;
}
}
public override void Update(GameTime gameTime)
{
if (_Menu._MuteActive)
_MuteActive = true;
else if (!_Menu._MuteActive)
_MuteActive = false;
if (_Menu._GameCommence)
{
_GameCommence = true;
_LeftSide = _Menu._LeftSide;
if (_Menu._Build)
{
_Build[0] = true;
_Menu._Build = false;
}
}
if (_StageComplete)
{
if (_StagePosition < 5)
{
_StagePosition++;
_Build[_StagePosition] = true;
_Introduction = true;
}
_StageComplete = false;
}
if (!_GameCommence)
_Menu.Update(gameTime);
else if (_GameCommence)
{
if (_Build[0])
{
_StageOpen = new Intro("Introduction/intro1", "Introduction/intro2", "Introduction/intro3");
_StageOpen.LoadContent();
_CurrentStage = new Level(0.9f, _TotalScore, _LeftSide, _MuteActive, "Space/Space", 1, "Stage1", 5, 5, 5);//10, 5, 10, 5, 15);
_CurrentStage.LoadContent();
_Build[0] = false;
}
if (_Build[1])
{
_StageOpen = new Intro("Introduction/intro4");
_StageOpen.LoadContent();
if (!_CurrentStage._ReBuild)
_TotalScore = _CurrentStage._Score;
_CurrentStage = new Level(0.7f, _TotalScore, _LeftSide, _MuteActive, "Landscape/planetTerrain", 2, "Stage2", 7, 5, 7, 5);//15, 5, 15, 7, 20, 10);
_CurrentStage.LoadContent();
_Build[1] = false;
}
if (_Build[2])
{
_StageOpen = new Intro("Introduction/intro5");
_StageOpen.LoadContent();
if (!_CurrentStage._ReBuild)
_TotalScore = _CurrentStage._Score;
_CurrentStage = new Level(0.7f, _TotalScore, _LeftSide, _MuteActive, "Cave/CaveL", 3, "Stage3", 5, 5, 5, 5, 5);//20, 6, 20, 5, 25, 8, 30);
_CurrentStage.LoadContent();
_Build[2] = false;
}
if (_Build[3])
{
_StageOpen = new Intro("Introduction/intro6");
_StageOpen.LoadContent();
if (!_CurrentStage._ReBuild)
_TotalScore = _CurrentStage._Score;
_CurrentStage = new Level(1.0f, _TotalScore, _LeftSide, _MuteActive, "Rough/Rough", 4, "Stage4", 5, 5, 5, 5, 5, 5);//15, 5, 20, 5, 20, 5, 20, 5);
_CurrentStage.LoadContent();
_Build[3] = false;
}
if (_Build[4])
{
_StageOpen = new Intro("Introduction/intro7");
_StageOpen.LoadContent();
if (!_CurrentStage._ReBuild)
_TotalScore = _CurrentStage._Score;
_CurrentStage = new Level(1.0f, _TotalScore, _LeftSide, _MuteActive, "Industry/industry", 5, "Stage5", 5, 5, 5, 5, 5, 5, 5, 5, 5);//15, 5, 20, 5, 20, 5, 20, 8, 25);
_CurrentStage.LoadContent();
_Build[4] = false;
}
if (_Build[5])
{
if (!_CurrentStage._ReBuild)
_TotalScore = _CurrentStage._Score;
_Credits = new Ending(_TotalScore);
_Credits.LoadContent();
_GameComplete = true;
_Build[5] = false;
}
if (!_GameComplete)
{
if (_Introduction)
_StageOpen.Update(gameTime);
else if (!_Introduction)
_CurrentStage.Update(gameTime);
}
if (!_StageOpen._Active)
{
_Introduction = false;
_Build[_StagePosition] = true;
_Prepare = true;
}
if (_GameComplete)
_Credits.Update(gameTime);
if (_CurrentStage._ReBuild)
{
Main.Instance._EnProjectiles.Clear();
Main.Instance._Enemies.Clear();
_Build[_StagePosition] = true;
}
if (_CurrentStage._NextStage)
{
_StageComplete = true;
_Introduction = true;
}
}
}
public override void Draw(GameTime gameTime)
{
if (!_GameCommence)
_Menu.Draw(gameTime);
else if (_GameCommence)
{
if (!_GameComplete)
{
if (_Introduction)
_StageOpen.Draw(gameTime);
else if (!_Introduction)
_CurrentStage.Draw(gameTime);
}
}
if (_GameComplete)
_Credits.Draw(gameTime);
}
}
}
| |
using System;
using UnityEngine;
public partial class LightShafts : MonoBehaviour
{
public LightShaftsShadowmapMode shadowmapMode = LightShaftsShadowmapMode.Dynamic;
public Camera[] cameras;
public Camera currentCamera;
public Vector3 size = new Vector3(10, 10, 20);
public float spotNear = 0.1f;
public float spotFar = 1.0f;
public LayerMask cullingMask = ~0;
public LayerMask colorFilterMask = 0;
public float brightness = 5;
public float brightnessColored = 5;
public float extinction = 0.5f;
public float minDistFromCamera = 0.0f;
public int shadowmapRes = 1024;
public Shader depthShader;
public Shader colorFilterShader;
public bool colored = false;
public float colorBalance = 1.0f;
public int epipolarLines = 256;
public int epipolarSamples = 512;
public Shader coordShader;
public Shader depthBreaksShader;
public Shader raymarchShader;
public Shader interpolateAlongRaysShader;
public Shader samplePositionsShader;
public Shader finalInterpolationShader;
public float depthThreshold = 0.5f;
public int interpolationStep = 32;
public bool showSamples = false;
public bool showInterpolatedSamples = false;
public float showSamplesBackgroundFade = 0.8f;
public bool attenuationCurveOn = false;
public AnimationCurve attenuationCurve;
private LightShaftsShadowmapMode m_ShadowmapModeOld = LightShaftsShadowmapMode.Dynamic;
private bool m_ShadowmapDirty = true;
private Camera m_ShadowmapCamera;
private RenderTexture m_Shadowmap;
private RenderTexture m_ColorFilter;
private RenderTexture m_CoordEpi;
private RenderTexture m_DepthEpi;
private Material m_CoordMaterial;
private Camera m_CoordsCamera;
private RenderTexture m_InterpolationEpi;
private Material m_DepthBreaksMaterial;
private RenderTexture m_RaymarchedLightEpi;
private Material m_RaymarchMaterial;
private RenderTexture m_InterpolateAlongRaysEpi;
private Material m_InterpolateAlongRaysMaterial;
private RenderTexture m_SamplePositions;
private Material m_SamplePositionsMaterial;
private Material m_FinalInterpolationMaterial;
private Texture2D m_AttenuationCurveTex;
private LightType m_LightType = LightType.Directional;
private bool m_DX11Support;
private bool m_MinRequirements;
private void InitLUTs()
{
if (m_AttenuationCurveTex)
{
return;
}
m_AttenuationCurveTex = new Texture2D(256, 1, TextureFormat.ARGB32, false, true);
m_AttenuationCurveTex.wrapMode = TextureWrapMode.Clamp;
m_AttenuationCurveTex.hideFlags = HideFlags.HideAndDontSave;
if (attenuationCurve == null || attenuationCurve.length == 0)
{
attenuationCurve = new AnimationCurve(new Keyframe(0, 1), new Keyframe(1, 1));
}
if (m_AttenuationCurveTex)
{
UpdateLUTs();
}
}
public void UpdateLUTs()
{
InitLUTs();
if (attenuationCurve == null)
{
return;
}
for (int i = 0; i < 256; ++i)
{
float v = Mathf.Clamp(attenuationCurve.Evaluate(i/255.0f), 0.0f, 1.0f);
m_AttenuationCurveTex.SetPixel(i, 0, new Color(v, v, v, v));
}
m_AttenuationCurveTex.Apply();
}
private void InitRenderTexture(ref RenderTexture rt, int width, int height, int depth, RenderTextureFormat format,
bool temp = true)
{
if (temp)
{
rt = RenderTexture.GetTemporary(width, height, depth, format);
}
else
{
if (rt != null)
{
if (rt.width == width && rt.height == height && rt.depth == depth && rt.format == format)
{
return;
}
rt.Release();
DestroyImmediate(rt);
}
rt = new RenderTexture(width, height, depth, format);
rt.hideFlags = HideFlags.HideAndDontSave;
}
}
private void InitShadowmap()
{
bool dynamic = (shadowmapMode == LightShaftsShadowmapMode.Dynamic);
if (dynamic && shadowmapMode != m_ShadowmapModeOld)
{
// Destroy static render textures, we only need temp now
if (m_Shadowmap)
{
m_Shadowmap.Release();
}
if (m_ColorFilter)
{
m_ColorFilter.Release();
}
}
InitRenderTexture(ref m_Shadowmap, shadowmapRes, shadowmapRes, 24, RenderTextureFormat.RFloat, dynamic);
m_Shadowmap.filterMode = FilterMode.Point;
m_Shadowmap.wrapMode = TextureWrapMode.Clamp;
if (colored)
{
InitRenderTexture(ref m_ColorFilter, shadowmapRes, shadowmapRes, 0, RenderTextureFormat.ARGB32, dynamic);
}
m_ShadowmapModeOld = shadowmapMode;
}
private void ReleaseShadowmap()
{
if (shadowmapMode == LightShaftsShadowmapMode.Static)
{
return;
}
RenderTexture.ReleaseTemporary(m_Shadowmap);
RenderTexture.ReleaseTemporary(m_ColorFilter);
}
private void InitEpipolarTextures()
{
epipolarLines = epipolarLines < 8 ? 8 : epipolarLines;
epipolarSamples = epipolarSamples < 4 ? 4 : epipolarSamples;
InitRenderTexture(ref m_CoordEpi, epipolarSamples, epipolarLines, 0, RenderTextureFormat.RGFloat);
m_CoordEpi.filterMode = FilterMode.Point;
InitRenderTexture(ref m_DepthEpi, epipolarSamples, epipolarLines, 0, RenderTextureFormat.RFloat);
m_DepthEpi.filterMode = FilterMode.Point;
InitRenderTexture(ref m_InterpolationEpi, epipolarSamples, epipolarLines, 0,
m_DX11Support ? RenderTextureFormat.RGInt : RenderTextureFormat.RGFloat);
m_InterpolationEpi.filterMode = FilterMode.Point;
InitRenderTexture(ref m_RaymarchedLightEpi, epipolarSamples, epipolarLines, 24,
RenderTextureFormat.ARGBFloat);
m_RaymarchedLightEpi.filterMode = FilterMode.Point;
InitRenderTexture(ref m_InterpolateAlongRaysEpi, epipolarSamples, epipolarLines, 0,
RenderTextureFormat.ARGBFloat);
m_InterpolateAlongRaysEpi.filterMode = FilterMode.Point;
}
private void InitMaterial(ref Material material, Shader shader)
{
if (material || !shader)
{
return;
}
material = new Material(shader);
material.hideFlags = HideFlags.HideAndDontSave;
}
private void InitMaterials()
{
InitMaterial(ref m_FinalInterpolationMaterial, finalInterpolationShader);
InitMaterial(ref m_CoordMaterial, coordShader);
InitMaterial(ref m_SamplePositionsMaterial, samplePositionsShader);
InitMaterial(ref m_RaymarchMaterial, raymarchShader);
InitMaterial(ref m_DepthBreaksMaterial, depthBreaksShader);
InitMaterial(ref m_InterpolateAlongRaysMaterial, interpolateAlongRaysShader);
}
private Mesh m_SpotMesh;
private float m_SpotMeshNear = -1;
private float m_SpotMeshFar = -1;
private float m_SpotMeshAngle = -1;
private float m_SpotMeshRange = -1;
private void InitSpotFrustumMesh()
{
if (!m_SpotMesh)
{
m_SpotMesh = new Mesh();
m_SpotMesh.hideFlags = HideFlags.HideAndDontSave;
}
Light l = GetComponent<Light>();
if (m_SpotMeshNear != spotNear || m_SpotMeshFar != spotFar || m_SpotMeshAngle != l.spotAngle ||
m_SpotMeshRange != l.range)
{
float far = l.range*spotFar;
float near = l.range*spotNear;
float tan = Mathf.Tan(l.spotAngle*Mathf.Deg2Rad*0.5f);
float halfwidthfar = far*tan;
float halfwidthnear = near*tan;
var vertices = (m_SpotMesh.vertices != null && m_SpotMesh.vertices.Length == 8)
? m_SpotMesh.vertices
: new Vector3[8];
vertices[0] = new Vector3(-halfwidthfar, -halfwidthfar, far);
vertices[1] = new Vector3(halfwidthfar, -halfwidthfar, far);
vertices[2] = new Vector3(halfwidthfar, halfwidthfar, far);
vertices[3] = new Vector3(-halfwidthfar, halfwidthfar, far);
vertices[4] = new Vector3(-halfwidthnear, -halfwidthnear, near);
vertices[5] = new Vector3(halfwidthnear, -halfwidthnear, near);
vertices[6] = new Vector3(halfwidthnear, halfwidthnear, near);
vertices[7] = new Vector3(-halfwidthnear, halfwidthnear, near);
m_SpotMesh.vertices = vertices;
if (m_SpotMesh.triangles == null || m_SpotMesh.triangles.Length != 36)
{
// far near top right left bottom
var triangles = new int[]
{
0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4, 3, 2, 6, 3, 6, 7, 2, 1, 5, 2, 5, 6, 0, 3, 7, 0, 7, 4, 5, 1, 0,
5, 0, 4
};
m_SpotMesh.triangles = triangles;
}
m_SpotMeshNear = spotNear;
m_SpotMeshFar = spotFar;
m_SpotMeshAngle = l.spotAngle;
m_SpotMeshRange = l.range;
}
}
public void UpdateLightType()
{
m_LightType = GetComponent<Light>().type;
}
public bool CheckMinRequirements()
{
if (m_MinRequirements)
{
return true;
}
m_DX11Support = SystemInfo.graphicsShaderLevel >= 50;
m_MinRequirements = SystemInfo.graphicsShaderLevel >= 30;
m_MinRequirements &= SystemInfo.supportsRenderTextures;
m_MinRequirements &= SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGFloat);
m_MinRequirements &= SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RFloat);
return m_MinRequirements;
}
private void InitResources()
{
UpdateLightType();
InitMaterials();
InitEpipolarTextures();
InitLUTs();
InitSpotFrustumMesh();
}
private void ReleaseResources()
{
ReleaseShadowmap();
RenderTexture.ReleaseTemporary(m_CoordEpi);
RenderTexture.ReleaseTemporary(m_DepthEpi);
RenderTexture.ReleaseTemporary(m_InterpolationEpi);
RenderTexture.ReleaseTemporary(m_RaymarchedLightEpi);
RenderTexture.ReleaseTemporary(m_InterpolateAlongRaysEpi);
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
namespace Microsoft.PythonTools.Debugger.DebugEngine {
// This class represents a pending breakpoint which is an abstract representation of a breakpoint before it is bound.
// When a user creates a new breakpoint, the pending breakpoint is created and is later bound. The bound breakpoints
// become children of the pending breakpoint.
class AD7PendingBreakpoint : IDebugPendingBreakpoint2 {
// The breakpoint request that resulted in this pending breakpoint being created.
private readonly IDebugBreakpointRequest2 _bpRequest;
private BP_REQUEST_INFO _bpRequestInfo;
private readonly AD7Engine _engine;
private readonly BreakpointManager _bpManager;
private readonly List<AD7BoundBreakpoint> _boundBreakpoints;
private bool _enabled;
private readonly bool _deleted;
public AD7PendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, AD7Engine engine, BreakpointManager bpManager) {
_bpRequest = pBPRequest;
BP_REQUEST_INFO[] requestInfo = new BP_REQUEST_INFO[1];
EngineUtils.CheckOk(_bpRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION | enum_BPREQI_FIELDS.BPREQI_CONDITION | enum_BPREQI_FIELDS.BPREQI_ALLFIELDS, requestInfo));
_bpRequestInfo = requestInfo[0];
_engine = engine;
_bpManager = bpManager;
_boundBreakpoints = new System.Collections.Generic.List<AD7BoundBreakpoint>();
_enabled = true;
_deleted = false;
}
private bool CanBind() {
// The Python engine only supports breakpoints on a file and line number. No other types of breakpoints are supported.
if (_deleted || _bpRequestInfo.bpLocation.bpLocationType != (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE) {
return false;
}
return true;
}
// Get the document context for this pending breakpoint. A document context is a abstract representation of a source file
// location.
public AD7DocumentContext GetDocumentContext(PythonBreakpoint address) {
IDebugDocumentPosition2 docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(_bpRequestInfo.bpLocation.unionmember2));
string documentName;
EngineUtils.CheckOk(docPosition.GetFileName(out documentName));
// Get the location in the document that the breakpoint is in.
TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
TEXT_POSITION[] endPosition = new TEXT_POSITION[1];
EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
AD7MemoryAddress codeContext = new AD7MemoryAddress(_engine, documentName, startPosition[0].dwLine);
return new AD7DocumentContext(documentName, startPosition[0], startPosition[0], codeContext, FrameKind.Python);
}
// Remove all of the bound breakpoints for this pending breakpoint
public void ClearBoundBreakpoints() {
lock (_boundBreakpoints) {
for (int i = _boundBreakpoints.Count - 1; i >= 0; i--) {
((IDebugBoundBreakpoint2)_boundBreakpoints[i]).Delete();
}
}
}
// Called by bound breakpoints when they are being deleted.
public void OnBoundBreakpointDeleted(AD7BoundBreakpoint boundBreakpoint) {
lock (_boundBreakpoints) {
_boundBreakpoints.Remove(boundBreakpoint);
}
}
#region IDebugPendingBreakpoint2 Members
// Binds this pending breakpoint to one or more code locations.
int IDebugPendingBreakpoint2.Bind() {
if (CanBind()) {
IDebugDocumentPosition2 docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(_bpRequestInfo.bpLocation.unionmember2));
// Get the name of the document that the breakpoint was put in
string documentName;
EngineUtils.CheckOk(docPosition.GetFileName(out documentName));
// Get the location in the document that the breakpoint is in.
TEXT_POSITION[] startPosition = new TEXT_POSITION[1];
TEXT_POSITION[] endPosition = new TEXT_POSITION[1];
EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition));
lock (_boundBreakpoints) {
if (_bpRequestInfo.guidLanguage == DebuggerConstants.guidLanguagePython) {
var bp = _engine.Process.AddBreakpoint(
documentName,
(int)(startPosition[0].dwLine + 1),
_bpRequestInfo.bpCondition.styleCondition.ToPython(),
_bpRequestInfo.bpCondition.bstrCondition,
_bpRequestInfo.bpPassCount.stylePassCount.ToPython(),
(int)_bpRequestInfo.bpPassCount.dwPassCount);
AD7BreakpointResolution breakpointResolution = new AD7BreakpointResolution(_engine, bp, GetDocumentContext(bp));
AD7BoundBreakpoint boundBreakpoint = new AD7BoundBreakpoint(_engine, bp, this, breakpointResolution, _enabled);
_boundBreakpoints.Add(boundBreakpoint);
_bpManager.AddBoundBreakpoint(bp, boundBreakpoint);
if (_enabled) {
TaskHelpers.RunSynchronouslyOnUIThread(ct => bp.AddAsync(ct));
}
return VSConstants.S_OK;
} else if (_bpRequestInfo.guidLanguage == DebuggerConstants.guidLanguageDjangoTemplate) {
// bind a Django template
var bp = _engine.Process.AddDjangoBreakpoint(
documentName,
(int)(startPosition[0].dwLine + 1)
);
AD7BreakpointResolution breakpointResolution = new AD7BreakpointResolution(_engine, bp, GetDocumentContext(bp));
AD7BoundBreakpoint boundBreakpoint = new AD7BoundBreakpoint(_engine, bp, this, breakpointResolution, _enabled);
_boundBreakpoints.Add(boundBreakpoint);
_bpManager.AddBoundBreakpoint(bp, boundBreakpoint);
if (_enabled) {
TaskHelpers.RunSynchronouslyOnUIThread(ct => bp.AddAsync(ct));
}
return VSConstants.S_OK;
}
}
}
// The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
// The Python engine does not support this.
// TODO: send an instance of IDebugBreakpointErrorEvent2 to the UI and return a valid instance of IDebugErrorBreakpoint2 from
// IDebugPendingBreakpoint2::EnumErrorBreakpoints. The debugger will then display information about why the breakpoint did not
// bind to the user.
return VSConstants.S_FALSE;
}
// Determines whether this pending breakpoint can bind to a code location.
int IDebugPendingBreakpoint2.CanBind(out IEnumDebugErrorBreakpoints2 ppErrorEnum) {
ppErrorEnum = null;
if (!CanBind()) {
// Called to determine if a pending breakpoint can be bound.
// The breakpoint may not be bound for many reasons such as an invalid location, an invalid expression, etc...
// TODO: return a valid enumeration of IDebugErrorBreakpoint2. The debugger will then display information about why
// the breakpoint did not bind to the user.
ppErrorEnum = null;
return VSConstants.S_FALSE;
}
return VSConstants.S_OK;
}
// Deletes this pending breakpoint and all breakpoints bound from it.
int IDebugPendingBreakpoint2.Delete() {
lock (_boundBreakpoints) {
for (int i = _boundBreakpoints.Count - 1; i >= 0; i--) {
((IDebugBoundBreakpoint2)_boundBreakpoints[i]).Delete();
}
}
return VSConstants.S_OK;
}
// Toggles the enabled state of this pending breakpoint.
int IDebugPendingBreakpoint2.Enable(int fEnable) {
lock (_boundBreakpoints) {
_enabled = fEnable == 0 ? false : true;
foreach (AD7BoundBreakpoint bp in _boundBreakpoints) {
((IDebugBoundBreakpoint2)bp).Enable(fEnable);
}
}
return VSConstants.S_OK;
}
// Enumerates all breakpoints bound from this pending breakpoint
int IDebugPendingBreakpoint2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) {
lock (_boundBreakpoints) {
IDebugBoundBreakpoint2[] boundBreakpoints = _boundBreakpoints.ToArray();
ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints);
}
return VSConstants.S_OK;
}
// Enumerates all error breakpoints that resulted from this pending breakpoint.
int IDebugPendingBreakpoint2.EnumErrorBreakpoints(enum_BP_ERROR_TYPE bpErrorType, out IEnumDebugErrorBreakpoints2 ppEnum) {
// Called when a pending breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc...
// TODO: send an instance of IDebugBreakpointErrorEvent2 to the UI and return a valid enumeration of IDebugErrorBreakpoint2
// from IDebugPendingBreakpoint2::EnumErrorBreakpoints. The debugger will then display information about why the breakpoint
// did not bind to the user.
ppEnum = null;
return VSConstants.E_NOTIMPL;
}
// Gets the breakpoint request that was used to create this pending breakpoint
int IDebugPendingBreakpoint2.GetBreakpointRequest(out IDebugBreakpointRequest2 ppBPRequest) {
ppBPRequest = _bpRequest;
return VSConstants.S_OK;
}
// Gets the state of this pending breakpoint.
int IDebugPendingBreakpoint2.GetState(PENDING_BP_STATE_INFO[] pState) {
if (_deleted) {
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DELETED;
} else if (_enabled) {
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_ENABLED;
} else {
pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DISABLED;
}
return VSConstants.S_OK;
}
int IDebugPendingBreakpoint2.SetCondition(BP_CONDITION bpCondition) {
_bpRequestInfo.bpCondition = bpCondition;
return VSConstants.S_OK;
}
int IDebugPendingBreakpoint2.SetPassCount(BP_PASSCOUNT bpPassCount) {
_bpRequestInfo.bpPassCount = bpPassCount;
return VSConstants.S_OK;
}
// Toggles the virtualized state of this pending breakpoint. When a pending breakpoint is virtualized,
// the debug engine will attempt to bind it every time new code loads into the program.
// The Python engine does not support this.
int IDebugPendingBreakpoint2.Virtualize(int fVirtualize) {
return VSConstants.S_OK;
}
#endregion
}
static class BreakpointEnumExtensions {
public static PythonBreakpointConditionKind ToPython(this enum_BP_COND_STYLE style) {
switch (style) {
case enum_BP_COND_STYLE.BP_COND_NONE:
return PythonBreakpointConditionKind.Always;
case enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED:
return PythonBreakpointConditionKind.WhenChanged;
case enum_BP_COND_STYLE.BP_COND_WHEN_TRUE:
return PythonBreakpointConditionKind.WhenTrue;
default:
throw new ArgumentException(Strings.UnrecognizedEnumValue.FormatUI(typeof(enum_BP_COND_STYLE)), nameof(style));
}
}
public static PythonBreakpointPassCountKind ToPython(this enum_BP_PASSCOUNT_STYLE style) {
switch (style) {
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_NONE:
return PythonBreakpointPassCountKind.Always;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_MOD:
return PythonBreakpointPassCountKind.Every;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL:
return PythonBreakpointPassCountKind.WhenEqual;
case enum_BP_PASSCOUNT_STYLE.BP_PASSCOUNT_EQUAL_OR_GREATER:
return PythonBreakpointPassCountKind.WhenEqualOrGreater;
default:
throw new ArgumentException(Strings.UnrecognizedEnumValue.FormatUI(typeof(enum_BP_PASSCOUNT_STYLE)), nameof(style));
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// GameCore
// ----------------------------------------------------------------------------
// This is the core of the gametype functionality. The "Default Game". All of
// the gametypes share or over-ride the scripted controls for the default game.
//
// The desired Game Type must be added to each mission's LevelInfo object.
// - gameType = "";
// - gameType = "Deathmatch";
// If this information is missing then the GameCore will default to Deathmatch.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Basic Functionality
// ----------------------------------------------------------------------------
// Static function to create the Game object.
// Makes use of theLevelInfo object to determine the game type.
// Returns: The Game object
function GameCore::createGame()
{
// Create Game Objects
// Here begins our gametype functionality
if (isObject(theLevelInfo))
{
$Server::MissionType = theLevelInfo.gameType; //MissionInfo.gametype;
//echo("\c4 -> Parsed mission Gametype: "@ theLevelInfo.gameType); //MissionInfo.gametype);
}
else
{
$Server::MissionType = "";
}
if ($Server::MissionType $= "")
$Server::MissionType = "Deathmatch"; //Default gametype, just in case
// Note: The Game object will be cleaned up by MissionCleanup. Therefore its lifetime is
// limited to that of the mission.
new ScriptObject(Game)
{
class = $Server::MissionType @"Game";
superClass = GameCore;
};
// Activate the Game specific packages that are defined by the level's gameType
Game.activatePackages();
return Game;
}
function GameCore::activatePackages(%game)
{
echo (%game @"\c4 -> activatePackages");
// Activate any mission specific game package
if (isPackage(%game.class) && %game.class !$= GameCore)
activatePackage(%game.class);
}
function GameCore::deactivatePackages(%game)
{
echo (%game @"\c4 -> deactivatePackages");
// Deactivate any mission specific game package
if (isPackage(%game.class) && %game.class !$= GameCore)
deactivatePackage(%game.class);
}
function GameCore::onAdd(%game)
{
//echo (%game @"\c4 -> onAdd");
}
function GameCore::onRemove(%game)
{
//echo (%game @"\c4 -> onRemove");
// Clean up
%game.deactivatePackages();
}
// ----------------------------------------------------------------------------
// Package
// ----------------------------------------------------------------------------
// The GameCore package overides functions loadMissionStage2(), endMission(),
// and function resetMission() from "core/scripts/server/missionLoad.cs" in
// order to create our Game object, which allows our gameType functionality to
// be initiated.
package GameCore
{
function loadMissionStage2()
{
//echo("\c4 -> loadMissionStage2() override success");
echo("*** Stage 2 load");
// Create the mission group off the ServerGroup
$instantGroup = ServerGroup;
// Make sure the mission exists
%file = $Server::MissionFile;
if( !isFile( %file ) )
{
$Server::LoadFailMsg = "Could not find mission \"" @ %file @ "\"";
}
else
{
// Calculate the mission CRC. The CRC is used by the clients
// to caching mission lighting.
$missionCRC = getFileCRC( %file );
// Exec the mission. The MissionGroup (loaded components) is added to the ServerGroup
exec(%file);
if( !isObject(MissionGroup) )
{
$Server::LoadFailMsg = "No 'MissionGroup' found in mission \"" @ %file @ "\".";
}
}
if( $Server::LoadFailMsg !$= "" )
{
// Inform clients that are already connected
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
messageClient(ClientGroup.getObject(%clientIndex), 'MsgLoadFailed', $Server::LoadFailMsg);
return;
}
// Set mission name.
if( isObject( theLevelInfo ) )
$Server::MissionName = theLevelInfo.levelName;
// Mission cleanup group. This is where run time components will reside. The MissionCleanup
// group will be added to the ServerGroup.
new SimGroup(MissionCleanup);
// Make the MissionCleanup group the place where all new objects will automatically be added.
$instantGroup = MissionCleanup;
// Create the Game object
GameCore::createGame();
// Construct MOD paths
pathOnMissionLoadDone();
// Mission loading done...
echo("*** Mission loaded");
// Start all the clients in the mission
$missionRunning = true;
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
ClientGroup.getObject(%clientIndex).loadMission();
// Go ahead and launch the mission
Game.onMissionLoaded();
}
function endMission()
{
//echo("\c4 -> endMission() override success");
// If there is no MissionGroup then there is no running mission.
// It may have already been cleaned up.
if (!isObject(MissionGroup))
return;
echo("*** ENDING MISSION");
// Inform the game code we're done.
Game.onMissionEnded();
// Inform the clients
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
{
// clear ghosts and paths from all clients
%cl = ClientGroup.getObject(%clientIndex);
%cl.endMission();
%cl.resetGhosting();
%cl.clearPaths();
}
// Delete everything
MissionGroup.delete();
MissionCleanup.delete(); // Note: Will also clean up the Game object
// With MissionCleanup gone, make the ServerGroup the default place to put objects
$instantGroup = ServerGroup;
clearServerpaths();
}
// resetMission() is very game specific. To get the most out of it you'll
// need to expand on what is here, such as recreating runtime objects etc.
function resetMission()
{
//echo("\c4 -> resetMission() override success");
echo("*** MISSION RESET");
// Remove any temporary mission objects
// NOTE: This will likely remove any player objects as well so
// use resetMission() with caution.
MissionCleanup.delete();
$instantGroup = ServerGroup;
new SimGroup(MissionCleanup);
$instantGroup = MissionCleanup;
clearServerpaths();
// Recreate the Game object
GameCore::createGame();
// Construct MOD paths
pathOnMissionLoadDone();
// Allow the Game object to reset the mission
Game.onMissionReset();
}
// We also need to override function GameConnection::onConnect() from
// "core/scripts/server/clientConnection.cs" in order to initialize, reset,
// and pass some client scoring variables to playerList.gui -- the scoreHUD.
function GameConnection::onConnect(%client, %name)
{
// Send down the connection error info, the client is responsible for
// displaying this message if a connection error occurs.
messageClient(%client, 'MsgConnectionError',"",$Pref::Server::ConnectionError);
// Send mission information to the client
sendLoadInfoToClient(%client);
// Simulated client lag for testing...
// %client.setSimulatedNetParams(0.1, 30);
// Get the client's unique id:
// %authInfo = %client.getAuthInfo();
// %client.guid = getField(%authInfo, 3);
%client.guid = 0;
addToServerGuidList(%client.guid);
// Set admin status
if (%client.getAddress() $= "local")
{
%client.isAdmin = true;
%client.isSuperAdmin = true;
}
else
{
%client.isAdmin = false;
%client.isSuperAdmin = false;
}
// Save client preferences on the connection object for later use.
%client.gender = "Male";
%client.armor = "Light";
%client.race = "Human";
%client.setPlayerName(%name);
%client.team = "";
%client.score = 0;
%client.kills = 0;
%client.deaths = 0;
//
echo("CADD: "@ %client @" "@ %client.getAddress());
// If the mission is running, go ahead download it to the client
if ($missionRunning)
{
%client.loadMission();
}
else if ($Server::LoadFailMsg !$= "")
{
messageClient(%client, 'MsgLoadFailed', $Server::LoadFailMsg);
}
$Server::PlayerCount++;
}
function GameConnection::onClientEnterGame(%this)
{
Game.onClientEnterGame(%this);
}
function GameConnection::onClientLeaveGame(%this)
{
// If this mission has ended before the client has left the game then
// the Game object will have already been cleaned up. See endMission()
// in the GameCore package.
if (isObject(Game))
{
Game.onClientLeaveGame(%this);
}
}
// Need to supersede this "core" function in order to properly re-spawn a
// player after he/she is killed.
// This will also allow the differing gametypes to more easily have a unique
// method for spawn handling without needless duplication of code.
function GameConnection::spawnPlayer(%this, %spawnPoint)
{
Game.spawnPlayer(%this, %spawnPoint);
}
function endGame()
{
Game.endGame();
}
};
// end of our package... now activate it!
activatePackage(GameCore);
// ----------------------------------------------------------------------------
// Game Control Functions
// ----------------------------------------------------------------------------
function GameCore::onMissionLoaded(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onMissionLoaded");
//set up the game and game variables
%game.initGameVars(%game);
$Game::Duration = %game.duration;
$Game::EndGameScore = %game.endgameScore;
$Game::EndGamePause = %game.endgamePause;
physicsStartSimulation("server");
%game.startGame();
}
function GameCore::onMissionEnded(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onMissionEnded");
// Called by endMission(), right before the mission is destroyed
// Normally the game should be ended first before the next
// mission is loaded, this is here in case loadMission has been
// called directly. The mission will be ended if the server
// is destroyed, so we only need to cleanup here.
physicsStopSimulation("server");
%game.endGame();
cancel($Game::Schedule);
$Game::Running = false;
$Game::Cycling = false;
}
function GameCore::onMissionReset(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onMissionReset");
}
function GameCore::startGame(%game)
{
// This is where the game play should start
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onStartGame");
if ($Game::Running)
{
error("startGame: End the game first!");
return;
}
// Inform the client we're starting up
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
{
%cl = ClientGroup.getObject(%clientIndex);
commandToClient(%cl, 'GameStart');
// Other client specific setup..
%cl.score = 0;
%cl.kills = 0;
%cl.deaths = 0;
}
// Start the game timer
if ($Game::Duration)
$Game::Schedule = %game.schedule($Game::Duration * 1000, "onGameDurationEnd");
$Game::Running = true;
// // Start the AIManager
// new ScriptObject(AIManager) {};
// MissionCleanup.add(AIManager);
// AIManager.think();
}
function GameCore::endGame(%game, %client)
{
// This is where the game play should end
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::endGame");
if (!$Game::Running)
{
error("endGame: No game running!");
return;
}
// // Stop the AIManager
// AIManager.delete();
// Stop any game timers
cancel($Game::Schedule);
for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)
{
%cl = ClientGroup.getObject(%clientIndex);
commandToClient(%cl, 'GameEnd', $Game::EndGamePause);
}
$Game::Running = false;
}
function GameCore::cycleGame(%game)
{
if (%game.allowCycling)
{
// Cycle to the next mission
cycleGame();
}
else
{
// We're done with the whole game
endMission();
// Destroy server to remove all connected clients after they've seen the
// end game GUI.
schedule($Game::EndGamePause * 1000, 0, "gameCoreDestroyServer", $Server::Session);
}
}
function GameCore::onGameDurationEnd(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onGameDurationEnd");
if ($Game::Duration && (!EditorIsActive() && !GuiEditorIsActive()))
%game.cycleGame();
}
// ----------------------------------------------------------------------------
// Game Setup
// ----------------------------------------------------------------------------
function GameCore::initGameVars(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::initGameVars");
//-----------------------------------------------------------------------------
// What kind of "player" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
//-----------------------------------------------------------------------------
$Game::DefaultPlayerClass = "Player";
$Game::DefaultPlayerDataBlock = "DefaultPlayerData";
$Game::DefaultPlayerSpawnGroups = "PlayerSpawnPoints";
//-----------------------------------------------------------------------------
// What kind of "camera" is spawned is either controlled directly by the
// SpawnSphere or it defaults back to the values set here. This also controls
// which SimGroups to attempt to select the spawn sphere's from by walking down
// the list of SpawnGroups till it finds a valid spawn object.
//-----------------------------------------------------------------------------
$Game::DefaultCameraClass = "Camera";
$Game::DefaultCameraDataBlock = "Observer";
$Game::DefaultCameraSpawnGroups = "CameraSpawnPoints PlayerSpawnPoints";
// Set the gameplay parameters
%game.duration = $Game::Duration;
%game.endgameScore = $Game::EndGameScore;
%game.endgamePause = $Game::EndGamePause;
%game.allowCycling = false; // Is mission cycling allowed?
}
// ----------------------------------------------------------------------------
// Client Management
// ----------------------------------------------------------------------------
function GameCore::onClientEnterGame(%game, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onClientEntergame");
// Sync the client's clocks to the server's
commandToClient(%client, 'SyncClock', $Sim::Time - $Game::StartTime);
// Find a spawn point for the camera
// This function currently relies on some helper functions defined in
// core/scripts/server/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
%cameraSpawnPoint = pickCameraSpawnPoint($Game::DefaultCameraSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
%client.spawnCamera(%cameraSpawnPoint);
// Setup game parameters, the onConnect method currently starts
// everyone with a 0 score.
%client.score = 0;
%client.kills = 0;
%client.deaths = 0;
// weaponHUD
%client.RefreshWeaponHud(0, "", "");
// Prepare the player object.
%game.preparePlayer(%client);
// Inform the client of all the other clients
%count = ClientGroup.getCount();
for (%cl = 0; %cl < %count; %cl++)
{
%other = ClientGroup.getObject(%cl);
if ((%other != %client))
{
// These should be "silent" versions of these messages...
messageClient(%client, 'MsgClientJoin', "",
%other.playerName,
%other,
%other.sendGuid,
%other.team,
%other.score,
%other.kills,
%other.deaths,
%other.isAIControlled(),
%other.isAdmin,
%other.isSuperAdmin);
}
}
// Inform the client we've joined up
messageClient(%client,
'MsgClientJoin', '\c2Welcome to the Torque demo app %1.',
%client.playerName,
%client,
%client.sendGuid,
%client.team,
%client.score,
%client.kills,
%client.deaths,
%client.isAiControlled(),
%client.isAdmin,
%client.isSuperAdmin);
// Inform all the other clients of the new guy
messageAllExcept(%client, -1, 'MsgClientJoin', '\c1%1 joined the game.',
%client.playerName,
%client,
%client.sendGuid,
%client.team,
%client.score,
%client.kills,
%client.deaths,
%client.isAiControlled(),
%client.isAdmin,
%client.isSuperAdmin);
}
function GameCore::onClientLeaveGame(%game, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onClientLeaveGame");
// Cleanup the camera
if (isObject(%client.camera))
%client.camera.delete();
// Cleanup the player
if (isObject(%client.player))
%client.player.delete();
}
// Added this stage to creating a player so game types can override it easily.
// This is a good place to initiate team selection.
function GameCore::preparePlayer(%game, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::preparePlayer");
// Find a spawn point for the player
// This function currently relies on some helper functions defined in
// core/scripts/spawn.cs. For custom spawn behaviors one can either
// override the properties on the SpawnSphere's or directly override the
// functions themselves.
%playerSpawnPoint = pickPlayerSpawnPoint($Game::DefaultPlayerSpawnGroups);
// Spawn a camera for this client using the found %spawnPoint
//%client.spawnPlayer(%playerSpawnPoint);
%game.spawnPlayer(%client, %playerSpawnPoint);
// Starting equipment
%game.loadOut(%client.player);
}
function GameCore::loadOut(%game, %player)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::loadOut");
%player.clearWeaponCycle();
%player.setInventory(Ryder, 1);
%player.setInventory(RyderClip, %player.maxInventory(RyderClip));
%player.setInventory(RyderAmmo, %player.maxInventory(RyderAmmo)); // Start the gun loaded
%player.addToWeaponCycle(Ryder);
%player.setInventory(Lurker, 1);
%player.setInventory(LurkerClip, %player.maxInventory(LurkerClip));
%player.setInventory(LurkerAmmo, %player.maxInventory(LurkerAmmo)); // Start the gun loaded
%player.addToWeaponCycle(Lurker);
%player.setInventory(LurkerGrenadeLauncher, 1);
%player.setInventory(LurkerGrenadeAmmo, %player.maxInventory(LurkerGrenadeAmmo));
%player.addToWeaponCycle(LurkerGrenadeLauncher);
%player.setInventory(ProxMine, %player.maxInventory(ProxMine));
%player.addToWeaponCycle(ProxMine);
%player.setInventory(DeployableTurret, %player.maxInventory(DeployableTurret));
%player.addToWeaponCycle(DeployableTurret);
if (%player.getDatablock().mainWeapon.image !$= "")
{
%player.mountImage(%player.getDatablock().mainWeapon.image, 0);
}
else
{
%player.mountImage(Lurker, 0);
}
}
// Customized kill message for falling deaths
function sendMsgClientKilled_Impact( %msgType, %client, %sourceClient, %damLoc )
{
messageAll( %msgType, '%1 fell to his death!', %client.playerName );
}
// Customized kill message for suicides
function sendMsgClientKilled_Suicide( %msgType, %client, %sourceClient, %damLoc )
{
messageAll( %msgType, '%1 takes his own life!', %client.playerName );
}
// Default death message
function sendMsgClientKilled_Default( %msgType, %client, %sourceClient, %damLoc )
{
if ( %sourceClient == %client )
sendMsgClientKilled_Suicide(%client, %sourceClient, %damLoc);
else if ( %sourceClient.team !$= "" && %sourceClient.team $= %client.team )
messageAll( %msgType, '%1 killed by %2 - friendly fire!', %client.playerName, %sourceClient.playerName );
else
messageAll( %msgType, '%1 gets nailed by %2!', %client.playerName, %sourceClient.playerName );
}
function GameCore::onDeath(%game, %client, %sourceObject, %sourceClient, %damageType, %damLoc)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::onDeath");
// clear the weaponHUD
%client.RefreshWeaponHud(0, "", "");
// Clear out the name on the corpse
%client.player.setShapeName("");
// Update the numerical Health HUD
%client.player.updateHealth();
// Switch the client over to the death cam and unhook the player object.
if (isObject(%client.camera) && isObject(%client.player))
{
%client.camera.setMode("Corpse", %client.player);
%client.setControlObject(%client.camera);
}
%client.player = 0;
// Display damage appropriate kill message
%sendMsgFunction = "sendMsgClientKilled_" @ %damageType;
if ( !isFunction( %sendMsgFunction ) )
%sendMsgFunction = "sendMsgClientKilled_Default";
call( %sendMsgFunction, 'MsgClientKilled', %client, %sourceClient, %damLoc );
// Dole out points and check for win
if ( %damageType $= "Suicide" || %sourceClient == %client )
{
%game.incDeaths( %client, 1, true );
%game.incScore( %client, -1, false );
}
else
{
%game.incDeaths( %client, 1, false );
%game.incScore( %sourceClient, 1, true );
%game.incKills( %sourceClient, 1, false );
// If the game may be ended by a client getting a particular score, check that now.
if ( $Game::EndGameScore > 0 && %sourceClient.kills >= $Game::EndGameScore )
%game.cycleGame();
}
}
// ----------------------------------------------------------------------------
// Scoring
// ----------------------------------------------------------------------------
function GameCore::incKills(%game, %client, %kill, %dontMessageAll)
{
%client.kills += %kill;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function GameCore::incDeaths(%game, %client, %death, %dontMessageAll)
{
%client.deaths += %death;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function GameCore::incScore(%game, %client, %score, %dontMessageAll)
{
%client.score += %score;
if( !%dontMessageAll )
messageAll('MsgClientScoreChanged', "", %client.score, %client.kills, %client.deaths, %client);
}
function GameCore::getScore(%client) { return %client.score; }
function GameCore::getKills(%client) { return %client.kills; }
function GameCore::getDeaths(%client) { return %client.deaths; }
function GameCore::getTeamScore(%client)
{
%score = %client.score;
if ( %client.team !$= "" )
{
// Compute team score
for (%i = 0; %i < ClientGroup.getCount(); %i++)
{
%other = ClientGroup.getObject(%i);
if ((%other != %client) && (%other.team $= %client.team))
%score += %other.score;
}
}
return %score;
}
// ----------------------------------------------------------------------------
// Spawning
// ----------------------------------------------------------------------------
//.logicking .hack add '1' as sufix because namespace linkage was damaged
function GameCore::spawnPlayer1(%game, %client, %spawnPoint, %noControl)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::spawnPlayer");
if (isObject(%client.player))
{
// The client should not already have a player. Assigning
// a new one could result in an uncontrolled player object.
error("Attempting to create a player for a client that already has one!");
}
// Attempt to treat %spawnPoint as an object
if (getWordCount(%spawnPoint) == 1 && isObject(%spawnPoint))
{
// Defaults
%spawnClass = $Game::DefaultPlayerClass;
%spawnDataBlock = $Game::DefaultPlayerDataBlock;
// Overrides by the %spawnPoint
if (isDefined("%spawnPoint.spawnClass"))
{
%spawnClass = %spawnPoint.spawnClass;
%spawnDataBlock = %spawnPoint.spawnDatablock;
}
else if (isDefined("%spawnPoint.spawnDatablock"))
{
// This may seem redundant given the above but it allows
// the SpawnSphere to override the datablock without
// overriding the default player class
%spawnDataBlock = %spawnPoint.spawnDatablock;
}
%spawnProperties = %spawnPoint.spawnProperties;
%spawnScript = %spawnPoint.spawnScript;
// Spawn with the engine's Sim::spawnObject() function
%player = spawnObject(%spawnClass, %spawnDatablock, "",
%spawnProperties, %spawnScript);
// If we have an object do some initial setup
if (isObject(%player))
{
// Pick a location within the spawn sphere.
%spawnLocation = GameCore::pickPointInSpawnSphere(%player, %spawnPoint);
%player.setTransform(%spawnLocation);
}
else
{
// If we weren't able to create the player object then warn the user
// When the player clicks OK in one of these message boxes, we will fall through
// to the "if (!isObject(%player))" check below.
if (isDefined("%spawnDatablock"))
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
" and datablock " @ %spawnDatablock @ ".\n\nStarting as an Observer instead.",
"");
}
else
{
MessageBoxOK("Spawn Player Failed",
"Unable to create a player with class " @ %spawnClass @
".\n\nStarting as an Observer instead.",
"");
}
}
}
else
{
// Create a default player
%player = spawnObject($Game::DefaultPlayerClass, $Game::DefaultPlayerDataBlock);
if (!%player.isMemberOfClass("Player"))
warn("Trying to spawn a class that does not derive from Player.");
// Treat %spawnPoint as a transform
%player.setTransform(%spawnPoint);
}
// If we didn't actually create a player object then bail
if (!isObject(%player))
{
// Make sure we at least have a camera
%client.spawnCamera(%spawnPoint);
return;
}
// Update the default camera to start with the player
if (isObject(%client.camera) && !isDefined("%noControl"))
{
if (%player.getClassname() $= "Player")
%client.camera.setTransform(%player.getEyeTransform());
else
%client.camera.setTransform(%player.getTransform());
}
// Add the player object to MissionCleanup so that it
// won't get saved into the level files and will get
// cleaned up properly
MissionCleanup.add(%player);
// Store the client object on the player object for
// future reference
%player.client = %client;
// If the player's client has some owned turrets, make sure we let them
// know that we're a friend too.
if (%client.ownedTurrets)
{
for (%i=0; %i<%client.ownedTurrets.getCount(); %i++)
{
%turret = %client.ownedTurrets.getObject(%i);
%turret.addToIgnoreList(%player);
}
}
// Player setup...
if (%player.isMethod("setShapeName"))
%player.setShapeName(%client.playerName);
if (%player.isMethod("setEnergyLevel"))
%player.setEnergyLevel(%player.getDataBlock().maxEnergy);
if (!isDefined("%client.skin"))
{
// Determine which character skins are not already in use
%availableSkins = %player.getDatablock().availableSkins; // TAB delimited list of skin names
%count = ClientGroup.getCount();
for (%cl = 0; %cl < %count; %cl++)
{
%other = ClientGroup.getObject(%cl);
if (%other != %client)
{
%availableSkins = strreplace(%availableSkins, %other.skin, "");
%availableSkins = strreplace(%availableSkins, "\t\t", ""); // remove empty fields
}
}
// Choose a random, unique skin for this client
%count = getFieldCount(%availableSkins);
%client.skin = addTaggedString( getField(%availableSkins, getRandom(%count)) );
}
%player.setSkinName(%client.skin);
// Give the client control of the player
%client.player = %player;
// Give the client control of the camera if in the editor
if( $startWorldEditor )
{
%control = %client.camera;
%control.mode = "Fly";
EditorGui.syncCameraGui();
}
else
%control = %player;
// Allow the player/camera to receive move data from the GameConnection. Without this
// the user is unable to control the player/camera.
if (!isDefined("%noControl"))
%client.setControlObject(%control);
}
function GameCore::pickPointInSpawnSphere(%objectToSpawn, %spawnSphere)
{
%SpawnLocationFound = false;
%attemptsToSpawn = 0;
while(!%SpawnLocationFound && (%attemptsToSpawn < 5))
{
%sphereLocation = %spawnSphere.getTransform();
// Attempt to spawn the player within the bounds of the spawnsphere.
%angleY = mDegToRad(getRandom(0, 100) * m2Pi());
%angleXZ = mDegToRad(getRandom(0, 100) * m2Pi());
%sphereLocation = setWord( %sphereLocation, 0, getWord(%sphereLocation, 0) + (mCos(%angleY) * mSin(%angleXZ) * getRandom(-%spawnSphere.radius, %spawnSphere.radius)));
%sphereLocation = setWord( %sphereLocation, 1, getWord(%sphereLocation, 1) + (mCos(%angleXZ) * getRandom(-%spawnSphere.radius, %spawnSphere.radius)));
%SpawnLocationFound = true;
// Now have to check that another object doesn't already exist at this spot.
// Use the bounding box of the object to check if where we are about to spawn in is
// clear.
%boundingBoxSize = %objectToSpawn.getDatablock().boundingBox;
%searchRadius = getWord(%boundingBoxSize, 0);
%boxSizeY = getWord(%boundingBoxSize, 1);
// Use the larger dimention as the radius to search
if (%boxSizeY > %searchRadius)
%searchRadius = %boxSizeY;
// Search a radius about the area we're about to spawn for players.
initContainerRadiusSearch( %sphereLocation, %searchRadius, $TypeMasks::PlayerObjectType );
while ( (%objectNearExit = containerSearchNext()) != 0 )
{
// If any player is found within this radius, mark that we need to look
// for another spot.
%SpawnLocationFound = false;
break;
}
// If the attempt at finding a clear spawn location failed
// try no more than 5 times.
%attemptsToSpawn++;
}
// If we couldn't find a spawn location after 5 tries, spawn the object
// At the center of the sphere and give a warning.
if (!%SpawnLocationFound)
{
%sphereLocation = %spawnSphere.getTransform();
warn("WARNING: Could not spawn player after" SPC %attemptsToSpawn
SPC "tries in spawnsphere" SPC %spawnSphere SPC "without overlapping another player. Attempting spawn in center of sphere.");
}
return %sphereLocation;
}
// ----------------------------------------------------------------------------
// Observer
// ----------------------------------------------------------------------------
function GameCore::spawnObserver(%game, %client)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::spawnObserver");
// Position the camera on one of our observer spawn points
%client.camera.setTransform(%game.pickObserverSpawnPoint());
// Set control to the camera
%client.setControlObject(%client.camera);
}
function GameCore::pickObserverSpawnPoint(%game)
{
//echo (%game @"\c4 -> "@ %game.class @" -> GameCore::pickObserverSpawnPoint");
%groupName = "MissionGroup/ObserverSpawnPoints";
%group = nameToID(%groupName);
if (%group != -1)
{
%count = %group.getCount();
if (%count != 0)
{
%index = getRandom(%count-1);
%spawn = %group.getObject(%index);
return %spawn.getTransform();
}
else
error("No spawn points found in "@ %groupName);
}
else
error("Missing spawn points group "@ %groupName);
// Could be no spawn points, in which case we'll stick the
// player at the center of the world.
return "0 0 300 1 0 0 0";
}
// ----------------------------------------------------------------------------
// Server
// ----------------------------------------------------------------------------
// Called by GameCore::cycleGame() when we need to destroy the server
// because we're done playing. We don't want to call destroyServer()
// directly so we can first check that we're about to destroy the
// correct server session.
function gameCoreDestroyServer(%serverSession)
{
if (%serverSession == $Server::Session)
{
if (isObject(LocalClientConnection))
{
// We're a local connection so issue a disconnect. The server will
// be automatically destroyed for us.
disconnect();
}
else
{
// We're a stand alone server
destroyServer();
}
}
}
//.logicking
function GameCore::spawnPlayer(%game, %this, %spawnPoint)
{
if(%spawnPoint $= "")
{
%spawnPoint = pickPlayerSpawnPoint($Game::DefaultPlayerSpawnGroups);
}
GameCore::spawnPlayer1(%game,%this, %spawnPoint);
addToTeam(%this.player, $PLAYERS_TEAM);
updateGameScore(0);
$playerForAi = %this.player;
%this.player.playerControlled = true;
}
function GameCore::loadOut(%game, %player)
{
%player.setInventory(BlasterGun, 1);
%player.setInventory(BlasterAmmo,%player.maxInventory(BlasterAmmo));
%player.mountImage(GreenBlasterGunImage, 0);
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* 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.
* - Neither the name of the openmetaverse.co 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.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
public class SoundManager
{
#region Private Members
private readonly GridClient Client;
#endregion
#region Event Handling
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<AttachedSoundEventArgs> m_AttachedSound;
///<summary>Raises the AttachedSound Event</summary>
/// <param name="e">A AttachedSoundEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnAttachedSound(AttachedSoundEventArgs e)
{
EventHandler<AttachedSoundEventArgs> handler = m_AttachedSound;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_AttachedSoundLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// sound</summary>
public event EventHandler<AttachedSoundEventArgs> AttachedSound
{
add { lock (m_AttachedSoundLock) { m_AttachedSound += value; } }
remove { lock (m_AttachedSoundLock) { m_AttachedSound -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<AttachedSoundGainChangeEventArgs> m_AttachedSoundGainChange;
///<summary>Raises the AttachedSoundGainChange Event</summary>
/// <param name="e">A AttachedSoundGainChangeEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnAttachedSoundGainChange(AttachedSoundGainChangeEventArgs e)
{
EventHandler<AttachedSoundGainChangeEventArgs> handler = m_AttachedSoundGainChange;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_AttachedSoundGainChangeLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<AttachedSoundGainChangeEventArgs> AttachedSoundGainChange
{
add { lock (m_AttachedSoundGainChangeLock) { m_AttachedSoundGainChange += value; } }
remove { lock (m_AttachedSoundGainChangeLock) { m_AttachedSoundGainChange -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<SoundTriggerEventArgs> m_SoundTrigger;
///<summary>Raises the SoundTrigger Event</summary>
/// <param name="e">A SoundTriggerEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnSoundTrigger(SoundTriggerEventArgs e)
{
EventHandler<SoundTriggerEventArgs> handler = m_SoundTrigger;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_SoundTriggerLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<SoundTriggerEventArgs> SoundTrigger
{
add { lock (m_SoundTriggerLock) { m_SoundTrigger += value; } }
remove { lock (m_SoundTriggerLock) { m_SoundTrigger -= value; } }
}
/// <summary>The event subscribers, null of no subscribers</summary>
private EventHandler<PreloadSoundEventArgs> m_PreloadSound;
///<summary>Raises the PreloadSound Event</summary>
/// <param name="e">A PreloadSoundEventArgs object containing
/// the data sent from the simulator</param>
protected virtual void OnPreloadSound(PreloadSoundEventArgs e)
{
EventHandler<PreloadSoundEventArgs> handler = m_PreloadSound;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_PreloadSoundLock = new object();
/// <summary>Raised when the simulator sends us data containing
/// ...</summary>
public event EventHandler<PreloadSoundEventArgs> PreloadSound
{
add { lock (m_PreloadSoundLock) { m_PreloadSound += value; } }
remove { lock (m_PreloadSoundLock) { m_PreloadSound -= value; } }
}
#endregion
/// <summary>
/// Construct a new instance of the SoundManager class, used for playing and receiving
/// sound assets
/// </summary>
/// <param name="client">A reference to the current GridClient instance</param>
public SoundManager(GridClient client)
{
Client = client;
Client.Network.RegisterCallback(PacketType.AttachedSound, AttachedSoundHandler);
Client.Network.RegisterCallback(PacketType.AttachedSoundGainChange, AttachedSoundGainChangeHandler);
Client.Network.RegisterCallback(PacketType.PreloadSound, PreloadSoundHandler);
Client.Network.RegisterCallback(PacketType.SoundTrigger, SoundTriggerHandler);
}
#region public methods
/// <summary>
/// Plays a sound in the current region at full volume from avatar position
/// </summary>
/// <param name="soundID">UUID of the sound to be played</param>
public void PlaySound(UUID soundID)
{
SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f);
}
/// <summary>
/// Plays a sound in the current region at full volume
/// </summary>
/// <param name="soundID">UUID of the sound to be played.</param>
/// <param name="position">position for the sound to be played at. Normally the avatar.</param>
public void SendSoundTrigger(UUID soundID, Vector3 position)
{
SendSoundTrigger(soundID, Client.Self.SimPosition, 1.0f);
}
/// <summary>
/// Plays a sound in the current region
/// </summary>
/// <param name="soundID">UUID of the sound to be played.</param>
/// <param name="position">position for the sound to be played at. Normally the avatar.</param>
/// <param name="gain">volume of the sound, from 0.0 to 1.0</param>
public void SendSoundTrigger(UUID soundID, Vector3 position, float gain)
{
SendSoundTrigger(soundID, Client.Network.CurrentSim.Handle, position, gain);
}
/// <summary>
/// Plays a sound in the specified sim
/// </summary>
/// <param name="soundID">UUID of the sound to be played.</param>
/// <param name="sim">UUID of the sound to be played.</param>
/// <param name="position">position for the sound to be played at. Normally the avatar.</param>
/// <param name="gain">volume of the sound, from 0.0 to 1.0</param>
public void SendSoundTrigger(UUID soundID, Simulator sim, Vector3 position, float gain)
{
SendSoundTrigger(soundID, sim.Handle, position, gain);
}
/// <summary>
/// Play a sound asset
/// </summary>
/// <param name="soundID">UUID of the sound to be played.</param>
/// <param name="handle">handle id for the sim to be played in.</param>
/// <param name="position">position for the sound to be played at. Normally the avatar.</param>
/// <param name="gain">volume of the sound, from 0.0 to 1.0</param>
public void SendSoundTrigger(UUID soundID, ulong handle, Vector3 position, float gain)
{
SoundTriggerPacket soundtrigger = new SoundTriggerPacket();
soundtrigger.SoundData = new SoundTriggerPacket.SoundDataBlock();
soundtrigger.SoundData.SoundID = soundID;
soundtrigger.SoundData.ObjectID = UUID.Zero;
soundtrigger.SoundData.OwnerID = UUID.Zero;
soundtrigger.SoundData.ParentID = UUID.Zero;
soundtrigger.SoundData.Handle = handle;
soundtrigger.SoundData.Position = position;
soundtrigger.SoundData.Gain = gain;
Client.Network.SendPacket(soundtrigger);
}
#endregion
#region Packet Handlers
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void AttachedSoundHandler(object sender, PacketReceivedEventArgs e)
{
if (m_AttachedSound != null)
{
AttachedSoundPacket sound = (AttachedSoundPacket)e.Packet;
OnAttachedSound(new AttachedSoundEventArgs(e.Simulator, sound.DataBlock.SoundID, sound.DataBlock.OwnerID, sound.DataBlock.ObjectID,
sound.DataBlock.Gain, (SoundFlags)sound.DataBlock.Flags));
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void AttachedSoundGainChangeHandler(object sender, PacketReceivedEventArgs e)
{
if (m_AttachedSoundGainChange != null)
{
AttachedSoundGainChangePacket change = (AttachedSoundGainChangePacket)e.Packet;
OnAttachedSoundGainChange(new AttachedSoundGainChangeEventArgs(e.Simulator, change.DataBlock.ObjectID, change.DataBlock.Gain));
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void PreloadSoundHandler(object sender, PacketReceivedEventArgs e)
{
if (m_PreloadSound != null)
{
PreloadSoundPacket preload = (PreloadSoundPacket)e.Packet;
foreach (PreloadSoundPacket.DataBlockBlock data in preload.DataBlock)
{
OnPreloadSound(new PreloadSoundEventArgs(e.Simulator, data.SoundID, data.OwnerID, data.ObjectID));
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void SoundTriggerHandler(object sender, PacketReceivedEventArgs e)
{
if (m_SoundTrigger != null)
{
SoundTriggerPacket trigger = (SoundTriggerPacket)e.Packet;
OnSoundTrigger(new SoundTriggerEventArgs(e.Simulator,
trigger.SoundData.SoundID,
trigger.SoundData.OwnerID,
trigger.SoundData.ObjectID,
trigger.SoundData.ParentID,
trigger.SoundData.Gain,
trigger.SoundData.Handle,
trigger.SoundData.Position));
}
}
#endregion
}
#region EventArgs
/// <summary>Provides data for the <see cref="SoundManager.AttachedSound"/> event</summary>
/// <remarks>The <see cref="SoundManager.AttachedSound"/> event occurs when the simulator sends
/// the sound data which emits from an agents attachment</remarks>
/// <example>
/// The following code example shows the process to subscribe to the <see cref="SoundManager.AttachedSound"/> event
/// and a stub to handle the data passed from the simulator
/// <code>
/// // Subscribe to the AttachedSound event
/// Client.Sound.AttachedSound += Sound_AttachedSound;
///
/// // process the data raised in the event here
/// private void Sound_AttachedSound(object sender, AttachedSoundEventArgs e)
/// {
/// // ... Process AttachedSoundEventArgs here ...
/// }
/// </code>
/// </example>
public class AttachedSoundEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private readonly UUID m_SoundID;
private readonly UUID m_OwnerID;
private readonly UUID m_ObjectID;
private readonly float m_Gain;
private readonly SoundFlags m_Flags;
/// <summary>Simulator where the event originated</summary>
public Simulator Simulator { get { return m_Simulator; } }
/// <summary>Get the sound asset id</summary>
public UUID SoundID { get { return m_SoundID; } }
/// <summary>Get the ID of the owner</summary>
public UUID OwnerID { get { return m_OwnerID; } }
/// <summary>Get the ID of the Object</summary>
public UUID ObjectID { get { return m_ObjectID; } }
/// <summary>Get the volume level</summary>
public float Gain { get { return m_Gain; } }
/// <summary>Get the <see cref="SoundFlags"/></summary>
public SoundFlags Flags { get { return m_Flags; } }
/// <summary>
/// Construct a new instance of the SoundTriggerEventArgs class
/// </summary>
/// <param name="sim">Simulator where the event originated</param>
/// <param name="soundID">The sound asset id</param>
/// <param name="ownerID">The ID of the owner</param>
/// <param name="objectID">The ID of the object</param>
/// <param name="gain">The volume level</param>
/// <param name="flags">The <see cref="SoundFlags"/></param>
public AttachedSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, float gain, SoundFlags flags)
{
this.m_Simulator = sim;
this.m_SoundID = soundID;
this.m_OwnerID = ownerID;
this.m_ObjectID = objectID;
this.m_Gain = gain;
this.m_Flags = flags;
}
}
/// <summary>Provides data for the <see cref="SoundManager.AttachedSoundGainChange"/> event</summary>
/// <remarks>The <see cref="SoundManager.AttachedSoundGainChange"/> event occurs when an attached sound
/// changes its volume level</remarks>
public class AttachedSoundGainChangeEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private readonly UUID m_ObjectID;
private readonly float m_Gain;
/// <summary>Simulator where the event originated</summary>
public Simulator Simulator { get { return m_Simulator; } }
/// <summary>Get the ID of the Object</summary>
public UUID ObjectID { get { return m_ObjectID; } }
/// <summary>Get the volume level</summary>
public float Gain { get { return m_Gain; } }
/// <summary>
/// Construct a new instance of the AttachedSoundGainChangedEventArgs class
/// </summary>
/// <param name="sim">Simulator where the event originated</param>
/// <param name="objectID">The ID of the Object</param>
/// <param name="gain">The new volume level</param>
public AttachedSoundGainChangeEventArgs(Simulator sim, UUID objectID, float gain)
{
this.m_Simulator = sim;
this.m_ObjectID = objectID;
this.m_Gain = gain;
}
}
/// <summary>Provides data for the <see cref="SoundManager.SoundTrigger"/> event</summary>
/// <remarks><para>The <see cref="SoundManager.SoundTrigger"/> event occurs when the simulator forwards
/// a request made by yourself or another agent to play either an asset sound or a built in sound</para>
///
/// <para>Requests to play sounds where the <see cref="SoundTriggerEventArgs.SoundID"/> is not one of the built-in
/// <see cref="Sounds"/> will require sending a request to download the sound asset before it can be played</para>
/// </remarks>
/// <example>
/// The following code example uses the <see cref="SoundTriggerEventArgs.OwnerID"/>, <see cref="SoundTriggerEventArgs.SoundID"/>
/// and <see cref="SoundTriggerEventArgs.Gain"/>
/// properties to display some information on a sound request on the <see cref="Console"/> window.
/// <code>
/// // subscribe to the event
/// Client.Sound.SoundTrigger += Sound_SoundTrigger;
///
/// // play the pre-defined BELL_TING sound
/// Client.Sound.SendSoundTrigger(Sounds.BELL_TING);
///
/// // handle the response data
/// private void Sound_SoundTrigger(object sender, SoundTriggerEventArgs e)
/// {
/// Console.WriteLine("{0} played the sound {1} at volume {2}",
/// e.OwnerID, e.SoundID, e.Gain);
/// }
/// </code>
/// </example>
public class SoundTriggerEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private readonly UUID m_SoundID;
private readonly UUID m_OwnerID;
private readonly UUID m_ObjectID;
private readonly UUID m_ParentID;
private readonly float m_Gain;
private readonly ulong m_RegionHandle;
private readonly Vector3 m_Position;
/// <summary>Simulator where the event originated</summary>
public Simulator Simulator { get { return m_Simulator; } }
/// <summary>Get the sound asset id</summary>
public UUID SoundID { get { return m_SoundID; } }
/// <summary>Get the ID of the owner</summary>
public UUID OwnerID { get { return m_OwnerID; } }
/// <summary>Get the ID of the Object</summary>
public UUID ObjectID { get { return m_ObjectID; } }
/// <summary>Get the ID of the objects parent</summary>
public UUID ParentID { get { return m_ParentID; } }
/// <summary>Get the volume level</summary>
public float Gain { get { return m_Gain; } }
/// <summary>Get the regionhandle</summary>
public ulong RegionHandle { get { return m_RegionHandle; } }
/// <summary>Get the source position</summary>
public Vector3 Position { get { return m_Position; } }
/// <summary>
/// Construct a new instance of the SoundTriggerEventArgs class
/// </summary>
/// <param name="sim">Simulator where the event originated</param>
/// <param name="soundID">The sound asset id</param>
/// <param name="ownerID">The ID of the owner</param>
/// <param name="objectID">The ID of the object</param>
/// <param name="parentID">The ID of the objects parent</param>
/// <param name="gain">The volume level</param>
/// <param name="regionHandle">The regionhandle</param>
/// <param name="position">The source position</param>
public SoundTriggerEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID, UUID parentID, float gain, ulong regionHandle, Vector3 position)
{
this.m_Simulator = sim;
this.m_SoundID = soundID;
this.m_OwnerID = ownerID;
this.m_ObjectID = objectID;
this.m_ParentID = parentID;
this.m_Gain = gain;
this.m_RegionHandle = regionHandle;
this.m_Position = position;
}
}
/// <summary>Provides data for the <see cref="AvatarManager.AvatarAppearance"/> event</summary>
/// <remarks>The <see cref="AvatarManager.AvatarAppearance"/> event occurs when the simulator sends
/// the appearance data for an avatar</remarks>
/// <example>
/// The following code example uses the <see cref="AvatarAppearanceEventArgs.AvatarID"/> and <see cref="AvatarAppearanceEventArgs.VisualParams"/>
/// properties to display the selected shape of an avatar on the <see cref="Console"/> window.
/// <code>
/// // subscribe to the event
/// Client.Avatars.AvatarAppearance += Avatars_AvatarAppearance;
///
/// // handle the data when the event is raised
/// void Avatars_AvatarAppearance(object sender, AvatarAppearanceEventArgs e)
/// {
/// Console.WriteLine("The Agent {0} is using a {1} shape.", e.AvatarID, (e.VisualParams[31] > 0) : "male" ? "female")
/// }
/// </code>
/// </example>
public class PreloadSoundEventArgs : EventArgs
{
private readonly Simulator m_Simulator;
private readonly UUID m_SoundID;
private readonly UUID m_OwnerID;
private readonly UUID m_ObjectID;
/// <summary>Simulator where the event originated</summary>
public Simulator Simulator { get { return m_Simulator; } }
/// <summary>Get the sound asset id</summary>
public UUID SoundID { get { return m_SoundID; } }
/// <summary>Get the ID of the owner</summary>
public UUID OwnerID { get { return m_OwnerID; } }
/// <summary>Get the ID of the Object</summary>
public UUID ObjectID { get { return m_ObjectID; } }
/// <summary>
/// Construct a new instance of the PreloadSoundEventArgs class
/// </summary>
/// <param name="sim">Simulator where the event originated</param>
/// <param name="soundID">The sound asset id</param>
/// <param name="ownerID">The ID of the owner</param>
/// <param name="objectID">The ID of the object</param>
public PreloadSoundEventArgs(Simulator sim, UUID soundID, UUID ownerID, UUID objectID)
{
this.m_Simulator = sim;
this.m_SoundID = soundID;
this.m_OwnerID = ownerID;
this.m_ObjectID = objectID;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using RRLab.PhysiologyWorkbench.Data;
using NationalInstruments.DAQmx;
using System.ComponentModel;
namespace RRLab.PhysiologyWorkbench.Daq
{
public class OscilloscopeProtocol : DaqProtocol
{
public override string ProtocolName
{
get { return "Oscilloscope"; }
}
public override string ProtocolDescription
{
get { return "Records from selected DAQ channels."; }
}
private Task _AITask;
protected Task AITask
{
get { return _AITask; }
set { _AITask = value; }
}
private float _UpdateTime = 200;
public float UpdateTime
{
get { return _UpdateTime; }
set {
_UpdateTime = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
}
}
private double _SampleRate = 10000;
public double SampleRate
{
get { return _SampleRate; }
set {
_SampleRate = value;
FireSettingsChangedEvent(this, EventArgs.Empty);
}
}
public override bool IsContinuousRecordingSupported
{
get
{
return true;
}
}
public event EventHandler ChannelsToRecordChanged;
private SortedList<string, string> _ChannelsToRecord = new SortedList<string, string>();
public IDictionary<string, string> ChannelsToRecord
{
get { return _ChannelsToRecord; }
}
protected AnalogMultiChannelReader ChannelReader;
private float[] _CachedTimeVector;
public OscilloscopeProtocol()
{
}
public void AddChannel(string name, string address)
{
_ChannelsToRecord.Add(name, address);
FireSettingsChangedEvent(this, EventArgs.Empty);
if (ChannelsToRecordChanged != null) ChannelsToRecordChanged(this, EventArgs.Empty);
}
public void RemoveChannel(string name)
{
_ChannelsToRecord.Remove(name);
FireSettingsChangedEvent(this, EventArgs.Empty);
if (ChannelsToRecordChanged != null) ChannelsToRecordChanged(this, EventArgs.Empty);
}
protected override void Initialize()
{
try
{
AITask = new Task("AI");
ConfigureChannels();
AITask.Timing.ConfigureSampleClock("", SampleRate, SampleClockActiveEdge.Rising, SampleQuantityMode.ContinuousSamples, Convert.ToInt32(UpdateTime*SampleRate*5/1000));
GenerateChannelReader();
FireStartingEvent(this, EventArgs.Empty);
}
catch (Exception e)
{
FinalizeProtocol();
}
}
protected virtual void ConfigureChannels()
{
foreach (KeyValuePair<string, string> kv in ChannelsToRecord)
AITask.AIChannels.CreateVoltageChannel(kv.Value, kv.Key, AITerminalConfiguration.Rse, -10, 10, AIVoltageUnits.Volts);
}
protected virtual void GenerateChannelReader()
{
ChannelReader = new AnalogMultiChannelReader(AITask.Stream);
}
public override void StartContinuousExecute()
{
if (!IsContinuousRecordingSupported) throw new ApplicationException("Continuous execution is not supported.");
StopContinuousExecutionTrigger = false;
Initialize();
try
{
AITask.Start();
BeginAsyncRead();
}
catch (Exception e)
{
ContinuouslyExecutingThread = null;
FinalizeProtocol();
}
}
protected override void Execute()
{
try
{
AITask.Start();
BeginAsyncRead();
System.Threading.Thread.Sleep(Convert.ToInt32(UpdateTime));
AITask.Stop();
}
catch (Exception e)
{
FinalizeProtocol();
}
}
protected virtual void BeginAsyncRead()
{
System.Threading.ThreadStart asyncRead = new System.Threading.ThreadStart(AsyncRead);
asyncRead.BeginInvoke(null, null);
}
protected virtual void AsyncRead()
{
if (!AITask.IsDone)
{
int nsamples = Convert.ToInt32(UpdateTime * SampleRate / 1000);
IAsyncResult ar = ChannelReader.BeginReadMultiSample(nsamples, new AsyncCallback(OnAsyncReadFinished), null);
}
}
public override void StopContinuousExecute()
{
StopContinuousExecutionTrigger = true;
try
{
AITask.Stop();
}
finally
{
ContinuouslyExecutingThread = null;
FinalizeProtocol();
}
}
protected override void FinalizeProtocol()
{
if (AITask != null)
{
AITask.Dispose();
AITask = null;
}
_CachedTimeVector = null;
FireFinishedEvent(this, EventArgs.Empty);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (AITask != null) AITask.Dispose();
}
protected virtual void OnAsyncReadFinished(IAsyncResult ar)
{
if (Disposing) return;
try
{
double[,] data = ChannelReader.EndReadMultiSample(ar);
if (_CachedTimeVector == null)
{
int nsamples = Convert.ToInt32(UpdateTime * SampleRate / 1000);
_CachedTimeVector = new float[nsamples];
for (int i = 0; i < nsamples; i++)
{
_CachedTimeVector[i] = ((float)i) * 1000 / ((float)SampleRate);
}
}
string[] channelNames = new string[ChannelsToRecord.Count];
ChannelsToRecord.Keys.CopyTo(channelNames, 0);
string[] units = new string[channelNames.Length];
for (int i = 0; i < units.Length; i++)
units[i] = "V";
StoreCollectedData(_CachedTimeVector, channelNames, data, units);
if (!StopContinuousExecutionTrigger) BeginAsyncRead();
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("Error while reading data: " + e.Message);
}
}
protected virtual void StoreCollectedData(float[] time, string[] channelNames, double[,] data, string[] units)
{
Data = CreateNewRecording();
Data.AddData(channelNames, time, data, units);
ProcessData();
}
public override System.Windows.Forms.Control GetConfigurationControl()
{
return new OscilloscopeConfigurationControl(this);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Google.Apis.Drive.v2;
using Microsoft.Extensions.Logging;
using GoogleFile = Google.Apis.Drive.v2.Data.File;
using ParentReference = Google.Apis.Drive.v2.Data.ParentReference;
namespace hutel.Storage
{
public class GoogleDriveHutelStorageClient : IHutelStorageClient, IDisposable
{
private const string ApplicationName = "Human Telemetry";
private const string RootFolderName = "Hutel";
private const string PointsFileBaseName = "storage";
private const string PointsFileName = "storage.json";
private const string TagsFileBaseName = "tags";
private const string TagsFileName = "tags.json";
private const string ChartsFileBaseName = "charts";
private const string ChartsFileName = "charts.json";
private const string FolderMimeType = "application/vnd.google-apps.folder";
private const string JsonMimeType = "application/octet-stream";
private readonly string _userId;
private bool _initialized;
private DriveService _driveService;
private string _rootFolderId;
private string _pointsFileId;
private DateTime? _pointsLastBackupDate;
private string _tagsFileId;
private DateTime? _tagsLastBackupDate;
private string _chartsFileId;
private DateTime? _chartsLastBackupDate;
private ILogger _logger;
public GoogleDriveHutelStorageClient(string userId, ILoggerFactory loggerFactory)
{
_userId = userId;
_initialized = false;
_logger = loggerFactory.CreateLogger<GoogleDriveHutelStorageClient>();
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
this._driveService.Dispose();
}
}
public async Task<string> ReadPointsAsStringAsync()
{
await InitAsync();
_logger.LogInformation("ReadPointsAsStringAsync");
return await ReadFileAsStringAsync(_pointsFileId);
}
public async Task WritePointsAsStringAsync(string data)
{
await InitAsync();
_logger.LogInformation("WritePointsAsStringAsync");
await BackupStorageIfNeededAsync();
await WriteFileAsStringAsync(_pointsFileId, data);
}
public async Task<string> ReadTagsAsStringAsync()
{
await InitAsync();
_logger.LogInformation("ReadTagsAsStringAsync");
return await ReadFileAsStringAsync(_tagsFileId);
}
public async Task WriteTagsAsStringAsync(string data)
{
await InitAsync();
_logger.LogInformation("WriteTagsAsStringAsync");
await BackupTagsIfNeededAsync();
await WriteFileAsStringAsync(_tagsFileId, data);
}
public async Task<string> ReadChartsAsStringAsync()
{
await InitAsync();
_logger.LogInformation("ReadChartsAsStringAsync");
return await ReadFileAsStringAsync(_chartsFileId);
}
public async Task WriteChartsAsStringAsync(string data)
{
await InitAsync();
_logger.LogInformation("WriteChartsAsStringAsync");
await BackupChartsIfNeededAsync();
await WriteFileAsStringAsync(_chartsFileId, data);
}
public Task Reload()
{
// This implementation is synchronous, nothing to reload
return Task.CompletedTask;
}
private async Task InitAsync()
{
if (_initialized)
{
return;
}
var HttpClientInitializer = new GoogleHttpClientInitializer(_userId);
_driveService = new DriveService(
new DriveService.Initializer
{
HttpClientInitializer = HttpClientInitializer,
ApplicationName = ApplicationName
}
);
var rootFolder = await GetOrCreateFileAsync(RootFolderName, FolderMimeType, null);
_rootFolderId = rootFolder.Id;
var pointsFileTask = GetOrCreateFileAsync(PointsFileName, null, _rootFolderId);
var tagsFileTask = GetOrCreateFileAsync(TagsFileName, null, _rootFolderId);
var chartsFileTask = GetOrCreateFileAsync(ChartsFileName, null, _rootFolderId);
var pointsLastBackupTask = FindLastBackupAsync(
PointsFileBaseName, PointsFileName, _rootFolderId);
var tagsLastBackupTask = FindLastBackupAsync(
TagsFileBaseName, TagsFileName, _rootFolderId);
var chartsLastBackupTask = FindLastBackupAsync(
ChartsFileBaseName, ChartsFileName, _rootFolderId);
var pointsFile = await pointsFileTask;
var tagsFile = await tagsFileTask;
var chartsFile = await chartsFileTask;
var pointsLastBackup = await pointsLastBackupTask;
var tagsLastBackup = await tagsLastBackupTask;
var chartsLastBackup = await chartsLastBackupTask;
_pointsFileId = pointsFile.Id;
_tagsFileId = tagsFile.Id;
_chartsFileId = chartsFile.Id;
_pointsLastBackupDate = pointsLastBackup?.CreatedDate;
_tagsLastBackupDate = tagsLastBackup?.CreatedDate;
_chartsLastBackupDate = chartsLastBackup?.CreatedDate;
_initialized = true;
}
private async Task<GoogleFile> FindLastBackupAsync(
string baseName, string fullName, string parent)
{
var listRequest = _driveService.Files.List();
listRequest.Q = $"title contains '{baseName}' and '{parent}' in parents";
listRequest.Spaces = "drive";
var fileList = await listRequest.ExecuteAsync();
var validFiles = fileList.Items
.Where(file => file.Labels.Trashed != true)
.Where(file => file.Title != fullName)
.ToList();
validFiles.Sort((a, b) => DateTimeOptCompareDesc(a.CreatedDate, b.CreatedDate));
if (validFiles.Count > 0)
{
return validFiles[0];
}
else
{
return null;
}
}
private static int DateTimeOptCompareDesc(DateTime? a, DateTime? b)
{
if (!a.HasValue && !b.HasValue)
{
return 0;
}
else if (!a.HasValue)
{
return 1;
}
else if (!b.HasValue)
{
return -1;
}
else
{
return -DateTime.Compare(a.Value, b.Value);
}
}
private async Task BackupStorageIfNeededAsync()
{
if (!_pointsLastBackupDate.HasValue ||
(DateTime.UtcNow - _pointsLastBackupDate.Value).Days >= 1)
{
var backupDateString = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
var backupFileName = $"{PointsFileBaseName}-{backupDateString}.json";
await CopyFileAsync(_pointsFileId, backupFileName);
}
}
private async Task BackupTagsIfNeededAsync()
{
if (!_tagsLastBackupDate.HasValue ||
(DateTime.UtcNow - _tagsLastBackupDate.Value).Days >= 1)
{
var backupDateString = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
var backupFileName = $"{TagsFileBaseName}-{backupDateString}.json";
await CopyFileAsync(_tagsFileId, backupFileName);
}
}
private async Task BackupChartsIfNeededAsync()
{
if (!_chartsLastBackupDate.HasValue ||
(DateTime.UtcNow - _chartsLastBackupDate.Value).Days >= 1)
{
var backupDateString = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
var backupFileName = $"{ChartsFileBaseName}-{backupDateString}.json";
await CopyFileAsync(_chartsFileId, backupFileName);
}
}
private async Task<GoogleFile> GetOrCreateFileAsync(
string name, string mimeType, string parent)
{
var listRequest = _driveService.Files.List();
var parentId = parent ?? "root";
var mimeQuery = mimeType != null ? $"mimeType = '{mimeType}' and " : "";
listRequest.Q = mimeQuery + $"title = '{name}' and '{parentId}' in parents";
listRequest.Spaces = "drive";
var fileList = await listRequest.ExecuteAsync();
var validFiles = fileList.Items.Where(file => file.Labels.Trashed != true).ToList();
if (validFiles.Count > 0)
{
return validFiles[0];
}
else
{
return await CreateFileAsync(name, mimeType, parent);
}
}
private async Task<GoogleFile> CreateFileAsync(string name, string mimeType, string parent)
{
var parentId = parent ?? "root";
var fileMetadata = new GoogleFile
{
Title = name,
MimeType = mimeType,
Parents = new List<ParentReference>
{
parent != null
? new ParentReference{ Id = parentId }
: new ParentReference{ IsRoot = true }
}
};
var request = _driveService.Files.Insert(fileMetadata);
request.Fields = "id";
var file = await request.ExecuteAsync();
return file;
}
private async Task<GoogleFile> CopyFileAsync(string fileId, string name)
{
var fileMetadata = new GoogleFile
{
Title = name
};
var copyRequest = _driveService.Files.Copy(fileMetadata, fileId);
var file = await copyRequest.ExecuteAsync();
return file;
}
private async Task<string> ReadFileAsStringAsync(string fileId)
{
_logger.LogInformation("ReadFileAsStringAsync");
var downloadRequest = _driveService.Files.Get(fileId);
var stream = new MemoryStream();
var progress = await downloadRequest.DownloadAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
var streamReader = new StreamReader(stream);
var contents = await streamReader.ReadToEndAsync();
return contents;
}
private async Task WriteFileAsStringAsync(string fileId, string data)
{
_logger.LogInformation("WriteFileAsStringAsync");
var stream = new MemoryStream();
var streamWriter = new StreamWriter(stream);
streamWriter.Write(data);
streamWriter.Flush();
stream.Seek(0, SeekOrigin.Begin);
var file = new GoogleFile();
var updateRequest = _driveService.Files.Update(file, fileId, stream, JsonMimeType);
var progress = await updateRequest.UploadAsync();
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Storages.Csv.Algo
File: CandleCsvSerializer.cs
Created: 2015, 12, 14, 1:43 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo.Storages.Csv
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Ecng.Collections;
using Ecng.Common;
using StockSharp.Messages;
/// <summary>
/// The candle serializer in the CSV format.
/// </summary>
public class CandleCsvSerializer<TCandleMessage> : CsvMarketDataSerializer<TCandleMessage>
where TCandleMessage : CandleMessage, new()
{
private class CandleCsvMetaInfo : MetaInfo
//where TCandleMessage : CandleMessage, new()
{
private readonly Dictionary<DateTime, TCandleMessage> _items = new Dictionary<DateTime, TCandleMessage>();
private readonly CandleCsvSerializer<TCandleMessage> _serializer;
private readonly Encoding _encoding;
private bool _isOverride;
public override bool IsOverride => _isOverride;
public CandleCsvMetaInfo(CandleCsvSerializer<TCandleMessage> serializer, DateTime date, Encoding encoding)
: base(date)
{
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
_serializer = serializer;
_encoding = encoding;
}
public override object LastId { get; set; }
public override void Write(Stream stream)
{
}
public override void Read(Stream stream)
{
CultureInfo.InvariantCulture.DoInCulture(() =>
{
var count = 0;
var firstTimeRead = false;
var reader = new FastCsvReader(stream, _encoding);
while (reader.NextLine())
{
var message = _serializer.Read(reader, this);
var openTime = message.OpenTime.UtcDateTime;
_items.Add(openTime, message);
if (!firstTimeRead)
{
FirstTime = openTime;
firstTimeRead = true;
}
LastTime = openTime;
count++;
}
Count = count;
stream.Position = 0;
});
}
public IEnumerable<TCandleMessage> Process(IEnumerable<TCandleMessage> messages)
{
messages = messages.ToArray();
if (messages.IsEmpty())
return Enumerable.Empty<TCandleMessage>();
foreach (var message in messages)
{
var openTime = message.OpenTime.UtcDateTime;
if (!_isOverride)
_isOverride = _items.ContainsKey(openTime) || openTime <= LastTime;
_items[openTime] = message;
LastTime = openTime;
}
return _isOverride ? _items.Values : messages;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="CandleCsvSerializer{TCandleMessage}"/>.
/// </summary>
/// <param name="securityId">Security ID.</param>
/// <param name="arg">Candle arg.</param>
/// <param name="encoding">Encoding.</param>
public CandleCsvSerializer(SecurityId securityId, object arg, Encoding encoding = null)
: base(securityId, encoding)
{
if (arg == null)
throw new ArgumentNullException(nameof(arg));
Arg = arg;
}
/// <summary>
/// Candle arg.
/// </summary>
public object Arg { get; set; }
/// <summary>
/// To create empty meta-information.
/// </summary>
/// <param name="date">Date.</param>
/// <returns>Meta-information on data for one day.</returns>
public override IMarketDataMetaInfo CreateMetaInfo(DateTime date)
{
return new CandleCsvMetaInfo(this, date, Encoding);
}
/// <summary>
/// Save data into stream.
/// </summary>
/// <param name="stream">Data stream.</param>
/// <param name="data">Data.</param>
/// <param name="metaInfo">Meta-information on data for one day.</param>
public override void Serialize(Stream stream, IEnumerable<TCandleMessage> data, IMarketDataMetaInfo metaInfo)
{
var candleMetaInfo = (CandleCsvMetaInfo)metaInfo;
var toWrite = candleMetaInfo.Process(data);
CultureInfo.InvariantCulture.DoInCulture(() =>
{
var writer = new CsvFileWriter(stream, Encoding);
try
{
foreach (var item in toWrite)
{
Write(writer, item, candleMetaInfo);
}
}
finally
{
writer.Writer.Flush();
}
});
}
/// <summary>
/// Write data to the specified writer.
/// </summary>
/// <param name="writer">CSV writer.</param>
/// <param name="data">Data.</param>
/// <param name="metaInfo">Meta-information on data for one day.</param>
protected override void Write(CsvFileWriter writer, TCandleMessage data, IMarketDataMetaInfo metaInfo)
{
writer.WriteRow(new[]
{
data.OpenTime.WriteTimeMls(),
data.OpenTime.ToString("zzz"),
data.OpenPrice.ToString(),
data.HighPrice.ToString(),
data.LowPrice.ToString(),
data.ClosePrice.ToString(),
data.TotalVolume.ToString()
});
}
/// <summary>
/// Read data from the specified reader.
/// </summary>
/// <param name="reader">CSV reader.</param>
/// <param name="metaInfo">Meta-information on data for one day.</param>
/// <returns>Data.</returns>
protected override TCandleMessage Read(FastCsvReader reader, IMarketDataMetaInfo metaInfo)
{
return new TCandleMessage
{
SecurityId = SecurityId,
Arg = Arg,
OpenTime = reader.ReadTime(metaInfo.Date),
OpenPrice = reader.ReadDecimal(),
HighPrice = reader.ReadDecimal(),
LowPrice = reader.ReadDecimal(),
ClosePrice = reader.ReadDecimal(),
TotalVolume = reader.ReadDecimal(),
State = CandleStates.Finished
};
}
}
}
| |
// 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.IO;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ChainTests
{
// #9293: Our Fedora and Ubuntu CI machines use NTFS for "tmphome", which causes our filesystem permissions checks to fail.
internal static bool IsReliableInCI { get; } =
!PlatformDetection.IsFedora24 &&
!PlatformDetection.IsFedora25 &&
!PlatformDetection.IsFedora26 &&
!PlatformDetection.IsUbuntu1604 &&
!PlatformDetection.IsUbuntu1610;
private static bool TrustsMicrosoftDotComRoot
{
get
{
// Verifies that the microsoft.com certs build with only the certificates in the root store
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
return chain.Build(microsoftDotCom);
}
}
}
[Fact]
public static void BuildChain()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
// Halfway between microsoftDotCom's NotBefore and NotAfter
// This isn't a boundary condition test.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Chain built validly");
// The chain should have 3 members
Assert.Equal(3, chain.ChainElements.Count);
// These are the three specific members.
Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate);
}
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void VerifyChainFromHandle()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.True(valid, "Source chain built validly");
Assert.Equal(3, chain.ChainElements.Count);
using (var chainHolder2 = new ChainHolder(chain.ChainContext))
{
X509Chain chain2 = chainHolder2.Chain;
Assert.NotSame(chain, chain2);
Assert.Equal(chain.ChainContext, chain2.ChainContext);
Assert.Equal(3, chain2.ChainElements.Count);
Assert.NotSame(chain.ChainElements[0], chain2.ChainElements[0]);
Assert.NotSame(chain.ChainElements[1], chain2.ChainElements[1]);
Assert.NotSame(chain.ChainElements[2], chain2.ChainElements[2]);
Assert.Equal(microsoftDotCom, chain2.ChainElements[0].Certificate);
Assert.Equal(microsoftDotComIssuer, chain2.ChainElements[1].Certificate);
Assert.Equal(microsoftDotComRoot, chain2.ChainElements[2].Certificate);
// ChainPolicy is not carried over from the Chain(IntPtr) constructor
Assert.NotEqual(chain.ChainPolicy.VerificationFlags, chain2.ChainPolicy.VerificationFlags);
Assert.NotEqual(chain.ChainPolicy.VerificationTime, chain2.ChainPolicy.VerificationTime);
Assert.NotEqual(chain.ChainPolicy.RevocationMode, chain2.ChainPolicy.RevocationMode);
Assert.Equal(X509VerificationFlags.NoFlag, chain2.ChainPolicy.VerificationFlags);
// Re-set the ChainPolicy properties
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain2.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain2.Build(microsoftDotCom);
Assert.True(valid, "Cloned chain built validly");
}
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[ConditionalFact(nameof(IsReliableInCI))]
public static void VerifyChainFromHandle_Unix()
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(microsoftDotCom);
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero));
}
[PlatformSpecific(TestPlatforms.Windows)]
[Fact]
public static void TestDispose()
{
X509Chain chain;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var chainHolder = new ChainHolder())
{
chain = chainHolder.Chain;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(microsoftDotCom);
Assert.NotEqual(IntPtr.Zero, chain.ChainContext);
}
// No exception thrown for accessing ChainContext on disposed chain
Assert.Equal(IntPtr.Zero, chain.ChainContext);
}
[Fact]
public static void TestResetMethod()
{
using (var sampleCert = new X509Certificate2(TestData.DssCer))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(sampleCert);
bool valid = chain.Build(sampleCert);
Assert.False(valid);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
valid = chain.Build(sampleCert);
Assert.True(valid, "Chain built validly");
Assert.Equal(1, chain.ChainElements.Count);
chain.Reset();
Assert.Equal(0, chain.ChainElements.Count);
// ChainPolicy did not reset (for desktop compat)
Assert.Equal(X509VerificationFlags.AllowUnknownCertificateAuthority, chain.ChainPolicy.VerificationFlags);
valid = chain.Build(sampleCert);
Assert.Equal(1, chain.ChainElements.Count);
// This succeeds because ChainPolicy did not reset
Assert.True(valid, "Chain built validly after reset");
}
}
/// <summary>
/// Tests that when a certificate chain has a root certification which is not trusted by the trust provider,
/// Build returns false and a ChainStatus returns UntrustedRoot
/// </summary>
[Fact]
[OuterLoop]
public static void BuildChainExtraStoreUntrustedRoot()
{
using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword))
using (ImportedCollection ic = Cert.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet))
using (var chainHolder = new ChainHolder())
{
X509Certificate2Collection collection = ic.Collection;
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.AddRange(collection);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0);
bool valid = chain.Build(testCert);
Assert.False(valid);
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot);
}
}
public static IEnumerable<object[]> VerifyExpressionData()
{
// The test will be using the chain for TestData.MicrosoftDotComSslCertBytes
// The leaf cert (microsoft.com) is valid from 2014-10-15 00:00:00Z to 2016-10-15 23:59:59Z
DateTime[] validTimes =
{
// The NotBefore value
new DateTime(2014, 10, 15, 0, 0, 0, DateTimeKind.Utc),
// One second before the NotAfter value
new DateTime(2016, 10, 15, 23, 59, 58, DateTimeKind.Utc),
};
// The NotAfter value as a boundary condition differs on Windows and OpenSSL.
// Windows considers it valid (<= NotAfter).
// OpenSSL considers it invalid (< NotAfter), with a comment along the lines of
// "it'll be invalid in a millisecond, why bother with the <="
// So that boundary condition is not being tested.
DateTime[] invalidTimes =
{
// One second before the NotBefore time
new DateTime(2014, 10, 14, 23, 59, 59, DateTimeKind.Utc),
// One second after the NotAfter time
new DateTime(2016, 10, 16, 0, 0, 0, DateTimeKind.Utc),
};
List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3);
// Build (date, result, kind) tuples. The kind is used to help describe the test case.
// The DateTime format that xunit uses does show a difference in the DateTime itself, but
// having the Kind be a separate parameter just helps.
foreach (DateTime utcTime in validTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, true, utcTime.Kind });
testCases.Add(new object[] { local, true, local.Kind });
testCases.Add(new object[] { unspecified, true, unspecified.Kind });
}
foreach (DateTime utcTime in invalidTimes)
{
DateTime local = utcTime.ToLocalTime();
DateTime unspecified = new DateTime(local.Ticks);
testCases.Add(new object[] { utcTime, false, utcTime.Kind });
testCases.Add(new object[] { local, false, local.Kind });
testCases.Add(new object[] { unspecified, false, unspecified.Kind });
}
return testCases;
}
[Theory]
[MemberData(nameof(VerifyExpressionData))]
public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind)
{
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// Ignore anything except NotTimeValid
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = verificationTime;
bool builtSuccessfully = chain.Build(microsoftDotCom);
Assert.Equal(shouldBeValid, builtSuccessfully);
// If we failed to build the chain, ensure that NotTimeValid is one of the reasons.
if (!shouldBeValid)
{
Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid);
}
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_Match()
{
using (var msCer = new X509Certificate2(TestData.MsCertificate))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3"));
chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2);
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(msCer);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithApplicationPolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Gibberish. (Code Signing + ".1")
chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_Match()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
// Code Signing
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool valid = chain.Build(cert);
Assert.True(valid, "Chain built validly");
}
}
[Fact]
public static void BuildChain_WithCertificatePolicy_NoMatch()
{
using (var cert = new X509Certificate2(TestData.CertWithPolicies))
using (var chainHolder = new ChainHolder())
{
X509Chain chain = chainHolder.Chain;
chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999"));
chain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
bool valid = chain.Build(cert);
Assert.False(valid, "Chain built validly");
Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue);
Assert.NotSame(cert, chain.ChainElements[0].Certificate);
Assert.Equal(cert, chain.ChainElements[0].Certificate);
X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus;
Assert.InRange(chainElementStatus.Length, 1, int.MaxValue);
Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage);
}
}
[ConditionalFact(nameof(TrustsMicrosoftDotComRoot))]
[OuterLoop(/* Modifies user certificate store */)]
public static void BuildChain_MicrosoftDotCom_WithRootCertInUserAndSystemRootCertStores()
{
// Verifies that when the same root cert is placed in both a user and machine root certificate store,
// any certs chain building to that root cert will build correctly
//
// We use a copy of the microsoft.com SSL certs and root certs to validate that the chain can build
// successfully
bool shouldInstallCertToUserStore = true;
bool installedCertToUserStore = false;
using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
// Check that microsoft.com's root certificate IS installed in the machine root store as a sanity step
using (var machineRootStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
machineRootStore.Open(OpenFlags.ReadOnly);
bool foundCert = false;
foreach (var machineCert in machineRootStore.Certificates)
{
if (machineCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
machineCert.Dispose();
}
Assert.True(foundCert, string.Format("Did not find expected certificate with thumbprint '{0}' in the machine root store", microsoftDotComRoot.Thumbprint));
}
// Concievably at this point there could still be something wrong and we still don't chain build correctly - if that's
// the case, then there's likely something wrong with the machine. Validating that happy path is out of scope
// of this particular test.
// Check that microsoft.com's root certificate is NOT installed on in the user cert store as a sanity step
// We won't try to install the microsoft.com root cert into the user root store if it's already there
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
{
userRootStore.Open(OpenFlags.ReadOnly);
foreach (var userCert in userRootStore.Certificates)
{
bool foundCert = false;
if (userCert.Equals(microsoftDotComRoot))
{
foundCert = true;
}
userCert.Dispose();
if (foundCert)
{
shouldInstallCertToUserStore = false;
}
}
}
using (var userRootStore = new X509Store(StoreName.Root, StoreLocation.CurrentUser))
using (var chainHolder = new ChainHolder())
{
try
{
if (shouldInstallCertToUserStore)
{
try
{
userRootStore.Open(OpenFlags.ReadWrite);
}
catch (CryptographicException)
{
return;
}
userRootStore.Add(microsoftDotComRoot); // throws CryptographicException
installedCertToUserStore = true;
}
X509Chain chainValidator = chainHolder.Chain;
chainValidator.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local);
chainValidator.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
bool chainBuildResult = chainValidator.Build(microsoftDotCom);
StringBuilder builder = new StringBuilder();
foreach (var status in chainValidator.ChainStatus)
{
builder.AppendFormat("{0} {1}{2}", status.Status, status.StatusInformation, Environment.NewLine);
}
Assert.True(chainBuildResult,
string.Format("Certificate chain build failed. ChainStatus is:{0}{1}", Environment.NewLine, builder.ToString()));
}
finally
{
if (installedCertToUserStore)
{
userRootStore.Remove(microsoftDotComRoot);
}
}
}
}
}
[Fact]
[OuterLoop( /* May require using the network, to download CRLs and intermediates */)]
public static void VerifyWithRevocation()
{
using (var cert = new X509Certificate2(Path.Combine("TestData", "MS.cer")))
using (var onlineChainHolder = new ChainHolder())
using (var offlineChainHolder = new ChainHolder())
{
X509Chain onlineChain = onlineChainHolder.Chain;
X509Chain offlineChain = offlineChainHolder.Chain;
onlineChain.ChainPolicy.VerificationFlags =
X509VerificationFlags.AllowUnknownCertificateAuthority;
onlineChain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2);
onlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
onlineChain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
bool valid = onlineChain.Build(cert);
Assert.True(valid, "Online Chain Built Validly");
// Since the network was enabled, we should get the whole chain.
Assert.Equal(3, onlineChain.ChainElements.Count);
Assert.Equal(0, onlineChain.ChainElements[0].ChainElementStatus.Length);
Assert.Equal(0, onlineChain.ChainElements[1].ChainElementStatus.Length);
// The root CA is not expected to be installed on everyone's machines,
// so allow for it to report UntrustedRoot, but nothing else..
X509ChainStatus[] rootElementStatus = onlineChain.ChainElements[2].ChainElementStatus;
if (rootElementStatus.Length != 0)
{
Assert.Equal(1, rootElementStatus.Length);
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, rootElementStatus[0].Status);
}
// Now that everything is cached, try again in Offline mode.
offlineChain.ChainPolicy.VerificationFlags = onlineChain.ChainPolicy.VerificationFlags;
offlineChain.ChainPolicy.VerificationTime = onlineChain.ChainPolicy.VerificationTime;
offlineChain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
offlineChain.ChainPolicy.RevocationFlag = onlineChain.ChainPolicy.RevocationFlag;
valid = offlineChain.Build(cert);
Assert.True(valid, "Offline Chain Built Validly");
// Everything should look just like the online chain:
Assert.Equal(onlineChain.ChainElements.Count, offlineChain.ChainElements.Count);
for (int i = 0; i < offlineChain.ChainElements.Count; i++)
{
X509ChainElement onlineElement = onlineChain.ChainElements[i];
X509ChainElement offlineElement = offlineChain.ChainElements[i];
Assert.Equal(onlineElement.ChainElementStatus, offlineElement.ChainElementStatus);
Assert.Equal(onlineElement.Certificate, offlineElement.Certificate);
}
}
}
[Fact]
public static void Create()
{
using (var chain = X509Chain.Create())
Assert.NotNull(chain);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using Fasterflect;
using VirtualObjects.Exceptions;
using VirtualObjects.CodeGenerators;
namespace VirtualObjects.Config
{
/// <summary>
/// Maps a type into an IEntityInfo. Caches out the results.
/// </summary>
class Mapper : IMapper
{
private readonly IOperationsProvider _operationsProvider;
private readonly IEntityInfoCodeGeneratorFactory _codeGeneratorFactory;
private readonly ITranslationConfiguration _configuration;
private readonly IEntityBag _entityBag;
public Mapper(IEntityBag entityBag, ITranslationConfiguration configuration, IOperationsProvider operationsProvider, IEntityInfoCodeGeneratorFactory codeGeneratorFactory)
{
_configuration = configuration;
_codeGeneratorFactory = codeGeneratorFactory;
_operationsProvider = operationsProvider;
_entityBag = entityBag;
}
#region IMapper Members
public IEntityInfo Map(Type entityType)
{
if (entityType.IsFrameworkType() || entityType.IsDynamic())
{
return null;
}
if (entityType.IsProxy())
{
return Map(entityType.BaseType);
}
try
{
return MapType(entityType);
}
catch (Exception ex)
{
throw new MappingException(Errors.UnableToMapEntity, entityType, ex);
}
}
private void MapRelatedEntities(IEntityInfo entityInfo)
{
foreach (var property in entityInfo.EntityType.GetProperties().Where(e => e.IsVirtual() && e.PropertyType.IsCollection()))
{
var entityType = property.PropertyType.GetGenericArguments().First();
Map(entityType);
}
}
private IEntityInfo MapType(Type entityType)
{
IEntityInfo entityInfo;
if (_entityBag.TryGetValue(entityType, out entityInfo) && entityInfo.State >= Mapping.FieldsMapped)
{
return entityInfo;
}
_entityBag[entityType] = entityInfo = new EntityInfo
{
EntityName = GetName(entityType),
EntityType = entityType
};
entityInfo.State = Mapping.Mapping;
entityInfo.Columns = MapColumns(entityInfo).ToList();
entityInfo.KeyColumns = entityInfo.Columns.Where(e => e.IsKey).ToList();
entityInfo.State = Mapping.KeysMapped;
int i = 0;
foreach (var column in entityInfo.Columns)
{
column.Index = i++;
column.ForeignKey = GetForeignKey(entityInfo, column.Property);
}
entityInfo.Columns = WrapColumns(entityInfo.Columns).ToList();
entityInfo.KeyColumns = entityInfo.Columns.Where(e => e.IsKey).ToList();
#if DEBUG
entityInfo.Columns.ForEach(e =>
{
if (e.ForeignKey == null && !e.Property.PropertyType.IsFrameworkType() && !e.Property.PropertyType.IsEnum)
{
throw new ConfigException("The column [{ColumnName}] returns a complex type but is not associated with another key.", e);
}
if (e.ForeignKey != null && !(e is EntityBoundColumnInfo))
{
throw new ConfigException("The column [{ColumnName}] returns a complex type but is not associated with another key.", e);
}
});
#endif
//
// Calculation of the entity Key.
//
entityInfo.KeyHashCode = obj => entityInfo.KeyColumns
.Aggregate(new StringBuffer(), (current, key) => current + key.GetFieldFinalValue(obj).ToString())
.GetHashCode();
entityInfo.Identity = entityInfo.KeyColumns.FirstOrDefault(e => e.IsIdentity);
entityInfo.VersionControl = entityInfo.Columns.FirstOrDefault(e => e.IsVersionControl);
entityInfo.ForeignKeys = entityInfo.Columns.Where(e => e.ForeignKey != null).ToList();
foreach (var column in entityInfo.Columns)
{
column.ForeignKeyLinks = GetForeignKeyLinks(column, entityInfo).ToList();
}
foreach (var foreignKey in entityInfo.ForeignKeys
.Where(foreignKey => foreignKey.Property.Name == foreignKey.ColumnName)
.Where(foreignKey => foreignKey.ForeignKeyLinks != null && foreignKey.ForeignKeyLinks.Any()))
{
// Remove foreignKey from columns if it was used only for bind purposes.
// This should be used when a lazy load is needed with multiple keys.
entityInfo.Columns.Remove(foreignKey);
}
// By this point all fields are mapped.
entityInfo.State = Mapping.FieldsMapped;
MapRelatedEntities(entityInfo);
entityInfo.State = Mapping.RelatedEntitiesMapped;
entityInfo.Operations = _operationsProvider.CreateOperations(entityInfo);
entityInfo.State = Mapping.OperationsCreated;
var codeGenerator = _codeGeneratorFactory.Make(entityInfo);
codeGenerator.GenerateCode();
entityInfo.MapEntity = codeGenerator.GetEntityMapper();
entityInfo.EntityFactory = codeGenerator.GetEntityProvider();
entityInfo.EntityProxyFactory = codeGenerator.GetEntityProxyProvider();
entityInfo.EntityCast = codeGenerator.GetEntityCast();
entityInfo.State = Mapping.Ready;
return entityInfo;
}
private static IEnumerable<IEntityColumnInfo> WrapColumns(IEnumerable<IEntityColumnInfo> columns)
{
return columns.Select(WrapColumn);
}
private static IEntityColumnInfo WrapColumn(IEntityColumnInfo column)
{
if (column.ForeignKey != null)
{
return WrapWithBoundColumn(column);
}
if (column.Property.PropertyType == typeof(DateTime))
{
return WrapWithDatetimeColumn(column);
}
if (column.Property.PropertyType == typeof(Guid))
{
return WrapWithGuidColumn(column);
}
return column;
}
private static IEntityColumnInfo WrapWithGuidColumn(IEntityColumnInfo column)
{
return new EntityGuidColumnInfo
{
Property = column.Property,
ColumnName = column.ColumnName,
EntityInfo = column.EntityInfo,
ForeignKey = column.ForeignKey,
IsIdentity = column.IsIdentity,
IsKey = column.IsKey,
ValueGetter = column.ValueGetter,
ValueSetter = column.ValueSetter,
IsVersionControl = column.IsVersionControl
};
}
private static IEntityColumnInfo WrapWithDatetimeColumn(IEntityColumnInfo column)
{
return new EntityDateTimeColumnInfo
{
Property = column.Property,
ColumnName = column.ColumnName,
EntityInfo = column.EntityInfo,
ForeignKey = column.ForeignKey,
IsIdentity = column.IsIdentity,
IsKey = column.IsKey,
ValueGetter = column.ValueGetter,
ValueSetter = column.ValueSetter,
IsVersionControl = column.IsVersionControl
};
}
private static IEntityColumnInfo WrapWithBoundColumn(IEntityColumnInfo column)
{
return new EntityBoundColumnInfo
{
Property = column.Property,
ColumnName = column.ColumnName,
EntityInfo = column.EntityInfo,
ForeignKey = column.ForeignKey,
ForeignKeyLinks = column.ForeignKeyLinks,
IsIdentity = column.IsIdentity,
IsKey = column.IsKey,
ValueGetter = column.ValueGetter,
ValueSetter = column.ValueSetter
};
}
#endregion
#region Auxiliary Entity mapping methods
private string GetName(Type entityType)
{
return _configuration.EntityNameGetters
.Select(nameGetter => nameGetter(entityType))
.FirstOrDefault(name => !String.IsNullOrEmpty(name));
}
#endregion
#region Auxiliary column mapping methods
private IEnumerable<IEntityColumnInfo> MapColumns(IEntityInfo entityInfo)
{
return MapColumns(entityInfo, entityInfo.EntityType);
}
private IEnumerable<IEntityColumnInfo> MapColumns(IEntityInfo entityInfo, Type type)
{
if (type == typeof(Object))
{
return new IEntityColumnInfo[0];
}
var baseColumns = MapColumns(entityInfo, type.BaseType);
return baseColumns.Concat(type.Properties()
.Where(e => !e.PropertyType.IsGenericType || !e.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
.Where(e => !ShouldIgnore(e))
.Where(e => !baseColumns.Select(o => o.Property.Name).Contains(e.Name))
.Select(e => MapColumn(e, entityInfo)));
}
private IEntityColumnInfo MapColumn(PropertyInfo propertyInfo, IEntityInfo entityInfo)
{
var columnName = GetName(propertyInfo);
if (columnName == null)
{
throw new MappingException(Errors.Mapping_UnableToGetColumnName, propertyInfo);
}
var column = new EntityColumnInfo
{
EntityInfo = entityInfo,
ColumnName = columnName,
IsKey = GetIsKey(propertyInfo),
IsIdentity = GetIsIdentity(propertyInfo),
IsVersionControl = _configuration.ColumnVersionFieldGetters.Any(isVersion => isVersion(propertyInfo)),
IsComputed = _configuration.ComputedColumnGetters.Any(isComputed => isComputed(propertyInfo)),
Property = propertyInfo,
ValueGetter = MakeValueGetter(columnName, propertyInfo.DelegateForGetPropertyValue()),
ValueSetter = MakeValueSetter(columnName, propertyInfo.DelegateForSetPropertyValue()),
InjectNulls = _configuration.IsForeignKeyGetters.Any(isForeignKey => isForeignKey(propertyInfo))
};
return column;
}
private IEntityColumnInfo GetForeignKey(IEntityInfo entityInfo, PropertyInfo propertyInfo)
{
if (propertyInfo.PropertyType.IsFrameworkType() || propertyInfo.PropertyType.IsEnum)
{
return null;
}
//
// If mapping a column with the same type as the current entity, use the current entity.
var entity = (propertyInfo.PropertyType == entityInfo.EntityType) ? entityInfo : Map(propertyInfo.PropertyType);
var keyName = _configuration.ColumnForeignKeyGetters
.Select(keyGetter => keyGetter(propertyInfo))
.FirstOrDefault();
var foreignKey = String.IsNullOrEmpty(keyName) ?
entity.KeyColumns.FirstOrDefault() :
entity[keyName];
if (foreignKey == null && _configuration.ColumnForeignKeyGetters.Any())
{
throw new ConfigException(Errors.Mapping_UnableToGetForeignKey, propertyInfo);
}
return foreignKey;
}
private IEnumerable<KeyValuePair<IEntityColumnInfo, IEntityColumnInfo>> GetForeignKeyLinks(IEntityColumnInfo column, IEntityInfo currentEntity)
{
if (column.ForeignKey != null)
{
var links = _configuration.ColumnForeignKeyLinksGetters
.Select(keyGetter => keyGetter(column.Property))
.FirstOrDefault();
if (links == null) yield break;
foreach (var link in links.Split(';'))
{
var properties = link.Split(':');
if (!link.Contains(':') && properties.Length != 2)
{
throw new MappingException(
"\nThe Bind was not properly set:\n" +
"Please use: [Property1]:[Property1]\n" +
"Where\n" +
" - Property1 is the property in the current entity.\n" +
" - Property2 is the property in the referenced entity.");
}
var firstField = currentEntity[properties[0]];
if (firstField == null)
{
throw new MappingException(
Errors.Mapping_FieldNotFoundOnEntity,
new
{
Name = properties[0],
currentEntity.EntityName
});
}
var columnLink = column.ForeignKey.EntityInfo[properties[1]];
if (columnLink == null)
{
throw new MappingException(
Errors.Mapping_FieldNotFoundOnEntity,
new
{
Name = properties[1],
column.ForeignKey.EntityInfo.EntityName
});
}
yield return new KeyValuePair<IEntityColumnInfo, IEntityColumnInfo>(firstField, columnLink);
}
}
}
private bool ShouldIgnore(PropertyInfo propertyInfo)
{
return _configuration.ColumnIgnoreGetters.Any(e => e(propertyInfo));
}
private bool GetIsIdentity(PropertyInfo propertyInfo)
{
return _configuration.ColumnIdentityGetters.Any(e => e(propertyInfo));
}
private bool GetIsKey(PropertyInfo propertyInfo)
{
return _configuration.ColumnKeyGetters.Any(e => e(propertyInfo));
}
private string GetName(PropertyInfo propertyInfo)
{
return _configuration.ColumnNameGetters
.Select(nameGetter => nameGetter(propertyInfo))
.FirstOrDefault(name => !String.IsNullOrEmpty(name));
}
private static Func<Object, Object> MakeValueGetter(String fieldName, MemberGetter getter)
{
return entity =>
{
try
{
return getter(entity);
}
catch (Exception ex)
{
throw new ConfigException(
Errors.Mapping_UnableToGetValue,
new
{
FieldName = fieldName
}, ex);
}
};
}
private static Action<Object, Object> MakeValueSetter(String fieldName, MemberSetter setter)
{
return (entity, value) =>
{
try
{
setter(entity, value);
}
catch (Exception ex)
{
throw new ConfigException(
Errors.Mapping_UnableToSetValue,
new
{
FieldName = fieldName,
Value = value
}, ex);
}
};
}
#endregion
#region IDisposable Members
private bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
}
}
#endregion
}
#pragma warning disable 1591
public enum Mapping
{
FieldsMapped = 50,
RelatedEntitiesMapped = 60,
OperationsCreated = 90,
Ready = 100,
Mapping = 0,
KeysMapped = 1
}
#pragma warning restore 1591
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NSubstitute;
using NuGet.Packaging.Core;
using NuGet.Versioning;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.NuGet;
using NuKeeper.Abstractions.NuGetApi;
using NuKeeper.Inspection.NuGetApi;
using NUnit.Framework;
namespace NuKeeper.Inspection.Tests.NuGetApi
{
[TestFixture]
public class UsePreleaseLookupTests
{
[TestCase(false, VersionChange.Major, 2, 3, 4, "")]
[TestCase(false, VersionChange.Minor, 1, 3, 1, "")]
[TestCase(false, VersionChange.Patch, 1, 2, 5, "")]
[TestCase(false, VersionChange.None, 1, 2, 3, "")]
[TestCase(true, VersionChange.Major, 2, 3, 4, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Minor, 1, 3, 1, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Patch, 1, 2, 5, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.None, 1, 2, 3, PackageVersionTestData.PrereleaseLabel)]
public async Task WhenFromPrereleaseIsAllowedFromPrereleaseAndCurrentVersionIsPrerelease(
bool latestPackageIsPrerelease,
VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
if (latestPackageIsPrerelease)
{
// Only grab updated prerelease packages for this test - otherwise we'll upgrade to 2.3.4 instead of 2.3.4-prerelease
resultPackages = resultPackages.Where(x => x.Identity.Version.IsPrerelease).ToList();
}
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123Prerelease("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.FromPrerelease);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
[TestCase(VersionChange.Major, 2, 3, 4, "")]
[TestCase(VersionChange.Minor, 1, 3, 1, "")]
[TestCase(VersionChange.Patch, 1, 2, 5, "")]
[TestCase(VersionChange.None, 1, 2, 3, "")]
public async Task WhenFromPrereleaseIsAllowedFromPrereleaseAndCurrentVersionIsStable(VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.FromPrerelease);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
[TestCase(false, VersionChange.Major, 2, 3, 4, "")]
[TestCase(false, VersionChange.Minor, 1, 3, 1, "")]
[TestCase(false, VersionChange.Patch, 1, 2, 5, "")]
[TestCase(false, VersionChange.None, 1, 2, 3, "")]
[TestCase(true, VersionChange.Major, 2, 3, 4, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Minor, 1, 3, 1, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Patch, 1, 2, 5, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.None, 1, 2, 3, PackageVersionTestData.PrereleaseLabel)]
public async Task WhenFromPrereleaseIsAlwaysAllowedAndCurrentVersionIsPrerelease(
bool latestPackageIsPrerelease,
VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
if (latestPackageIsPrerelease)
{
// Only grab updated prerelease packages for this test - otherwise we'll upgrade to 2.3.4 instead of 2.3.4-prerelease
resultPackages = resultPackages.Where(x => x.Identity.Version.IsPrerelease).ToList();
}
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123Prerelease("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.Always);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
[TestCase(false, VersionChange.Major, 2, 3, 4, "")]
[TestCase(false, VersionChange.Minor, 1, 3, 1, "")]
[TestCase(false, VersionChange.Patch, 1, 2, 5, "")]
[TestCase(false, VersionChange.None, 1, 2, 3, "")]
[TestCase(true, VersionChange.Major, 2, 3, 4, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Minor, 1, 3, 1, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.Patch, 1, 2, 5, PackageVersionTestData.PrereleaseLabel)]
[TestCase(true, VersionChange.None, 1, 2, 3, PackageVersionTestData.PrereleaseLabel)]
public async Task WhenFromPrereleaseIsAlwaysAllowedAndCurrentVersionIsStable(
bool latestPackageIsPrerelease,
VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
if (latestPackageIsPrerelease)
{
// Only grab updated prerelease packages for this test - otherwise we'll upgrade to 2.3.4 instead of 2.3.4-prerelease
resultPackages = resultPackages.Where(x => x.Identity.Version.IsPrerelease).ToList();
}
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.Always);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
[TestCase(VersionChange.Major, 2, 3, 4, "")]
[TestCase(VersionChange.Minor, 1, 3, 1, "")]
[TestCase(VersionChange.Patch, 1, 2, 5, "")]
[TestCase(VersionChange.None, 1, 2, 3, "")]
public async Task WhenFromPrereleaseIsNeverAllowedAndCurrentVersionIsPrerelease(
VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123Prerelease("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.Never);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
[TestCase(VersionChange.Major, 2, 3, 4, "")]
[TestCase(VersionChange.Minor, 1, 3, 1, "")]
[TestCase(VersionChange.Patch, 1, 2, 5, "")]
[TestCase(VersionChange.None, 1, 2, 3, "")]
public async Task WhenFromPrereleaseIsNeverAllowedAndCurrentVersionIsStable(
VersionChange dataRange,
int expectedMajor, int expectedMinor, int expectedPatch, string expectedReleaseLabel)
{
var expectedUpdate = new NuGetVersion(expectedMajor, expectedMinor, expectedPatch, expectedReleaseLabel);
var resultPackages = PackageVersionTestData.VersionsFor(dataRange);
var allVersionsLookup = MockVersionLookup(resultPackages);
IApiPackageLookup lookup = new ApiPackageLookup(allVersionsLookup);
var updates = await lookup.FindVersionUpdate(
CurrentVersion123("TestPackage"),
NuGetSources.GlobalFeed,
VersionChange.Major,
UsePrerelease.Never);
AssertPackagesIdentityIs(updates, "TestPackage");
Assert.That(updates.Selected().Identity.Version, Is.EqualTo(expectedUpdate));
Assert.That(updates.Major.Identity.Version, Is.EqualTo(HighestVersion(resultPackages)));
}
private static IPackageVersionsLookup MockVersionLookup(List<PackageSearchMetadata> actualResults)
{
var allVersions = Substitute.For<IPackageVersionsLookup>();
allVersions.Lookup(Arg.Any<string>(), false, Arg.Any<NuGetSources>())
.Returns(actualResults.Where(x => !x.Identity.Version.IsPrerelease).ToList());
allVersions.Lookup(Arg.Any<string>(), true, Arg.Any<NuGetSources>())
.Returns(actualResults);
return allVersions;
}
private static PackageIdentity CurrentVersion123(string packageId)
{
return new PackageIdentity(packageId, new NuGetVersion(1, 2, 3));
}
private static PackageIdentity CurrentVersion123Prerelease(string packageId)
{
return new PackageIdentity(packageId, new NuGetVersion(1, 2, 3, PackageVersionTestData.PrereleaseLabel));
}
private static void AssertPackagesIdentityIs(PackageLookupResult packages, string id)
{
Assert.That(packages, Is.Not.Null);
AssertPackageIdentityIs(packages.Major, id);
AssertPackageIdentityIs(packages.Selected(), id);
Assert.That(packages.Major.Identity.Version, Is.GreaterThanOrEqualTo(packages.Selected().Identity));
}
private static void AssertPackageIdentityIs(PackageSearchMetadata package, string id)
{
Assert.That(package, Is.Not.Null);
Assert.That(package.Identity, Is.Not.Null);
Assert.That(package.Identity.Id, Is.EqualTo(id));
}
private static NuGetVersion HighestVersion(IEnumerable<PackageSearchMetadata> packages)
{
return packages
.Select(p => p.Identity.Version)
.OrderByDescending(v => v)
.First();
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Petstore
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial interface ISwaggerPetstore : System.IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a new
/// pet to the store
/// </summary>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> AddPetUsingByteArrayWithHttpMessagesAsync(string body = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input
/// if your pet is invalid.
/// </remarks>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> AddPetWithHttpMessagesAsync(Pet body = default(Pet), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body = default(Pet), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use
/// tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will
/// simulate API error conditions
/// </remarks>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string>> FindPetsWithByteArrayWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will
/// simulate API error conditions
/// </remarks>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(string petId, string name = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// uploads an image
/// </summary>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UploadFileWithHttpMessagesAsync(long petId, string additionalMetadata = default(string), Stream file = default(Stream), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body = default(Order), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10.
/// Other values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything
/// above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body = default(User), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body = default(IList<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body = default(IList<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string>> LoginUserWithHttpMessagesAsync(string username = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body = default(User), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage.Internal;
namespace Orleans.Storage
{
/// <summary>
/// This is a simple in-memory grain implementation of a storage provider.
/// </summary>
/// <remarks>
/// This storage provider is ONLY intended for simple in-memory Development / Unit Test scenarios.
/// This class should NOT be used in Production environment,
/// because [by-design] it does not provide any resilience
/// or long-term persistence capabilities.
/// </remarks>
/// <example>
/// Example configuration for this storage provider in OrleansConfiguration.xml file:
/// <code>
/// <OrleansConfiguration xmlns="urn:orleans">
/// <Globals>
/// <StorageProviders>
/// <Provider Type="Orleans.Storage.MemoryStorage" Name="MemoryStore" />
/// </StorageProviders>
/// </code>
/// </example>
[DebuggerDisplay("MemoryStore:{Name}")]
public class MemoryGrainStorage : IGrainStorage, IDisposable
{
private MemoryGrainStorageOptions options;
private const string STATE_STORE_NAME = "MemoryStorage";
private Lazy<IMemoryStorageGrain>[] storageGrains;
private ILogger logger;
private IGrainFactory grainFactory;
/// <summary> Name of this storage provider instance. </summary>
private readonly string name;
/// <summary> Default constructor. </summary>
public MemoryGrainStorage(string name, MemoryGrainStorageOptions options, ILoggerFactory loggerFactory, IGrainFactory grainFactory)
{
this.options = options;
this.name = name;
this.logger = loggerFactory.CreateLogger($"{this.GetType().FullName}.{name}");
this.grainFactory = grainFactory;
//Init
logger.LogInformation("Init: Name={Name} NumStorageGrains={NumStorageGrains}", name, this.options.NumStorageGrains);
storageGrains = new Lazy<IMemoryStorageGrain>[this.options.NumStorageGrains];
for (int i = 0; i < this.options.NumStorageGrains; i++)
{
int idx = i; // Capture variable to avoid modified closure error
storageGrains[idx] = new Lazy<IMemoryStorageGrain>(() => this.grainFactory.GetGrain<IMemoryStorageGrain>(idx));
}
}
/// <summary> Read state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ReadStateAsync"/>
public virtual async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Read Keys={Keys}", StorageProviderUtils.PrintKeys(keys));
string id = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(id);
var state = await storageGrain.ReadStateAsync(STATE_STORE_NAME, id);
if (state != null)
{
grainState.ETag = state.ETag;
grainState.State = state.State;
}
}
/// <summary> Write state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.WriteStateAsync"/>
public virtual async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
string key = HierarchicalKeyStore.MakeStoreKey(keys);
if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Write {Write} ", StorageProviderUtils.PrintOneWrite(keys, grainState.State, grainState.ETag));
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
grainState.ETag = await storageGrain.WriteStateAsync(STATE_STORE_NAME, key, grainState);
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
/// <summary> Delete / Clear state data function for this storage provider. </summary>
/// <see cref="IGrainStorage.ClearStateAsync"/>
public virtual async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
{
IList<Tuple<string, string>> keys = MakeKeys(grainType, grainReference).ToList();
if (logger.IsEnabled(LogLevel.Trace)) logger.LogTrace("Delete Keys={Keys} Etag={Etag}", StorageProviderUtils.PrintKeys(keys), grainState.ETag);
string key = HierarchicalKeyStore.MakeStoreKey(keys);
IMemoryStorageGrain storageGrain = GetStorageGrain(key);
try
{
await storageGrain.DeleteStateAsync(STATE_STORE_NAME, key, grainState.ETag);
grainState.ETag = null;
}
catch (MemoryStorageEtagMismatchException e)
{
throw e.AsInconsistentStateException();
}
}
private static IEnumerable<Tuple<string, string>> MakeKeys(string grainType, GrainReference grain)
{
return new[]
{
Tuple.Create("GrainType", grainType),
Tuple.Create("GrainId", grain.ToKeyString())
};
}
private IMemoryStorageGrain GetStorageGrain(string id)
{
int idx = StorageProviderUtils.PositiveHash(id.GetHashCode(), this.options.NumStorageGrains);
IMemoryStorageGrain storageGrain = storageGrains[idx].Value;
return storageGrain;
}
internal static Func<IDictionary<string, object>, bool> GetComparer<T>(string rangeParamName, T fromValue, T toValue) where T : IComparable
{
Comparer comparer = Comparer.DefaultInvariant;
bool sameRange = comparer.Compare(fromValue, toValue) == 0; // FromValue == ToValue
bool insideRange = comparer.Compare(fromValue, toValue) < 0; // FromValue < ToValue
Func<IDictionary<string, object>, bool> compareClause;
if (sameRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) == 0;
};
}
else if (insideRange)
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 && comparer.Compare(obj, toValue) <= 0;
};
}
else
{
compareClause = data =>
{
if (data == null || data.Count <= 0) return false;
if (!data.ContainsKey(rangeParamName))
{
var error = string.Format("Cannot find column '{0}' for range query from {1} to {2} in Data={3}",
rangeParamName, fromValue, toValue, StorageProviderUtils.PrintData(data));
throw new KeyNotFoundException(error);
}
T obj = (T) data[rangeParamName];
return comparer.Compare(obj, fromValue) >= 0 || comparer.Compare(obj, toValue) <= 0;
};
}
return compareClause;
}
public void Dispose()
{
for (int i = 0; i < this.options.NumStorageGrains; i++)
storageGrains[i] = null;
}
}
/// <summary>
/// Factory for creating MemoryGrainStorage
/// </summary>
public class MemoryGrainStorageFactory
{
public static IGrainStorage Create(IServiceProvider services, string name)
{
return ActivatorUtilities.CreateInstance<MemoryGrainStorage>(services,
services.GetRequiredService<IOptionsMonitor<MemoryGrainStorageOptions>>().Get(name), name);
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using MigraDoc.DocumentObjectModel.Internals;
using MigraDoc.DocumentObjectModel.Visitors;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using MigraDoc.DocumentObjectModel.Shapes;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// Represents a collection of document elements.
/// </summary>
public class DocumentElements : DocumentObjectCollection, IVisitable
{
/// <summary>
/// Initializes a new instance of the DocumentElements class.
/// </summary>
public DocumentElements()
{
}
/// <summary>
/// Initializes a new instance of the DocumentElements class with the specified parent.
/// </summary>
internal DocumentElements(DocumentObject parent) : base(parent) { }
/// <summary>
/// Gets a document object by its index.
/// </summary>
public new DocumentObject this[int index]
{
get { return base[index]; }
}
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new DocumentElements Clone()
{
return (DocumentElements)DeepCopy();
}
/// <summary>
/// Adds a new paragraph to the collection.
/// </summary>
public Paragraph AddParagraph()
{
Paragraph paragraph = new Paragraph();
Add(paragraph);
return paragraph;
}
/// <summary>
/// Adds a new paragraph with the specified text to the collection.
/// </summary>
public Paragraph AddParagraph(string text)
{
Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
Add(paragraph);
return paragraph;
}
/// <summary>
/// Adds a new paragraph with the specified text and style to the collection.
/// </summary>
public Paragraph AddParagraph(string text, string style)
{
Paragraph paragraph = new Paragraph();
paragraph.AddText(text);
paragraph.Style = style;
Add(paragraph);
return paragraph;
}
/// <summary>
/// Adds a new table to the collection.
/// </summary>
public Table AddTable()
{
Table tbl = new Table();
Add(tbl);
return tbl;
}
/// <summary>
/// Adds a new legend to the collection.
/// </summary>
public Legend AddLegend()
{
Legend legend = new Legend();
Add(legend);
return legend;
}
/// <summary>
/// Add a manual page break.
/// </summary>
public void AddPageBreak()
{
PageBreak pageBreak = new PageBreak();
Add(pageBreak);
}
/// <summary>
/// Adds a new barcode to the collection.
/// </summary>
public Barcode AddBarcode()
{
Barcode barcode = new Barcode();
Add(barcode);
return barcode;
}
/// <summary>
/// Adds a new chart with the specified type to the collection.
/// </summary>
public Chart AddChart(ChartType type)
{
Chart chart = AddChart();
chart.Type = type;
return chart;
}
/// <summary>
/// Adds a new chart with the specified type to the collection.
/// </summary>
public Chart AddChart()
{
Chart chart = new Chart();
chart.Type = ChartType.Line;
Add(chart);
return chart;
}
/// <summary>
/// Adds a new image to the collection.
/// </summary>
public Image AddImage(string name)
{
Image image = new Image();
image.Name = name;
Add(image);
return image;
}
/// <summary>
/// Adds a new image to the collection from a MemoryStream.
/// </summary>
/// <returns></returns>
public Image AddImage(MemoryStream stream)
{
Image image = new Image();
image.StreamBased = true;
image.ImageStream = stream;
image.Name = String.Empty;
Add(image);
return image;
}
/// <summary>
/// Adds a new text frame to the collection.
/// </summary>
public TextFrame AddTextFrame()
{
TextFrame textFrame = new TextFrame();
Add(textFrame);
return textFrame;
}
#endregion
#region Internal
/// <summary>
/// Converts DocumentElements into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
int count = Count;
if (count == 1 && this[0] is Paragraph)
{
// Omit keyword if paragraph has no attributes set.
Paragraph paragraph = (Paragraph)this[0];
if (paragraph.Style == "" && paragraph.IsNull("Format"))
{
paragraph.SerializeContentOnly = true;
paragraph.Serialize(serializer);
paragraph.SerializeContentOnly = false;
return;
}
}
for (int index = 0; index < count; index++)
{
DocumentObject documentElement = this[index];
documentElement.Serialize(serializer);
}
}
/// <summary>
/// Allows the visitor object to visit the document object and it's child objects.
/// </summary>
void IVisitable.AcceptVisitor(DocumentObjectVisitor visitor, bool visitChildren)
{
visitor.VisitDocumentElements(this);
foreach (DocumentObject docObject in this)
{
if (docObject is IVisitable)
((IVisitable)docObject).AcceptVisitor(visitor, visitChildren);
}
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get
{
if (meta == null)
meta = new Meta(typeof(DocumentElements));
return meta;
}
}
static Meta meta;
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mime;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using AspNet.WebApi.HtmlMicrodataFormatter;
using Lucene.Net.Linq;
using NuGet.Lucene.Util;
using NuGet.Lucene.Web.Models;
using NuGet.Lucene.Web.Symbols;
using NuGet.Lucene.Web.Util;
namespace NuGet.Lucene.Web.Controllers
{
/// <summary>
/// Provides methods to search, get metadata, download, upload and delete packages.
/// </summary>
public class PackagesController : ApiControllerBase
{
public ILucenePackageRepository LuceneRepository { get; set; }
public IMirroringPackageRepository MirroringRepository { get; set; }
public ISymbolSource SymbolSource { get; set; }
public ITaskRunner TaskRunner { get; set; }
/// <summary>
/// Gets metadata about a package from the <c>nuspec</c> files and other
/// metadata such as package size, date published, download counts, etc.
/// </summary>
public object GetPackageInfo(string id, string version="")
{
var packageSpec = new PackageSpec(id, version);
var packages = LuceneRepository
.LucenePackages
.Where(p => p.Id == packageSpec.Id)
.OrderBy(p => p.Version)
.ToList();
var package = packageSpec.Version != null
? packages.Find(p => p.Version.SemanticVersion == packageSpec.Version)
: packages.LastOrDefault();
if (package == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Package not found.");
}
var versionHistory = packages.Select(pkg => new PackageVersionSummary(pkg, new Link(GetPackageInfoUrl(pkg), pkg.Version.ToString()))).ToList();
versionHistory.Select(v => v.Link).SetRelationships(packages.IndexOf(package));
var result = new PackageWithVersionHistory();
package.ShallowClone(result);
result.PackageDownloadLink = new Link(Url.Link(RouteNames.Packages.Download, new { id = result.Id, version = result.Version }), "attachment", "Download Package");
result.VersionHistory = versionHistory.ToArray();
result.SymbolsAvailable = SymbolSource.AreSymbolsPresentFor(package);
return result;
}
private string GetPackageInfoUrl(LucenePackage pkg)
{
return Url.Link(RouteNames.Packages.Info, new { id = pkg.Id, version = pkg.Version });
}
/// <summary>
/// Downloads the complete <c>.nupkg</c> content. The HTTP HEAD method
/// is also supported for verifying package size, and modification date.
/// The <c>ETag</c> response header will contain the md5 hash of the
/// package content.
/// </summary>
[HttpGet, HttpHead]
public HttpResponseMessage DownloadPackage(string id, string version="")
{
var packageSpec = new PackageSpec(id, version);
var package = FindPackage(packageSpec);
var result = EvaluateCacheHeaders(packageSpec, package);
if (result != null)
{
return result;
}
result = Request.CreateResponse(HttpStatusCode.OK);
if (Request.Method == HttpMethod.Get)
{
result.Content = new StreamContent(package.GetStream());
TaskRunner.QueueBackgroundWorkItem(cancellationToken => LuceneRepository.IncrementDownloadCountAsync(package, cancellationToken));
}
else
{
result.Content = new StringContent(string.Empty);
}
result.Headers.ETag = new EntityTagHeaderValue('"' + package.PackageHash + '"');
result.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/zip");
result.Content.Headers.LastModified = package.LastUpdated;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment)
{
FileName = string.Format("{0}.{1}{2}", package.Id, package.Version, Constants.PackageExtension),
Size = package.PackageSize,
CreationDate = package.Created,
ModificationDate = package.LastUpdated,
};
return result;
}
private HttpResponseMessage EvaluateCacheHeaders(PackageSpec packageSpec, LucenePackage package)
{
if (package == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound,
string.Format("Package {0} version {1} not found.", packageSpec.Id,
packageSpec.Version));
}
var etagMatch = Request.Headers.IfMatch.Any(etag => !etag.IsWeak && etag.Tag == '"' + package.PackageHash + '"');
var notModifiedSince = Request.Headers.IfModifiedSince.HasValue &&
Request.Headers.IfModifiedSince >= package.LastUpdated;
if (etagMatch || notModifiedSince)
{
return Request.CreateResponse(HttpStatusCode.NotModified);
}
return null;
}
/// <summary>
/// Searches for packages that match <paramref name="query"/>, or if no query
/// is provided, returns all packages in the repository.
/// </summary>
/// <param name="query">Search terms. May include special characters to support prefix,
/// wildcard or phrase queries.
/// </param>
/// <param name="includePrerelease">Specify <c>true</c> to look for pre-release packages.</param>
/// <param name="latestOnly">Specify <c>true</c> to only search most recent package version or <c>false</c> to search all versions</param>
/// <param name="offset">Number of results to skip, for pagination.</param>
/// <param name="count">Number of results to return, for pagination.</param>
/// <param name="originFilter">Limit result to mirrored or local packages, or both.</param>
/// <param name="sort">Specify field to sort results on. Score (relevance) is default.</param>
/// <param name="order">Sort order (default:ascending or descending)</param>
[HttpGet]
public dynamic Search(
string query = "",
bool includePrerelease = false,
bool latestOnly = true,
int offset = 0,
int count = 20,
PackageOriginFilter originFilter = PackageOriginFilter.Any,
SearchSortField sort = SearchSortField.Score,
SearchSortDirection order = SearchSortDirection.Ascending)
{
var criteria = new SearchCriteria(query)
{
AllowPrereleaseVersions = includePrerelease,
PackageOriginFilter = originFilter,
SortField = sort,
SortDirection = order
};
LuceneQueryStatistics stats = null;
List<IPackage> hits;
try
{
var queryable = LuceneRepository.Search(criteria).CaptureStatistics(s => stats = s);
if (latestOnly)
{
queryable = queryable.LatestOnly(includePrerelease);
}
hits = queryable.Skip(offset).Take(count).ToList();
}
catch (InvalidSearchCriteriaException ex)
{
var message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, message);
}
dynamic result = new ExpandoObject();
// criteria
result.Query = query;
result.IncludePrerelease = includePrerelease;
result.TotalHits = stats.TotalHits;
result.OriginFilter = originFilter;
result.Sort = sort;
result.Order = order;
// statistics
result.Offset = stats.SkippedHits;
result.Count = stats.RetrievedDocuments;
result.ElapsedPreparationTime = stats.ElapsedPreparationTime;
result.ElapsedSearchTime = stats.ElapsedSearchTime;
result.ElapsedRetrievalTime = stats.ElapsedRetrievalTime;
var chars = stats.Query.ToString().Normalize(NormalizationForm.FormD);
result.ComputedQuery = new string(chars.Where(c => c < 0x7f && !char.IsControl(c)).ToArray());
// hits
result.Hits = hits;
return result;
}
/// <summary>
/// Gets a list of fields that can be searched using the advanced search function.
/// </summary>
[HttpGet]
public IList<string> GetAvailableSearchFieldNames()
{
return LuceneRepository.GetAvailableSearchFieldNames().ToList();
}
/// <summary>
/// Permanently delete a package from the repository.
/// </summary>
[Authorize(Roles=RoleNames.PackageManager)]
public async Task<HttpResponseMessage> DeletePackage(string id, string version="")
{
if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(version))
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Must specify package id and version.");
}
var package = LuceneRepository.FindPackage(id, new SemanticVersion(version));
if (package == null)
{
var message = string.Format("Package '{0}' version '{1}' not found.", id, version);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
Audit("Delete package {0} version {1}", id, version);
var task1 = LuceneRepository.RemovePackageAsync(package, CancellationToken.None);
var task2 = SymbolSource.RemoveSymbolsAsync(package);
await Task.WhenAll(task1, task2);
return Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Upload a package to the repository. If a package already exists
/// with the same Id and Version, it will be replaced with the new package.
/// </summary>
[HttpPut]
[HttpPost]
[Authorize(Roles = RoleNames.PackageManager)]
public async Task<HttpResponseMessage> PutPackage([FromBody]IPackage package)
{
if (package == null || string.IsNullOrWhiteSpace(package.Id) || package.Version == null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Must provide package with valid id and version.");
}
if (package.HasSourceAndSymbols())
{
var response = Request.CreateResponse(HttpStatusCode.RedirectKeepVerb);
response.Headers.Location = new Uri(Url.Link(RouteNames.Symbols.Upload, null), UriKind.RelativeOrAbsolute);
return response;
}
try
{
Audit("Add package {0} version {1}", package.Id, package.Version);
await LuceneRepository.AddPackageAsync(package, CancellationToken.None);
}
catch (PackageOverwriteDeniedException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex.Message);
}
var location = Url.Link(RouteNames.Packages.Info, new { id = package.Id, version = package.Version });
var result = Request.CreateResponse(HttpStatusCode.Created);
result.Headers.Location = new Uri(location);
return result;
}
private LucenePackage FindPackage(PackageSpec packageSpec)
{
if (packageSpec.Version == null)
{
return FindNewestReleasePackage(packageSpec.Id);
}
var package = MirroringRepository.FindPackage(packageSpec.Id, packageSpec.Version);
return package != null ? LuceneRepository.Convert(package) : null;
}
private LucenePackage FindNewestReleasePackage(string packageId)
{
return (LucenePackage) LuceneRepository
.FindPackagesById(packageId)
.Where(p => p.IsReleaseVersion())
.OrderByDescending(p => p.Version)
.FirstOrDefault();
}
}
}
| |
namespace FakeItEasy.Tests.Creation
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using FakeItEasy.Core;
using FakeItEasy.Creation;
using FakeItEasy.Tests.TestHelpers;
using FluentAssertions;
using Xunit;
public class DummyValueResolverTests
{
private readonly IFakeObjectCreator fakeObjectCreator;
public DummyValueResolverTests()
{
this.fakeObjectCreator = A.Fake<IFakeObjectCreator>();
A.CallTo(() => this.fakeObjectCreator.CreateFakeWithoutLoopDetection(
A<Type>._,
A<IProxyOptions>._,
A<IDummyValueResolver>._,
A<LoopDetectingResolutionContext>._))
.ReturnsLazily((
Type type,
IProxyOptions proxyOptions,
IDummyValueResolver resolver,
LoopDetectingResolutionContext resolutionContext) =>
CreationResult.FailedToCreateDummy(type, string.Empty));
}
public static IEnumerable<object?[]> DummiesInContainer()
{
return TestCases.FromObject(
"dummy value",
Task.FromResult(7),
Task.WhenAll()); // creates a completed Task
}
[Theory]
[MemberData(nameof(DummiesInContainer))]
public void Should_return_dummy_from_container_when_available(object dummyForContainer)
{
Guard.AgainstNull(dummyForContainer, nameof(dummyForContainer));
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakes(dummyForContainer),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(dummyForContainer.GetType(), new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().BeSameAs(dummyForContainer);
}
[Fact]
public void Should_return_failed_creation_result_when_type_cannot_be_created()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(TypeThatCanNotBeInstantiated),
new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeFalse();
}
[Fact]
public void Should_return_fake_when_it_can_be_created()
{
// Arrange
var fake = A.Fake<IFoo>();
this.StubFakeObjectCreatorWithValue(fake);
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(typeof(IFoo), new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().BeSameAs(fake);
}
[Fact]
public void Should_return_default_value_when_type_is_value_type()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(typeof(int), new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().Be(0);
}
[Fact]
public void Should_be_able_to_create_class_with_default_constructor()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(ClassWithDefaultConstructor),
new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().BeOfType<ClassWithDefaultConstructor>();
}
[Fact]
public void Should_be_able_to_create_class_with_resolvable_constructor_arguments()
{
// Arrange
this.StubFakeObjectCreatorWithValue(A.Fake<IFoo>());
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakes("dummy string"),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(TypeWithResolvableConstructorArguments<string, IFoo>),
new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().BeOfType<TypeWithResolvableConstructorArguments<string, IFoo>>();
}
[Fact]
public void Should_not_be_able_to_create_class_with_circular_dependencies()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(TypeWithCircularDependency),
new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeFalse();
}
[Fact]
public void Should_be_able_to_resolve_same_type_twice_when_successful()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakes("dummy value"),
this.fakeObjectCreator);
resolver.TryResolveDummyValue(typeof(string), new LoopDetectingResolutionContext());
// Act
var result = resolver.TryResolveDummyValue(typeof(string), new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
result.Result.Should().Be("dummy value");
}
[Fact]
public void Should_return_failed_result_when_default_constructor_throws()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(TypeWithDefaultConstructorThatThrows),
new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeFalse();
}
[Fact]
public void Should_favor_the_widest_constructor_when_activating()
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakes("dummy value"),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(
typeof(TypeWithMultipleConstructorsOfDifferentWidth),
new LoopDetectingResolutionContext());
// Assert
var dummy = result.Result;
dummy.Should().BeOfType<TypeWithMultipleConstructorsOfDifferentWidth>();
((TypeWithMultipleConstructorsOfDifferentWidth)dummy!).WidestConstructorWasCalled.Should().BeTrue();
}
[Theory]
[InlineData(typeof(void))]
[InlineData(typeof(Func<int>))]
[InlineData(typeof(Action))]
public void Should_return_failed_result_for_restricted_types(Type restrictedType)
{
// Arrange
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(restrictedType, new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeFalse();
}
[Fact]
public void Should_be_able_to_create_lazy_wrapper()
{
// Arrange
var fake = A.Fake<IFoo>();
this.StubFakeObjectCreatorWithValue(fake);
var resolver = new DummyValueResolver(
this.CreateDummyFactoryThatMakesNoDummy(),
this.fakeObjectCreator);
// Act
var result = resolver.TryResolveDummyValue(typeof(Lazy<IFoo>), new LoopDetectingResolutionContext());
// Assert
result.WasSuccessful.Should().BeTrue();
var dummy = result.Result;
dummy.Should().BeOfType<Lazy<IFoo>>();
((Lazy<IFoo>)dummy!).Value.Should().BeSameAs(fake);
}
private void StubFakeObjectCreatorWithValue<T>(T value)
{
A.CallTo(() => this.fakeObjectCreator.CreateFakeWithoutLoopDetection(
typeof(T),
A<IProxyOptions>._,
A<IDummyValueResolver>._,
A<LoopDetectingResolutionContext>._))
.Returns(CreationResult.SuccessfullyCreated(value));
}
private DynamicDummyFactory CreateDummyFactoryThatMakes(object value)
{
return new DynamicDummyFactory(new[] { new FixedDummyFactory(value) });
}
private DynamicDummyFactory CreateDummyFactoryThatMakesNoDummy()
{
return new DynamicDummyFactory(Array.Empty<IDummyFactory>());
}
public class ClassWithDefaultConstructor
{
}
public class TypeWithResolvableConstructorArguments<T1, T2>
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")]
public TypeWithResolvableConstructorArguments(T1 argument1, T2 argument2)
{
}
}
public class TypeWithCircularDependency
{
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "circular", Justification = "Required for testing.")]
public TypeWithCircularDependency(TypeWithCircularDependency circular)
{
}
}
public class TypeWithMultipleConstructorsOfDifferentWidth
{
public TypeWithMultipleConstructorsOfDifferentWidth()
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
public TypeWithMultipleConstructorsOfDifferentWidth(string argument1)
{
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument1", Justification = "Required for testing.")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "argument2", Justification = "Required for testing.")]
public TypeWithMultipleConstructorsOfDifferentWidth(string argument1, string argument2)
{
this.WidestConstructorWasCalled = true;
}
public bool WidestConstructorWasCalled { get; }
}
internal class FixedDummyFactory : IDummyFactory
{
private readonly object dummy;
public FixedDummyFactory(object dummy)
{
this.dummy = dummy;
}
public Priority Priority => Priority.Default;
public bool CanCreate(Type type)
{
return type == this.dummy.GetType();
}
public object Create(Type type)
{
return this.dummy;
}
}
private static class TypeThatCanNotBeInstantiated
{
}
private class TypeWithDefaultConstructorThatThrows
{
public TypeWithDefaultConstructorThatThrows()
{
throw new InvalidOperationException();
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Config.DataAccess;
using Frapid.Config.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Config.Api.Tests
{
public class CustomFieldFormTests
{
public static CustomFieldFormController Fixture()
{
CustomFieldFormController controller = new CustomFieldFormController(new CustomFieldFormRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().Get(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetFirst();
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetPrevious(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetNext(string.Empty);
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Config.Entities.CustomFieldForm customFieldForm = Fixture().GetLast();
Assert.NotNull(customFieldForm);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Config.Entities.CustomFieldForm> customFieldForms = Fixture().Get(new string[] { });
Assert.NotNull(customFieldForms);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(string.Empty, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(string.Empty);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
// 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.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class TypeManager
{
private BSYMMGR _BSymmgr;
private PredefinedTypes _predefTypes;
private readonly TypeFactory _typeFactory;
private readonly TypeTable _typeTable;
private SymbolTable _symbolTable;
// Special types
private readonly VoidType _voidType;
private readonly NullType _nullType;
private readonly MethodGroupType _typeMethGrp;
private readonly ArgumentListType _argListType;
private readonly ErrorType _errorType;
private readonly StdTypeVarColl _stvcMethod;
private readonly StdTypeVarColl _stvcClass;
public TypeManager(BSYMMGR bsymmgr, PredefinedTypes predefTypes)
{
_typeFactory = new TypeFactory();
_typeTable = new TypeTable();
// special types with their own symbol kind.
_errorType = _typeFactory.CreateError(null, null, null);
_voidType = _typeFactory.CreateVoid();
_nullType = _typeFactory.CreateNull();
_typeMethGrp = _typeFactory.CreateMethodGroup();
_argListType = _typeFactory.CreateArgList();
_errorType.SetErrors(true);
_stvcMethod = new StdTypeVarColl();
_stvcClass = new StdTypeVarColl();
_BSymmgr = bsymmgr;
_predefTypes = predefTypes;
}
public void InitTypeFactory(SymbolTable table)
{
_symbolTable = table;
}
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt = null;
if (iv >= this.prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = pTypeManager.GetTypeParameter(pTypeParameter);
this.prgptvs.Add(tpt);
}
else
{
tpt = this.prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Name name;
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
switch (args)
{
case 1:
if (isSZArray)
{
goto case 2;
}
else
{
goto default;
}
case 2:
name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args);
break;
default:
name = _BSymmgr.GetNameManager().Add("[X" + args + 1);
break;
}
// See if we already have an array type of this element type and rank.
ArrayType pArray = _typeTable.LookupArray(name, elementType);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray);
pArray.InitFromParent();
_typeTable.InsertArray(name, elementType, pArray);
}
else
{
Debug.Assert(pArray.HasErrors() == elementType.HasErrors());
}
Debug.Assert(pArray.rank == args);
Debug.Assert(pArray.GetElementType() == elementType);
return pArray;
}
public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(agg.GetTypeManager() == this);
Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
Name name = _BSymmgr.GetNameFromPtrs(typeArgs, atsOuter);
Debug.Assert(name != null);
AggregateType pAggregate = _typeTable.LookupAggregate(name, agg);
if (pAggregate == null)
{
pAggregate = _typeFactory.CreateAggregateType(
name,
agg,
typeArgs,
atsOuter
);
Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError);
pAggregate.SetErrors(false);
_typeTable.InsertAggregate(name, agg, pAggregate);
// If we have a generic type definition, then we need to set the
// base class to be our current base type, and use that to calculate
// our agg type and its base, then set it to be the generic version of the
// base type. This is because:
//
// Suppose we have Foo<T> : IFoo<T>
//
// Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution
// that we want to use for our agg type's base type. However, in the Symbol chain,
// we want the base type to be IFoo<IFoo.T>. Thats why we need to do this little trick.
//
// If we don't have a generic type definition, then we just need to set our base
// class. This is so that if we have a base type that's generic, we'll be
// getting the correctly instantiated base type.
var baseType = pAggregate.AssociatedSystemType?.BaseType;
if (baseType != null)
{
// Store the old base class.
AggregateType oldBaseType = agg.GetBaseClass();
agg.SetBaseClass(_symbolTable.GetCTypeFromType(baseType) as AggregateType);
pAggregate.GetBaseClass(); // Get the base type for the new agg type we're making.
agg.SetBaseClass(oldBaseType);
}
}
else
{
Debug.Assert(!pAggregate.HasErrors());
}
Debug.Assert(pAggregate.getAggregate() == agg);
Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null);
Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs);
return pAggregate;
}
public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public PointerType GetPointer(CType baseType)
{
PointerType pPointer = _typeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR);
pPointer = _typeFactory.CreatePointer(namePtr, baseType);
pPointer.InitFromParent();
_typeTable.InsertPointer(baseType, pPointer);
}
else
{
Debug.Assert(pPointer.HasErrors() == baseType.HasErrors());
}
Debug.Assert(pPointer.GetReferentType() == baseType);
return pPointer;
}
public NullableType GetNullable(CType pUnderlyingType)
{
if (pUnderlyingType is NullableType nt)
{
Debug.Fail("Attempt to make nullable of nullable");
return nt;
}
NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB);
pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this);
pNullableType.InitFromParent();
_typeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public NullableType GetNubFromNullable(AggregateType ats)
{
Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL));
return GetNullable(ats.GetTypeArgsAll()[0]);
}
public ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM);
ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = _typeFactory.CreateParameterModifier(name, paramType);
pParamModifier.isOut = isOut;
pParamModifier.InitFromParent();
_typeTable.InsertParameterModifier(name, paramType, pParamModifier);
}
else
{
Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors());
}
Debug.Assert(pParamModifier.GetParameterType() == paramType);
return pParamModifier;
}
public ErrorType GetErrorType(
Name nameText,
TypeArray typeArgs)
{
Debug.Assert(nameText != null);
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs);
Debug.Assert(name != null);
ErrorType pError = _typeTable.LookupError(name);
if (pError == null)
{
// No existing error symbol. Create a new one.
pError = _typeFactory.CreateError(name, nameText, typeArgs);
pError.SetErrors(true);
_typeTable.InsertError(name, pError);
}
else
{
Debug.Assert(pError.HasErrors());
Debug.Assert(pError.nameText == nameText);
Debug.Assert(pError.typeArgs == typeArgs);
}
return pError;
}
public VoidType GetVoid()
{
return _voidType;
}
public NullType GetNullType()
{
return _nullType;
}
public MethodGroupType GetMethGrpType()
{
return _typeMethGrp;
}
public ArgumentListType GetArgListType()
{
return _argListType;
}
public ErrorType GetErrorSym()
{
return _errorType;
}
public AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL);
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeSrc == null)
return null;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public CType SubstType(CType typeSrc, TypeArray typeArgsCls)
{
return SubstType(typeSrc, typeArgsCls, null, SubstTypeFlags.NormNone);
}
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext pctx)
{
if (taSrc == null || taSrc.Count == 0 || pctx == null || pctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = this.SubstTypeCore(taSrc[ipts], pctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
private TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (taSrc == null || taSrc.Count == 0)
return taSrc;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = SubstTypeCore(taSrc[ipts], ctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return this.SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls)
{
return this.SubstTypeArray(taSrc, typeArgsCls, (TypeArray)null, SubstTypeFlags.NormNone);
}
private CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false);
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ArgumentListType:
return type;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)type;
typeDst = SubstTypeCore(typeSrc = mod.GetParameterType(), pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.isOut);
case TypeKind.TK_ArrayType:
var arr = (ArrayType)type;
typeDst = SubstTypeCore(typeSrc = arr.GetElementType(), pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.rank, arr.IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = ((PointerType)type).GetReferentType(), pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = ((NullableType)type).GetUnderlyingType(), pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
AggregateType ats = (AggregateType)type;
if (ats.GetTypeArgsAll().Count > 0)
{
TypeArray typeArgs = SubstTypeArray(ats.GetTypeArgsAll(), pctx);
if (ats.GetTypeArgsAll() != typeArgs)
return GetAggregate(ats.getAggregate(), typeArgs);
}
return type;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx);
if (typeArgs != err.typeArgs)
{
return GetErrorType(err.nameText, typeArgs);
}
}
return type;
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = ((TypeParameterType)type).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
return type;
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.ctypeMeth)
{
Debug.Assert(pctx.prgtypeMeth != null);
return pctx.prgtypeMeth[index];
}
else
{
return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type);
}
}
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
return type;
return index < pctx.ctypeCls ? pctx.prgtypeCls[index] :
((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type);
}
}
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst)));
return true;
}
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return false;
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
ArrayType arrSrc = (ArrayType)typeSrc;
if (!(typeDst is ArrayType arrDst) || arrDst.rank != arrSrc.rank || arrDst.IsSZArray != arrSrc.IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (!(typeDst is ParameterModifierType modDest) ||
((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 &&
modDest.isOut != ((ParameterModifierType)typeSrc).isOut))
return false;
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.GetTypeKind() != typeSrc.GetTypeKind())
return false;
LCheckBases:
typeSrc = typeSrc.GetBaseOrParameterOrElementType();
typeDst = typeDst.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
if (!(typeDst is AggregateType atsDst))
return false;
{ // BLOCK
AggregateType atsSrc = (AggregateType)typeSrc;
if (atsSrc.getAggregate() != atsDst.getAggregate())
return false;
Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count);
// All the args must unify.
for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++)
{
if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_ErrorType:
ErrorType errSrc = (ErrorType)typeSrc;
if (!(typeDst is ErrorType errDst) || !errSrc.HasParent || !errDst.HasParent)
return false;
{
Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null);
Debug.Assert(errDst.nameText != null && errDst.typeArgs != null);
if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count
|| errSrc.HasParent != errDst.HasParent)
{
return false;
}
// All the args must unify.
for (int i = 0; i < errSrc.typeArgs.Count; i++)
{
if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth);
if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null)
{
return typeDst == pctx.prgtypeMeth[index];
}
if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0)
{
return typeDst == GetStdMethTypeVar(index);
}
}
else
{
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls);
if (index < pctx.ctypeCls)
return typeDst == pctx.prgtypeCls[index];
if ((pctx.grfst & SubstTypeFlags.NormClass) != 0)
return typeDst == GetStdClsTypeVar(index);
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsType(err.typeArgs[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsTyVars(err.typeArgs[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = ((TypeParameterType)type).GetIndexInTotalParameters();
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind)
{
Debug.Assert(@params != null);
Debug.Assert(typeFind != null);
for (int p = 0; p < @params.Count; p++)
{
CType sym = @params[p];
if (TypeContainsType(sym, typeFind))
{
return true;
}
}
return false;
}
public AggregateSymbol GetPredefAgg(PredefinedType pt) => _predefTypes.GetPredefinedAggregate(pt);
public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2)
{
return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2);
}
public TypeArray GetStdMethTyVarArray(int cTyVars)
{
TypeParameterType[] prgvar = new TypeParameterType[cTyVars];
for (int ivar = 0; ivar < cTyVars; ivar++)
{
prgvar[ivar] = GetStdMethTypeVar(ivar);
}
return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar);
}
public CType SubstType(CType typeSrc, SubstContext pctx)
{
return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx);
}
public CType SubstType(CType typeSrc, AggregateType atsCls)
{
return SubstType(typeSrc, atsCls, (TypeArray)null);
}
public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls)
{
return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null);
}
private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth, SubstTypeFlags.NormNone);
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls)
{
return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null);
}
//public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
//{
// return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone);
//}
public TypeParameterType GetStdMethTypeVar(int iv)
{
return _stvcMethod.GetTypeVarSym(iv, this, true);
}
private TypeParameterType GetStdClsTypeVar(int iv)
{
return _stvcClass.GetTypeVarSym(iv, this, false);
}
public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
// These guys should be singletons for each.
TypeParameterType pTypeParameter = _typeTable.LookupTypeParameter(pSymbol);
if (pTypeParameter == null)
{
pTypeParameter = _typeFactory.CreateTypeParameter(pSymbol);
_typeTable.InsertTypeParameter(pSymbol, pTypeParameter);
}
return pTypeParameter;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(semanticChecker != null);
Debug.Assert(bindingContext != null);
Debug.Assert(typeSrc != null);
typeDst = null;
if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup))
{
// If we already have an accessible type, then use it. This is the terminal point of the recursion.
typeDst = typeSrc;
return true;
}
// These guys have no accessibility concerns.
Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is ErrorType) && !(typeSrc is TypeParameterType));
if (typeSrc is ParameterModifierType || typeSrc is PointerType)
{
// We cannot vary these.
return false;
}
CType intermediateType;
if (typeSrc is AggregateType aggSrc && (aggSrc.isInterfaceType() || aggSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, aggSrc, out intermediateType))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType arrSrc && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, arrSrc, out intermediateType))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is NullableType)
{
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
typeDst = GetPredefAgg(PredefinedType.PT_VALUE).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType)
{
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
typeDst = GetPredefAgg(PredefinedType.PT_ARRAY).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
Debug.Assert(typeSrc is AggregateType);
if (typeSrc is AggregateType aggType)
{
// We have an AggregateType, so recurse on its base class.
AggregateType baseType = aggType.GetBaseClass();
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and so we will use it.
baseType = GetPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst);
}
return false;
}
private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType());
typeDst = null;
AggregateSymbol aggSym = typeSrc.GetOwningAggregate();
AggregateType aggOpenType = aggSym.getThisType();
if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.GetTypeArgsThis();
TypeArray typeParams = aggOpenType.GetTypeArgsThis();
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < typeArgs.Count; i++)
{
if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArgs[i];
continue;
}
if (!typeArgs[i].IsRefType() || !((TypeParameterType)typeParams[i]).Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
CType intermediateTypeArg;
if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg))
{
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
newTypeArgsTemp[i] = intermediateTypeArg;
continue;
}
else
{
Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter");
return false;
}
}
TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp);
CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
typeDst = null;
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.GetElementType();
if (!elementType.IsRefType())
{
// Covariant array conversions exist for reference types only.
return false;
}
CType intermediateType;
if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType))
{
typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray);
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
return false;
}
public AggregateType ObjectAggregateType => (AggregateType)_symbolTable.GetCTypeFromType(typeof(object));
private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated
= new Dictionary<Tuple<Assembly, Assembly>, bool>();
internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
bool result;
var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck);
if (!_internalsVisibleToCalculated.TryGetValue(key, out result))
{
AssemblyName assyName = null;
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
assyName = assemblyToCheck.GetName();
}
catch (System.Security.SecurityException)
{
result = false;
goto SetMemo;
}
result = assemblyThatDefinesAttribute.GetCustomAttributes()
.OfType<InternalsVisibleToAttribute>()
.Select(ivta => new AssemblyName(ivta.AssemblyName))
.Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName));
SetMemo:
_internalsVisibleToCalculated[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Hosting
{
public static class WebHostBuilderExtensions
{
private static readonly string ServerUrlsSeparator = ";";
/// <summary>
/// Use the given configuration settings on the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="configuration">The <see cref="IConfiguration"/> containing settings to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseConfiguration(this IWebHostBuilder hostBuilder, IConfiguration configuration)
{
foreach (var setting in configuration.AsEnumerable())
{
hostBuilder.UseSetting(setting.Key, setting.Value);
}
return hostBuilder;
}
/// <summary>
/// Set whether startup errors should be captured in the configuration settings of the web host.
/// When enabled, startup exceptions will be caught and an error page will be returned. If disabled, startup exceptions will be propagated.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="captureStartupErrors"><c>true</c> to use startup error page; otherwise <c>false</c>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder CaptureStartupErrors(this IWebHostBuilder hostBuilder, bool captureStartupErrors)
{
return hostBuilder.UseSetting(WebHostDefaults.CaptureStartupErrorsKey, captureStartupErrors ? "true" : "false");
}
/// <summary>
/// Specify the startup method to be used to configure the web application.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="configureApp">The delegate that configures the <see cref="IApplicationBuilder"/>.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder Configure(this IWebHostBuilder hostBuilder, Action<IApplicationBuilder> configureApp)
{
if (configureApp == null)
{
throw new ArgumentNullException(nameof(configureApp));
}
var startupAssemblyName = configureApp.GetMethodInfo().DeclaringType.GetTypeInfo().Assembly.GetName().Name;
return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
.ConfigureServices(services =>
{
services.AddSingleton<IStartup>(new DelegateStartup(configureApp));
});
}
/// <summary>
/// Specify the startup type to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="startupType">The <see cref="Type"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType)
{
var startupAssemblyName = startupType.GetTypeInfo().Assembly.GetName().Name;
return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
.ConfigureServices(services =>
{
if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
{
services.AddSingleton(typeof(IStartup), startupType);
}
else
{
services.AddSingleton(typeof(IStartup), sp =>
{
var hostingEnvironment = sp.GetRequiredService<IHostingEnvironment>();
return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName));
});
}
});
}
/// <summary>
/// Specify the startup type to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseStartup<TStartup>(this IWebHostBuilder hostBuilder) where TStartup : class
{
return hostBuilder.UseStartup(typeof(TStartup));
}
/// <summary>
/// Specify the assembly containing the startup type to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="startupAssemblyName">The name of the assembly containing the startup type.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, string startupAssemblyName)
{
if (startupAssemblyName == null)
{
throw new ArgumentNullException(nameof(startupAssemblyName));
}
return hostBuilder
.UseSetting(WebHostDefaults.ApplicationKey, startupAssemblyName)
.UseSetting(WebHostDefaults.StartupAssemblyKey, startupAssemblyName);
}
/// <summary>
/// Specify the assembly containing the server to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="assemblyName">The name of the assembly containing the server to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, string assemblyName)
{
if (assemblyName == null)
{
throw new ArgumentNullException(nameof(assemblyName));
}
return hostBuilder.UseSetting(WebHostDefaults.ServerKey, assemblyName);
}
/// <summary>
/// Specify the server to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="server">The <see cref="IServer"/> to be used.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseServer(this IWebHostBuilder hostBuilder, IServer server)
{
if (server == null)
{
throw new ArgumentNullException(nameof(server));
}
return hostBuilder.ConfigureServices(services =>
{
// It would be nicer if this was transient but we need to pass in the
// factory instance directly
services.AddSingleton(server);
});
}
/// <summary>
/// Specify the environment to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="environment">The environment to host the application in.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseEnvironment(this IWebHostBuilder hostBuilder, string environment)
{
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
return hostBuilder.UseSetting(WebHostDefaults.EnvironmentKey, environment);
}
/// <summary>
/// Specify the content root directory to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="contentRoot">Path to root directory of the application.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot)
{
if (contentRoot == null)
{
throw new ArgumentNullException(nameof(contentRoot));
}
return hostBuilder.UseSetting(WebHostDefaults.ContentRootKey, contentRoot);
}
/// <summary>
/// Specify the webroot directory to be used by the web host.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="webRoot">Path to the root directory used by the web server.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseWebRoot(this IWebHostBuilder hostBuilder, string webRoot)
{
if (webRoot == null)
{
throw new ArgumentNullException(nameof(webRoot));
}
return hostBuilder.UseSetting(WebHostDefaults.WebRootKey, webRoot);
}
/// <summary>
/// Specify the urls the web host will listen on.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
/// <param name="urls">The urls the hosted application will listen on.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHostBuilder UseUrls(this IWebHostBuilder hostBuilder, params string[] urls)
{
if (urls == null)
{
throw new ArgumentNullException(nameof(urls));
}
return hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, string.Join(ServerUrlsSeparator, urls));
}
/// <summary>
/// Start the web host and listen on the speficied urls.
/// </summary>
/// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to start.</param>
/// <param name="urls">The urls the hosted application will listen on.</param>
/// <returns>The <see cref="IWebHostBuilder"/>.</returns>
public static IWebHost Start(this IWebHostBuilder hostBuilder, params string[] urls)
{
var host = hostBuilder.UseUrls(urls).Build();
host.Start();
return host;
}
}
}
| |
/*
* Copyright (C) Sony Computer Entertainment America LLC.
* All Rights Reserved.
*/
using System;
using System.Drawing;
using System.Net;
using System.Windows.Forms;
using System.Xml;
using Sce.Sled.Shared.Services;
namespace Sce.Sled.Shared.Plugin
{
/// <summary>
/// Delegate representing a connection to a target event
/// </summary>
/// <param name="sender">Object that triggered the event</param>
/// <param name="target">ISledTarget of event</param>
public delegate void ConnectionHandler(object sender, ISledTarget target);
/// <summary>
/// Delegate representing data received from the target
/// </summary>
/// <param name="sender">Object that triggered the event</param>
/// <param name="buffer">Data received</param>
public delegate void DataReadyHandler(object sender, byte[] buffer);
/// <summary>
/// Delegate representing an unhandled exception event
/// </summary>
/// <param name="sender">Object that triggered the event</param>
/// <param name="ex">Unhandled Exception</param>
public delegate void UnHandledExceptionHandler(object sender, Exception ex);
/// <summary>
/// Base network plugin interface for SLED
/// <remarks>Derived from IDisposable, so a Dispose() method is needed as well that
/// gets called by SLED after disconnecting from a target or if an unhandled
/// exception event is triggered and received by SLED.</remarks>
/// </summary>
public interface ISledNetworkPlugin : IDisposable, ISledNetworkPluginPersistedSettings
{
/// <summary>
/// Make a connection to a target
/// <remarks>Upon successful connection to a target, the
/// ConnectedEvent event should be triggered, or if an error
/// occurs, the UnHandledExceptionEvent should be triggered.</remarks>
/// </summary>
/// <param name="target">ISledTarget</param>
void Connect(ISledTarget target);
/// <summary>
/// Get whether or not the plugin is connected to a target
/// <remarks>This property should not lock or rely on locking mechanisms, because it
/// is used frequently when the status of GUI elements is updated to reflect
/// the connection state.</remarks>
/// </summary>
bool IsConnected
{
get;
}
/// <summary>
/// Disconnect from the target
/// <remarks>This method should trigger the DisconnectedEvent after successful
/// disconnection or trigger the UnHandledExceptionEvent if an error occurs
/// while trying to disconnect.</remarks>
/// </summary>
void Disconnect();
/// <summary>
/// Send data to the target
/// </summary>
/// <param name="buffer">Data to send</param>
/// <returns>Length of data sent or -1 if failure</returns>
int Send(byte[] buffer);
/// <summary>
/// Send data to the target
/// <remarks>Allow specification of length of buffer</remarks>
/// </summary>
/// <param name="buffer">Data to send</param>
/// <param name="length">Length of data to send</param>
/// <returns>Length of data sent or -1 if failure</returns>
int Send(byte[] buffer, int length);
/// <summary>
/// Event to trigger after connecting to a target
/// </summary>
event ConnectionHandler ConnectedEvent;
/// <summary>
/// Event to trigger after disconnecting from a target
/// </summary>
event ConnectionHandler DisconnectedEvent;
/// <summary>
/// Event to trigger when data has been received from the target
/// </summary>
event DataReadyHandler DataReadyEvent;
/// <summary>
/// Event to trigger when an unhandled exception has occurred
/// </summary>
event UnHandledExceptionHandler UnHandledExceptionEvent;
/// <summary>
/// Get name of plugin
/// <remarks>Name can be any string</remarks>
/// </summary>
string Name
{
get;
}
/// <summary>
/// Get protocol that plugin uses
/// <remarks>This should be a simple string, such as "TCP", etc.</remarks>
/// </summary>
string Protocol
{
get;
}
/// <summary>
/// Create a settings control based on a specific target
/// </summary>
/// <param name="target">Target to build settings from or null if no target created yet</param>
/// <returns>Settings control</returns>
SledNetworkPluginTargetFormSettings CreateSettingsControl(ISledTarget target);
/// <summary>
/// Create and set up a new target
/// </summary>
/// <param name="name">Name of the target</param>
/// <param name="endPoint">IP address and port of the target</param>
/// <param name="settings">Optional settings to pass in</param>
/// <returns>New target or null if an error occurred</returns>
ISledTarget CreateAndSetup(string name, IPEndPoint endPoint, params object[] settings);
/// <summary>
/// Get an array of any automatically generated targets
/// <remarks>Some network plugins may be able to notify SLED of targets
/// based on outside software.</remarks>
/// </summary>
ISledTarget[] ImportedTargets { get; }
/// <summary>
/// Get unique identifier for the network plugin
/// </summary>
Guid PluginGuid { get; }
}
/// <summary>
/// Interface for SLED network plugin persisted settings
/// </summary>
public interface ISledNetworkPluginPersistedSettings
{
/// <summary>
/// Write a target to an XmlElement
/// </summary>
/// <param name="target">Target being saved</param>
/// <param name="elem">XmlElement to write data to</param>
/// <returns>True iff successful</returns>
bool Save(ISledTarget target, XmlElement elem);
/// <summary>
/// Read a target from an XmlElement
/// </summary>
/// <param name="target">Target to fill in from the XmlElement</param>
/// <param name="elem">XmlElement to read from</param>
/// <returns>True iff successful</returns>
bool Load(out ISledTarget target, XmlElement elem);
}
/// <summary>
/// Interface for SLED network plugin target form customizer
/// </summary>
public interface ISledNetworkPluginTargetFormCustomizer
{
/// <summary>
/// Get whether the protocol displays in the protocol combo box
/// </summary>
bool AllowProtocolOption { get; }
}
/// <summary>
/// SLED network targets form render arguments class
/// </summary>
public class SledNetworkTargetsFormRenderArgs
{
/// <summary>
/// Constructor with parameters
/// </summary>
/// <param name="gfx">GDI+ drawing surface</param>
/// <param name="bounds">Bounding rectangle for drawing</param>
/// <param name="font">Font</param>
/// <param name="selected">Whether item selected</param>
/// <param name="item">ISledTarget item being rendered</param>
/// <param name="textColor">Text color</param>
/// <param name="highlightTextColor">Highlight text color</param>
/// <param name="highlightBackColor">Highlight background color</param>
public SledNetworkTargetsFormRenderArgs(Graphics gfx, Rectangle bounds, Font font, bool selected, ISledTarget item, Color textColor, Color highlightTextColor, Color highlightBackColor)
{
Graphics = gfx;
Bounds = bounds;
Font = font;
Selected = selected;
Item = item;
DrawDefault = false;
TextColor = textColor;
HighlightTextColor = highlightTextColor;
HighlightBackColor = highlightBackColor;
}
/// <summary>
/// Get Graphics device (GDI+ drawing surface)
/// </summary>
public Graphics Graphics { get; private set; }
/// <summary>
/// Get bounds
/// </summary>
public Rectangle Bounds { get; private set; }
/// <summary>
/// Get font
/// </summary>
public Font Font { get; private set; }
/// <summary>
/// Get whether the item is selected or not
/// </summary>
public bool Selected { get; private set; }
/// <summary>
/// Get the ISledTarget item being rendered
/// </summary>
public ISledTarget Item { get; private set; }
/// <summary>
/// Get or set whether normal drawing should take place
/// </summary>
public bool DrawDefault { get; set; }
/// <summary>
/// Get or set the text color
/// </summary>
public Color TextColor { get; set; }
/// <summary>
/// Get or set the highlight text color
/// </summary>
public Color HighlightTextColor { get; set; }
/// <summary>
/// Get or set the highlight background color
/// </summary>
public Color HighlightBackColor { get; set; }
}
/// <summary>
/// SLED network targets form renderer interface
/// </summary>
public interface ISledNetworkTargetsFormRenderer
{
/// <summary>
/// Draw the name of the target
/// </summary>
/// <param name="e">Render arguments</param>
void DrawName(SledNetworkTargetsFormRenderArgs e);
/// <summary>
/// Draw the IP address
/// </summary>
/// <param name="e">Render arguments</param>
void DrawHost(SledNetworkTargetsFormRenderArgs e);
/// <summary>
/// Draw the port
/// </summary>
/// <param name="e">Render arguments</param>
void DrawPort(SledNetworkTargetsFormRenderArgs e);
}
/// <summary>
/// A custom settings control that fits into the SledTargetForm form when adding a new
/// or editing an existing target
/// </summary>
public abstract class SledNetworkPluginTargetFormSettings : UserControl
{
/// <summary>
/// Determine whether the current settings are valid or not
/// </summary>
/// <param name="errorMsg">Error message to display if there is an error</param>
/// <param name="errorControl">Control to focus on if there is an error</param>
/// <returns>True iff settings contain errors</returns>
public abstract bool ContainsErrors(out string errorMsg, out Control errorControl);
/// <summary>
/// Get a BLOB of data that contains the additional (with respect to ISledTarget) settings
/// </summary>
/// <returns>A BLOB of all additional settings</returns>
public abstract object[] GetDataBlob();
/// <summary>
/// Get the protocol's default port number
/// </summary>
public abstract int DefaultPort { get; }
}
}
| |
using DFHack;
using System.Collections.Generic;
using UnityEngine;
using RemoteFortressReader;
public class MapBlock : MonoBehaviour
{
public const int blockWidthTiles = 16;
public const int blockAreaTiles = blockWidthTiles * blockWidthTiles;
public static float tileHeight = 3.0f;
public static float tileWidth = 2.0f;
public static float blockWidth
{
get { return tileWidth * 16; }
}
public static float BlockHeight
{
get { return tileHeight; }
}
public static float floorHeight = 0.5f;
public static float rampDistance = 2.0f*tileWidth;
public string coordString
{
get { return coordinates.x + "," + coordinates.y + "," + coordinates.z; }
}
DFCoord coordinates;
DFCoord2d map_coords;
public GameMap parent;
public static Vector3 DFtoUnityCoord(int x, int y, int z)
{
Vector3 outCoord = new Vector3(x * tileWidth, z * tileHeight, y * (-tileWidth));
return outCoord;
}
[SerializeField]
TiletypeShape[] terrain = new TiletypeShape[blockAreaTiles];
[SerializeField]
Color32[] colors = new Color32[blockAreaTiles];
//CombineInstance[] instances = new CombineInstance[blockAreaTiles];
//bool propogatedTransforms = false;
List<Vector3> finalVertices = new List<Vector3>();
List<int> finalFaces = new List<int>();
List<Color32> finalVertexColors = new List<Color32>();
List<Vector2> finalUVs = new List<Vector2>();
public enum Openness
{
air,
mixed,
stone
}
Openness openness;
// Use this for initialization
void Start()
{
}
public void SetOpenness()
{
int air = 0;
int solid = 0;
for (int x = 0; x < blockWidthTiles; x++)
for (int y = 0; y < blockWidthTiles; y++)
{
if (terrain[y * blockWidthTiles + x] == TiletypeShape.EMPTY || terrain[y * blockWidthTiles + x] == TiletypeShape.NO_SHAPE)
air++;
else if (terrain[y * blockWidthTiles + x] == TiletypeShape.WALL)
solid++;
}
if (air == blockAreaTiles)
openness = Openness.air;
else if (solid == blockAreaTiles)
openness = Openness.stone;
else openness = Openness.mixed;
}
public void Reposition(RemoteFortressReader.BlockList input)
{
int diff_x = input.map_x - map_coords.x;
int diff_y = input.map_y - map_coords.y;
coordinates.x += (diff_x * 3);
coordinates.y += (diff_y * 3);
map_coords.x = input.map_x;
map_coords.y = input.map_y;
SetUnityPosition();
}
public void SetUnityPosition()
{
transform.position = DFtoUnityCoord(coordinates.x, coordinates.y, coordinates.z);
}
public Openness GetOpenness()
{
return openness;
}
public Color32 GetColor(DFCoord2d position)
{
if ((position.x + position.y * blockWidthTiles) < colors.Length)
return colors[position.x + position.y * blockWidthTiles];
else return Color.white;
}
public void SetColor(DFCoord2d position, Color32 input)
{
if ((position.x + position.y * blockWidthTiles) < colors.Length)
colors[position.x + position.y * blockWidthTiles] = input;
}
public void SetSingleTile(DFCoord2d position, TiletypeShape tile)
{
terrain[position.x + position.y * blockWidthTiles] = tile;
SetOpenness();
}
public void SetAllTiles(TiletypeShape tile)
{
for(int i = 0; i < terrain.GetLength(0);i++)
{
terrain[i] = tile;
}
SetOpenness();
}
public void SetAllTiles(RemoteFortressReader.MapBlock DFBlock, RemoteFortressReader.BlockList blockList, RemoteFortressReader.TiletypeList tiletypeList)
{
if (DFBlock.tiles.Count != terrain.Length)
{
Debug.LogError("Map Block has " + DFBlock.tiles.Count + " tiles, should be " + terrain.Length);
}
for (int i = 0; i < DFBlock.tiles.Count; i++)
{
terrain[i] = tiletypeList.tiletype_list[DFBlock.tiles[i]].shape;
colors[i] = Color.white;
}
SetOpenness();
coordinates.x = DFBlock.map_x;
coordinates.y = DFBlock.map_y;
coordinates.z = DFBlock.map_z;
map_coords.x = blockList.map_x;
map_coords.y = blockList.map_y;
SetUnityPosition();
}
public TiletypeShape GetSingleTile(DFCoord2d position)
{
if (position.x >= 0 && position.x < blockWidthTiles && position.y >= 0 && position.y < blockWidthTiles)
return terrain[position.x + position.y * blockWidthTiles];
else
return TiletypeShape.EMPTY;
}
public void Regenerate()
{
//if (openness == Openness.air)
//{
//}
//else
//{
// for (int i = 0; i < blockAreaTiles; i++)
// {
// int yy = i / blockWidthTiles;
// int xx = i % blockWidthTiles;
// int terraintype = (int)terrain[i];
// //this is very very temporary
// if (parent.defaultMeshes[terraintype] == null)
// parent.defaultMeshes[terraintype] = new Mesh();
// instances[i].mesh = parent.defaultMeshes[terraintype];
// instances[i].transform = Matrix4x4.TRS(new Vector3(xx * tileWidth, 0, -yy * tileWidth), Quaternion.identity, Vector3.one);
// }
// MeshFilter mf = GetComponent<MeshFilter>();
// if (mf.mesh == null)
// mf.mesh = new Mesh();
// mf.mesh.Clear();
// mf.mesh.CombineMeshes(instances, true);
//}
}
//public void Regenerate()
//{
// finalVertices.Clear();
// finalFaces.Clear();
// finalVertexColors.Clear();
// finalUVs.Clear();
// if (openness == Openness.air)
// {
// }
// else
// {
// for (int i = 0; i < blockWidthTiles; i++)
// for (int j = 0; j < blockWidthTiles; j++)
// {
// DFCoord2d here = new DFCoord2d(i, j);
// switch (GetSingleTile(here))
// {
// case TiletypeShape.WALL:
// AddTopFace(here, tileHeight);
// break;
// case TiletypeShape.RAMP:
// case TiletypeShape.FLOOR:
// AddTopFace(here, floorHeight);
// break;
// }
// AddSideFace(here, FaceDirection.North);
// AddSideFace(here, FaceDirection.South);
// AddSideFace(here, FaceDirection.East);
// AddSideFace(here, FaceDirection.West);
// }
// }
// MeshFilter mf = GetComponent<MeshFilter>();
// Mesh mesh = new Mesh();
// mf.mesh = mesh;
// mesh.vertices = finalVertices.ToArray();
// mesh.uv = finalUVs.ToArray();
// mesh.colors32 = finalVertexColors.ToArray();
// mesh.triangles = finalFaces.ToArray();
// mesh.RecalculateBounds();
// mesh.RecalculateNormals();
//}
enum FaceDirection
{
Up,
Down,
North,
South,
East,
West
}
TiletypeShape GetRelativeTile(DFCoord2d position, FaceDirection direction)
{
DFCoord2d relativePosition = new DFCoord2d(position.x, position.y);
switch (direction)
{
case FaceDirection.North:
relativePosition.y--;
break;
case FaceDirection.South:
relativePosition.y++;
break;
case FaceDirection.East:
relativePosition.x++;
break;
case FaceDirection.West:
relativePosition.x--;
break;
}
return GetSingleTile(relativePosition);
}
enum Layer
{
Base,
Floor,
Top
}
float convertDistanceToOffset(float input)
{
if (input == float.MaxValue)
return 0;
input = Mathf.Pow(input, 0.5f);
input = (rampDistance - input) / rampDistance;
if (input < 0)
return 0;
return Mathf.Sin(input * Mathf.PI / 4.0f) * tileHeight;
}
Vector3 AdjustForRamps(Vector3 input, Layer layer = Layer.Floor)
{
return input;
}
void AddSideFace(DFCoord2d position, FaceDirection direction)
{
Layer topLayer = Layer.Top;
Layer bottomLayer = Layer.Base;
float currentFloorHeight = -0.5f * tileHeight;
float adjacentFloorHeight = -0.5f * tileHeight;
switch (GetSingleTile(position))
{
case TiletypeShape.WALL:
currentFloorHeight = 0.5f * tileHeight;
topLayer = Layer.Top;
break;
case TiletypeShape.RAMP:
case TiletypeShape.FLOOR:
currentFloorHeight = floorHeight - (0.5f * tileHeight);
topLayer = Layer.Floor;
break;
default:
break;
}
switch (GetRelativeTile(position, direction))
{
case TiletypeShape.WALL:
adjacentFloorHeight = 0.5f * tileHeight;
bottomLayer = Layer.Top;
break;
case TiletypeShape.FLOOR:
adjacentFloorHeight = floorHeight - (0.5f * tileHeight);
bottomLayer = Layer.Floor;
break;
default:
break;
}
if (currentFloorHeight <= adjacentFloorHeight)
return;
int startindex = finalVertices.Count;
int uvPos = 0;
switch (direction)
{
case FaceDirection.North:
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, currentFloorHeight, -(position.y - 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, currentFloorHeight, -(position.y - 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, adjacentFloorHeight, -(position.y - 0.5f) * tileWidth), bottomLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, adjacentFloorHeight, -(position.y - 0.5f) * tileWidth), bottomLayer));
uvPos = position.x;
break;
case FaceDirection.South:
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, currentFloorHeight, -(position.y + 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, currentFloorHeight, -(position.y + 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, adjacentFloorHeight, -(position.y + 0.5f) * tileWidth), bottomLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, adjacentFloorHeight, -(position.y + 0.5f) * tileWidth), bottomLayer));
uvPos = 16 - position.x;
break;
case FaceDirection.East:
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, currentFloorHeight, -(position.y + 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, currentFloorHeight, -(position.y - 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, adjacentFloorHeight, -(position.y + 0.5f) * tileWidth), bottomLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, adjacentFloorHeight, -(position.y - 0.5f) * tileWidth), bottomLayer));
uvPos = position.y;
break;
case FaceDirection.West:
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, currentFloorHeight, -(position.y - 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, currentFloorHeight, -(position.y + 0.5f) * tileWidth), topLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, adjacentFloorHeight, -(position.y - 0.5f) * tileWidth), bottomLayer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, adjacentFloorHeight, -(position.y + 0.5f) * tileWidth), bottomLayer));
uvPos = 16 - position.y;
break;
default:
break;
}
finalUVs.Add(new Vector2(-(float)(uvPos + 1) / 16.0f, -(float)(0) / 16.0f));
finalUVs.Add(new Vector2(-(float)(uvPos) / 16.0f, -(float)(0) / 16.0f));
finalUVs.Add(new Vector2(-(float)(uvPos + 1) / 16.0f, -(float)(0 + 1) / 16.0f));
finalUVs.Add(new Vector2(-(float)(uvPos) / 16.0f, -(float)(0 + 1) / 16.0f));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalFaces.Add(startindex);
finalFaces.Add(startindex + 1);
finalFaces.Add(startindex + 2);
finalFaces.Add(startindex + 1);
finalFaces.Add(startindex + 3);
finalFaces.Add(startindex + 2);
}
void AddTopFace(DFCoord2d position, float height)
{
Layer layer = Layer.Base;
if (GetSingleTile(position) == TiletypeShape.FLOOR)
layer = Layer.Floor;
else if (GetSingleTile(position) == TiletypeShape.WALL)
layer = Layer.Top;
height -= 0.5f * tileHeight;
//Todo: Weld vertices that should be welded
//On second though, not with vertex colors there.
int startindex = finalVertices.Count;
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, height, -(position.y - 0.5f) * tileWidth), layer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, height, -(position.y - 0.5f) * tileWidth), layer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x - 0.5f) * tileWidth, height, -(position.y + 0.5f) * tileWidth), layer));
finalVertices.Add(AdjustForRamps(new Vector3((position.x + 0.5f) * tileWidth, height, -(position.y + 0.5f) * tileWidth), layer));
finalUVs.Add(new Vector2((float)(position.x) / 16.0f, -(float)(position.y) / 16.0f));
finalUVs.Add(new Vector2((float)(position.x + 1) / 16.0f, -(float)(position.y) / 16.0f));
finalUVs.Add(new Vector2((float)(position.x) / 16.0f, -(float)(position.y + 1) / 16.0f));
finalUVs.Add(new Vector2((float)(position.x + 1) / 16.0f, -(float)(position.y + 1) / 16.0f));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalVertexColors.Add(GetColor(position));
finalFaces.Add(startindex);
finalFaces.Add(startindex + 1);
finalFaces.Add(startindex + 2);
finalFaces.Add(startindex + 1);
finalFaces.Add(startindex + 3);
finalFaces.Add(startindex + 2);
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
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;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
namespace Achordeon.Annotations
{
/// <summary>
/// Indicates that the value of the marked element could be <c>null</c> sometimes,
/// so the check for <c>null</c> is necessary before its usage.
/// </summary>
/// <example><code>
/// [CanBeNull] public object Test() { return null; }
/// public void UseTest() {
/// var p = Test();
/// var s = p.ToString(); // Warning: Possible 'System.NullReferenceException'
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class CanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the value of the marked element could never be <c>null</c>.
/// </summary>
/// <example><code>
/// [NotNull] public object Foo() {
/// return null; // Warning: Possible 'null' assignment
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field | AttributeTargets.Event)]
public sealed class NotNullAttribute : Attribute { }
/// <summary>
/// Indicates that collection or enumerable value does not contain null elements.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemNotNullAttribute : Attribute { }
/// <summary>
/// Indicates that collection or enumerable value can contain null elements.
/// </summary>
[AttributeUsage(
AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Property |
AttributeTargets.Delegate | AttributeTargets.Field)]
public sealed class ItemCanBeNullAttribute : Attribute { }
/// <summary>
/// Indicates that the marked method builds string by format pattern and (optional) arguments.
/// Parameter, which contains format string, should be given in constructor. The format string
/// should be in <see cref="string.Format(IFormatProvider,string,object[])"/>-like form.
/// </summary>
/// <example><code>
/// [StringFormatMethod("message")]
/// public void ShowError(string message, params object[] args) { /* do something */ }
/// public void Foo() {
/// ShowError("Failed: {0}"); // Warning: Non-existing argument in format string
/// }
/// </code></example>
[AttributeUsage(
AttributeTargets.Constructor | AttributeTargets.Method |
AttributeTargets.Property | AttributeTargets.Delegate)]
public sealed class StringFormatMethodAttribute : Attribute
{
/// <param name="formatParameterName">
/// Specifies which parameter of an annotated method should be treated as format-string
/// </param>
public StringFormatMethodAttribute(string formatParameterName)
{
FormatParameterName = formatParameterName;
}
public string FormatParameterName { get; private set; }
}
/// <summary>
/// For a parameter that is expected to be one of the limited set of values.
/// Specify fields of which type should be used as values for this parameter.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class ValueProviderAttribute : Attribute
{
public ValueProviderAttribute(string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// public void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Indicates that the method is contained in a type that implements
/// <c>System.ComponentModel.INotifyPropertyChanged</c> interface and this method
/// is used to notify that some property value changed.
/// </summary>
/// <remarks>
/// The method should be non-static and conform to one of the supported signatures:
/// <list>
/// <item><c>NotifyChanged(string)</c></item>
/// <item><c>NotifyChanged(params string[])</c></item>
/// <item><c>NotifyChanged{T}(Expression{Func{T}})</c></item>
/// <item><c>NotifyChanged{T,U}(Expression{Func{T,U}})</c></item>
/// <item><c>SetProperty{T}(ref T, T, string)</c></item>
/// </list>
/// </remarks>
/// <example><code>
/// public class Foo : INotifyPropertyChanged {
/// public event PropertyChangedEventHandler PropertyChanged;
/// [NotifyPropertyChangedInvocator]
/// protected virtual void NotifyChanged(string propertyName) { ... }
///
/// private string _name;
/// public string Name {
/// get { return _name; }
/// set { _name = value; NotifyChanged("LastName"); /* Warning */ }
/// }
/// }
/// </code>
/// Examples of generated notifications:
/// <list>
/// <item><c>NotifyChanged("Property")</c></item>
/// <item><c>NotifyChanged(() => Property)</c></item>
/// <item><c>NotifyChanged((VM x) => x.Property)</c></item>
/// <item><c>SetProperty(ref myField, value, "Property")</c></item>
/// </list>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute
{
public NotifyPropertyChangedInvocatorAttribute() { }
public NotifyPropertyChangedInvocatorAttribute(string parameterName)
{
ParameterName = parameterName;
}
public string ParameterName { get; private set; }
}
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same)
/// for method output means that the methos doesn't return normally.<br/>
/// <c>canbenull</c> annotation is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row,
/// or use single attribute with rows separated by semicolon.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null=>false; =>true,result:notnull; =>false, result:null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Indicates that marked element should be localized or not.
/// </summary>
/// <example><code>
/// [LocalizationRequiredAttribute(true)]
/// public class Foo {
/// private string str = "my string"; // Warning: Localizable string
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.All)]
public sealed class LocalizationRequiredAttribute : Attribute
{
public LocalizationRequiredAttribute() : this(true) { }
public LocalizationRequiredAttribute(bool required)
{
Required = required;
}
public bool Required { get; private set; }
}
/// <summary>
/// Indicates that the value of the marked type (or its derivatives)
/// cannot be compared using '==' or '!=' operators and <c>Equals()</c>
/// should be used instead. However, using '==' or '!=' for comparison
/// with <c>null</c> is always permitted.
/// </summary>
/// <example><code>
/// [CannotApplyEqualityOperator]
/// class NoEquality { }
/// class UsesNoEquality {
/// public void Test() {
/// var ca1 = new NoEquality();
/// var ca2 = new NoEquality();
/// if (ca1 != null) { // OK
/// bool condition = ca1 == ca2; // Warning
/// }
/// }
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct)]
public sealed class CannotApplyEqualityOperatorAttribute : Attribute { }
/// <summary>
/// When applied to a target attribute, specifies a requirement for any type marked
/// with the target attribute to implement or inherit specific type or types.
/// </summary>
/// <example><code>
/// [BaseTypeRequired(typeof(IComponent)] // Specify requirement
/// public class ComponentAttribute : Attribute { }
/// [Component] // ComponentAttribute requires implementing IComponent interface
/// public class MyComponent : IComponent { }
/// </code></example>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[BaseTypeRequired(typeof(Attribute))]
public sealed class BaseTypeRequiredAttribute : Attribute
{
public BaseTypeRequiredAttribute([NotNull] Type baseType)
{
BaseType = baseType;
}
[NotNull] public Type BaseType { get; private set; }
}
/// <summary>
/// Indicates that the marked symbol is used implicitly (e.g. via reflection, in external library),
/// so this symbol will not be marked as unused (as well as by other usage inspections).
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public sealed class UsedImplicitlyAttribute : Attribute
{
public UsedImplicitlyAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
public ImplicitUseKindFlags UseKindFlags { get; private set; }
public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
/// <summary>
/// Should be used on attributes and causes ReSharper to not mark symbols marked with such attributes
/// as unused (as well as by other usage inspections)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.GenericParameter)]
public sealed class MeansImplicitUseAttribute : Attribute
{
public MeansImplicitUseAttribute()
: this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags)
: this(useKindFlags, ImplicitUseTargetFlags.Default) { }
public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags)
: this(ImplicitUseKindFlags.Default, targetFlags) { }
public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags)
{
UseKindFlags = useKindFlags;
TargetFlags = targetFlags;
}
[UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; private set; }
[UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; private set; }
}
[Flags]
public enum ImplicitUseKindFlags
{
Default = Access | Assign | InstantiatedWithFixedConstructorSignature,
/// <summary>Only entity marked with attribute considered used.</summary>
Access = 1,
/// <summary>Indicates implicit assignment to a member.</summary>
Assign = 2,
/// <summary>
/// Indicates implicit instantiation of a type with fixed constructor signature.
/// That means any unused constructor parameters won't be reported as such.
/// </summary>
InstantiatedWithFixedConstructorSignature = 4,
/// <summary>Indicates implicit instantiation of a type.</summary>
InstantiatedNoFixedConstructorSignature = 8,
}
/// <summary>
/// Specify what is considered used implicitly when marked
/// with <see cref="MeansImplicitUseAttribute"/> or <see cref="UsedImplicitlyAttribute"/>.
/// </summary>
[Flags]
public enum ImplicitUseTargetFlags
{
Default = Itself,
Itself = 1,
/// <summary>Members of entity marked with attribute are considered used.</summary>
Members = 2,
/// <summary>Entity marked with attribute and all its members considered used.</summary>
WithMembers = Itself | Members
}
/// <summary>
/// This attribute is intended to mark publicly available API
/// which should not be removed and so is treated as used.
/// </summary>
[MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)]
public sealed class PublicAPIAttribute : Attribute
{
public PublicAPIAttribute() { }
public PublicAPIAttribute([NotNull] string comment)
{
Comment = comment;
}
public string Comment { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class InstantHandleAttribute : Attribute { }
/// <summary>
/// Indicates that a method does not make any observable state changes.
/// The same as <c>System.Diagnostics.Contracts.PureAttribute</c>.
/// </summary>
/// <example><code>
/// [Pure] private int Multiply(int x, int y) { return x * y; }
/// public void Foo() {
/// const int a = 2, b = 2;
/// Multiply(a, b); // Waring: Return value of pure method is not used
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class PureAttribute : Attribute { }
/// <summary>
/// Indicates that a parameter is a path to a file or a folder within a web project.
/// Path can be relative or absolute, starting from web root (~).
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class PathReferenceAttribute : Attribute
{
public PathReferenceAttribute() { }
public PathReferenceAttribute([PathReference] string basePath)
{
BasePath = basePath;
}
public string BasePath { get; private set; }
}
/// <summary>
/// An extension method marked with this attribute is processed by ReSharper code completion
/// as a 'Source Template'. When extension method is completed over some expression, it's source code
/// is automatically expanded like a template at call site.
/// </summary>
/// <remarks>
/// Template method body can contain valid source code and/or special comments starting with '$'.
/// Text inside these comments is added as source code when the template is applied. Template parameters
/// can be used either as additional method parameters or as identifiers wrapped in two '$' signs.
/// Use the <see cref="MacroAttribute"/> attribute to specify macros for parameters.
/// </remarks>
/// <example>
/// In this example, the 'forEach' method is a source template available over all values
/// of enumerable types, producing ordinary C# 'foreach' statement and placing caret inside block:
/// <code>
/// [SourceTemplate]
/// public static void forEach<T>(this IEnumerable<T> xs) {
/// foreach (var x in xs) {
/// //$ $END$
/// }
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SourceTemplateAttribute : Attribute { }
/// <summary>
/// Allows specifying a macro for a parameter of a <see cref="SourceTemplateAttribute">source template</see>.
/// </summary>
/// <remarks>
/// You can apply the attribute on the whole method or on any of its additional parameters. The macro expression
/// is defined in the <see cref="MacroAttribute.Expression"/> property. When applied on a method, the target
/// template parameter is defined in the <see cref="MacroAttribute.Target"/> property. To apply the macro silently
/// for the parameter, set the <see cref="MacroAttribute.Editable"/> property value = -1.
/// </remarks>
/// <example>
/// Applying the attribute on a source template method:
/// <code>
/// [SourceTemplate, Macro(Target = "item", Expression = "suggestVariableName()")]
/// public static void forEach<T>(this IEnumerable<T> collection) {
/// foreach (var item in collection) {
/// //$ $END$
/// }
/// }
/// </code>
/// Applying the attribute on a template method parameter:
/// <code>
/// [SourceTemplate]
/// public static void something(this Entity x, [Macro(Expression = "guid()", Editable = -1)] string newguid) {
/// /*$ var $x$Id = "$newguid$" + x.ToString();
/// x.DoSomething($x$Id); */
/// }
/// </code>
/// </example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method, AllowMultiple = true)]
public sealed class MacroAttribute : Attribute
{
/// <summary>
/// Allows specifying a macro that will be executed for a <see cref="SourceTemplateAttribute">source template</see>
/// parameter when the template is expanded.
/// </summary>
public string Expression { get; set; }
/// <summary>
/// Allows specifying which occurrence of the target parameter becomes editable when the template is deployed.
/// </summary>
/// <remarks>
/// If the target parameter is used several times in the template, only one occurrence becomes editable;
/// other occurrences are changed synchronously. To specify the zero-based index of the editable occurrence,
/// use values >= 0. To make the parameter non-editable when the template is expanded, use -1.
/// </remarks>>
public int Editable { get; set; }
/// <summary>
/// Identifies the target parameter of a <see cref="SourceTemplateAttribute">source template</see> if the
/// <see cref="MacroAttribute"/> is applied on a template method.
/// </summary>
public string Target { get; set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaMasterLocationFormatAttribute : Attribute
{
public AspMvcAreaMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaPartialViewLocationFormatAttribute : Attribute
{
public AspMvcAreaPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcAreaViewLocationFormatAttribute : Attribute
{
public AspMvcAreaViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcMasterLocationFormatAttribute : Attribute
{
public AspMvcMasterLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcPartialViewLocationFormatAttribute : Attribute
{
public AspMvcPartialViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class AspMvcViewLocationFormatAttribute : Attribute
{
public AspMvcViewLocationFormatAttribute(string format)
{
Format = format;
}
public string Format { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC action. If applied to a method, the MVC action name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcActionAttribute : Attribute
{
public AspMvcActionAttribute() { }
public AspMvcActionAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC area.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcAreaAttribute : Attribute
{
public AspMvcAreaAttribute() { }
public AspMvcAreaAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is
/// an MVC controller. If applied to a method, the MVC controller name is calculated
/// implicitly from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper, String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcControllerAttribute : Attribute
{
public AspMvcControllerAttribute() { }
public AspMvcControllerAttribute(string anonymousProperty)
{
AnonymousProperty = anonymousProperty;
}
public string AnonymousProperty { get; private set; }
}
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC Master. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcMasterAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC model type. Use this attribute
/// for custom wrappers similar to <c>System.Web.Mvc.Controller.View(String, Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcModelTypeAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter is an MVC
/// partial view. If applied to a method, the MVC partial view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcPartialViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Allows disabling inspections for MVC views within a class or a method.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class AspMvcSupressViewErrorAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC display template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.DisplayExtensions.DisplayForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcDisplayTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC editor template.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Html.EditorExtensions.EditorForModel(HtmlHelper, String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcEditorTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. Indicates that a parameter is an MVC template.
/// Use this attribute for custom wrappers similar to
/// <c>System.ComponentModel.DataAnnotations.UIHintAttribute(System.String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AspMvcTemplateAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. If applied to a parameter, indicates that the parameter
/// is an MVC view. If applied to a method, the MVC view name is calculated implicitly
/// from the context. Use this attribute for custom wrappers similar to
/// <c>System.Web.Mvc.Controller.View(Object)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class AspMvcViewAttribute : Attribute { }
/// <summary>
/// ASP.NET MVC attribute. When applied to a parameter of an attribute,
/// indicates that this parameter is an MVC action name.
/// </summary>
/// <example><code>
/// [ActionName("Foo")]
/// public ActionResult Login(string returnUrl) {
/// ViewBag.ReturnUrl = Url.Action("Foo"); // OK
/// return RedirectToAction("Bar"); // Error: Cannot resolve action
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property)]
public sealed class AspMvcActionSelectorAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Field)]
public sealed class HtmlElementAttributesAttribute : Attribute
{
public HtmlElementAttributesAttribute() { }
public HtmlElementAttributesAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class HtmlAttributeValueAttribute : Attribute
{
public HtmlAttributeValueAttribute([NotNull] string name)
{
Name = name;
}
[NotNull] public string Name { get; private set; }
}
/// <summary>
/// Razor attribute. Indicates that a parameter or a method is a Razor section.
/// Use this attribute for custom wrappers similar to
/// <c>System.Web.WebPages.WebPageBase.RenderSection(String)</c>.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method)]
public sealed class RazorSectionAttribute : Attribute { }
/// <summary>
/// Indicates how method invocation affects content of the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class CollectionAccessAttribute : Attribute
{
public CollectionAccessAttribute(CollectionAccessType collectionAccessType)
{
CollectionAccessType = collectionAccessType;
}
public CollectionAccessType CollectionAccessType { get; private set; }
}
[Flags]
public enum CollectionAccessType
{
/// <summary>Method does not use or modify content of the collection.</summary>
None = 0,
/// <summary>Method only reads content of the collection but does not modify it.</summary>
Read = 1,
/// <summary>Method can change content of the collection but does not add new elements.</summary>
ModifyExistingContent = 2,
/// <summary>Method can add new elements to the collection.</summary>
UpdatedContent = ModifyExistingContent | 4
}
/// <summary>
/// Indicates that the marked method is assertion method, i.e. it halts control flow if
/// one of the conditions is satisfied. To set the condition, mark one of the parameters with
/// <see cref="AssertionConditionAttribute"/> attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class AssertionMethodAttribute : Attribute { }
/// <summary>
/// Indicates the condition parameter of the assertion method. The method itself should be
/// marked by <see cref="AssertionMethodAttribute"/> attribute. The mandatory argument of
/// the attribute is the assertion type.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class AssertionConditionAttribute : Attribute
{
public AssertionConditionAttribute(AssertionConditionType conditionType)
{
ConditionType = conditionType;
}
public AssertionConditionType ConditionType { get; private set; }
}
/// <summary>
/// Specifies assertion type. If the assertion method argument satisfies the condition,
/// then the execution continues. Otherwise, execution is assumed to be halted.
/// </summary>
public enum AssertionConditionType
{
/// <summary>Marked parameter should be evaluated to true.</summary>
IS_TRUE = 0,
/// <summary>Marked parameter should be evaluated to false.</summary>
IS_FALSE = 1,
/// <summary>Marked parameter should be evaluated to null value.</summary>
IS_NULL = 2,
/// <summary>Marked parameter should be evaluated to not null value.</summary>
IS_NOT_NULL = 3,
}
/// <summary>
/// Indicates that the marked method unconditionally terminates control flow execution.
/// For example, it could unconditionally throw exception.
/// </summary>
[Obsolete("Use [ContractAnnotation('=> halt')] instead")]
[AttributeUsage(AttributeTargets.Method)]
public sealed class TerminatesProgramAttribute : Attribute { }
/// <summary>
/// Indicates that method is pure LINQ method, with postponed enumeration (like Enumerable.Select,
/// .Where). This annotation allows inference of [InstantHandle] annotation for parameters
/// of delegate type by analyzing LINQ method chains.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class LinqTunnelAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// XAML attribute. Indicates the type that has <c>ItemsSource</c> property and should be treated
/// as <c>ItemsControl</c>-derived type, to enable inner items <c>DataContext</c> type resolve.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class XamlItemsControlAttribute : Attribute { }
/// <summary>
/// XAML attibute. Indicates the property of some <c>BindingBase</c>-derived type, that
/// is used to bind some item of <c>ItemsControl</c>-derived type. This annotation will
/// enable the <c>DataContext</c> type resolve for XAML bindings for such properties.
/// </summary>
/// <remarks>
/// Property should have the tree ancestor of the <c>ItemsControl</c> type or
/// marked with the <see cref="XamlItemsControlAttribute"/> attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Property)]
public sealed class XamlItemBindingOfItemsControlAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspChildControlTypeAttribute : Attribute
{
public AspChildControlTypeAttribute(string tagName, Type controlType)
{
TagName = tagName;
ControlType = controlType;
}
public string TagName { get; private set; }
public Type ControlType { get; private set; }
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
public sealed class AspDataFieldsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspMethodPropertyAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public sealed class AspRequiredAttributeAttribute : Attribute
{
public AspRequiredAttributeAttribute([NotNull] string attribute)
{
Attribute = attribute;
}
public string Attribute { get; private set; }
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class AspTypePropertyAttribute : Attribute
{
public bool CreateConstructorReferences { get; private set; }
public AspTypePropertyAttribute(bool createConstructorReferences)
{
CreateConstructorReferences = createConstructorReferences;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorImportNamespaceAttribute : Attribute
{
public RazorImportNamespaceAttribute(string name)
{
Name = name;
}
public string Name { get; private set; }
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public sealed class RazorInjectionAttribute : Attribute
{
public RazorInjectionAttribute(string type, string fieldName)
{
Type = type;
FieldName = fieldName;
}
public string Type { get; private set; }
public string FieldName { get; private set; }
}
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorHelperCommonAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Property)]
public sealed class RazorLayoutAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteLiteralMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
public sealed class RazorWriteMethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RazorWriteMethodParameterAttribute : Attribute { }
/// <summary>
/// Prevents the Member Reordering feature from tossing members of the marked class.
/// </summary>
/// <remarks>
/// The attribute must be mentioned in your member reordering patterns
/// </remarks>
[AttributeUsage(AttributeTargets.All)]
public sealed class NoReorder : Attribute { }
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using CherrySeed.DefaultValues;
using CherrySeed.PrimaryKeyIdGeneration;
using CherrySeed.PrimaryKeyIdGeneration.ApplicationGeneration;
using CherrySeed.Repositories;
using CherrySeed.Utils;
namespace CherrySeed.EntitySettings
{
public class EntitySettingBuilder
{
protected readonly EntitySetting Obj;
public EntitySettingBuilder(Type entityType, int order)
{
Obj = new EntitySetting
{
EntityType = entityType,
PrimaryKey = new PrimaryKeySetting(),
References = new List<ReferenceSetting>(),
IdGeneration = null,
EntityNames = GetPossibleEntityNames(entityType),
AfterSave = obj => { },
DefaultValueSettings = new List<DefaultValueSetting>(),
Order = order
};
}
private List<string> GetPossibleEntityNames(Type entityType)
{
var firstEntityName = entityType.FullName;
var secondEntityName = entityType.Name;
return new List<string>
{
firstEntityName,
secondEntityName
};
}
public EntitySetting Build(IRepository defaultRepository, IdGenerationSetting defaultGenerationSetting, List<string> defaultPrimaryKeyNames)
{
if (Obj.Repository == null)
{
Obj.Repository = defaultRepository;
}
if (Obj.IdGeneration == null)
{
Obj.IdGeneration = defaultGenerationSetting;
}
if (string.IsNullOrEmpty(Obj.PrimaryKey.PrimaryKeyName))
{
Obj.PrimaryKey.PrimaryKeyName = GetFinalPrimaryKeyName(Obj.EntityType, defaultPrimaryKeyNames);
}
return Obj;
}
private string GetFinalPrimaryKeyName(Type type, List<string> defaultPrimaryKeyNames)
{
return defaultPrimaryKeyNames
.Select(propertyName => propertyName.Replace("{ClassName}", type.Name))
.FirstOrDefault(propertyNameWithoutTokens => ReflectionUtil.ExistProperty(type, propertyNameWithoutTokens));
}
}
public interface IEntitySettingBuilder<T>
{
IEntitySettingBuilder<T> WithPrimaryKey(Expression<Func<T, object>> primaryKeyExpression);
IEntitySettingBuilder<T> WithReference(Expression<Func<T, object>> referenceExpression, Type referenceEntity);
IEntitySettingBuilder<T> WithRepository(IRepository repository);
IEntitySettingBuilder<T> WithDisabledPrimaryKeyIdGeneration();
IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInDatabase();
IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsInteger(int startId = 1, int steps = 1);
IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsGuid();
IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsString(string prefix = "", int startId = 1, int steps = 1);
IEntitySettingBuilder<T> WithCustomPrimaryKeyIdGenerationInApplication(IPrimaryKeyIdGenerator generator);
IEntitySettingBuilder<T> HasEntityName(string entityName);
IEntitySettingBuilder<T> AfterSave(Action<object> afterSaveAction);
IEntitySettingBuilder<T> WithFieldWithDefaultValue(Expression<Func<T, object>> fieldExpression,
IDefaultValueProvider defaultValueProvider);
IEntitySettingBuilder<T> WithFieldWithDefaultValue(Expression<Func<T, object>> fieldExpression,
Func<object> defaultValueFunc);
}
public class EntitySettingBuilder<T> : EntitySettingBuilder, IEntitySettingBuilder<T>
{
public EntitySettingBuilder(Type entityType, int order)
: base(entityType, order)
{ }
public IEntitySettingBuilder<T> WithPrimaryKey(Expression<Func<T, object>> primaryKeyExpression)
{
Obj.PrimaryKey = new PrimaryKeySetting<T>(primaryKeyExpression);
return this;
}
public IEntitySettingBuilder<T> WithReference(
Expression<Func<T, object>> referenceExpression,
Type referenceEntity)
{
Obj.References.Add(new ReferenceSetting<T>(referenceExpression, referenceEntity));
return this;
}
public IEntitySettingBuilder<T> WithRepository(IRepository repository)
{
Obj.Repository = repository;
return this;
}
public IEntitySettingBuilder<T> WithDisabledPrimaryKeyIdGeneration()
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = null
};
return this;
}
public IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInDatabase()
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = new DatabasePrimaryKeyIdGeneration()
};
return this;
}
public IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsInteger(int startId = 1, int steps = 1)
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = new ApplicationPrimaryKeyIdGeneration
{
Generator = new IntegerPrimaryKeyIdGenerator(startId, steps)
}
};
return this;
}
public IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsGuid()
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = new ApplicationPrimaryKeyIdGeneration
{
Generator = new GuidPrimaryKeyIdGenerator()
}
};
return this;
}
public IEntitySettingBuilder<T> WithPrimaryKeyIdGenerationInApplicationAsString(string prefix = "", int startId = 1, int steps = 1)
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = new ApplicationPrimaryKeyIdGeneration
{
Generator = new StringPrimaryKeyIdGenerator(prefix, startId, steps)
}
};
return this;
}
public IEntitySettingBuilder<T> WithCustomPrimaryKeyIdGenerationInApplication(IPrimaryKeyIdGenerator generator)
{
Obj.IdGeneration = new IdGenerationSetting
{
Generator = new ApplicationPrimaryKeyIdGeneration
{
Generator = generator
}
};
return this;
}
public IEntitySettingBuilder<T> HasEntityName(string entityName)
{
Obj.EntityNames = new List<string> { entityName };
return this;
}
public IEntitySettingBuilder<T> AfterSave(Action<object> afterSaveAction)
{
Obj.AfterSave = afterSaveAction;
return this;
}
public IEntitySettingBuilder<T> WithFieldWithDefaultValue(Expression<Func<T, object>> fieldExpression, IDefaultValueProvider defaultValueProvider)
{
Obj.DefaultValueSettings.Add(new DefaultValueSetting<T>(fieldExpression, defaultValueProvider));
return this;
}
public IEntitySettingBuilder<T> WithFieldWithDefaultValue(Expression<Func<T, object>> fieldExpression, Func<object> defaultValueFunc)
{
Obj.DefaultValueSettings.Add(new DefaultValueSetting<T>(fieldExpression, new FuncDefaultValueProvider(defaultValueFunc)));
return this;
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using System.Security;
using System.Xml;
#if !MONO
namespace NLog.UnitTests.Config
{
using NLog.Config;
using System;
using System.IO;
using System.Threading;
using Xunit;
public class ReloadTests : NLogTestBase
{
[Fact]
public void TestNoAutoReload()
{
string config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "noreload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.False(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, config2, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileChange()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileChange because we are running in Travis");
return;
}
#endif
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string badConfig = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
Assert.True(((XmlLoggingConfiguration)LogManager.Configuration).AutoReload);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(configFilePath, badConfig, assertDidReload: false);
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
ChangeAndReloadConfigFile(configFilePath, config2);
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileMove()
{
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(configFilePath, otherFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Move(otherFilePath, configFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestAutoReloadOnFileCopy()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestAutoReloadOnFileCopy because we are running in Travis");
return;
}
#endif
string config1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string config2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string configFilePath = Path.Combine(tempPath, "reload.nlog");
WriteConfigFile(configFilePath, config1);
string otherFilePath = Path.Combine(tempPath, "other.nlog");
try
{
LogManager.Configuration = new XmlLoggingConfiguration(configFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Delete(configFilePath);
reloadWaiter.WaitForReload();
}
logger.Debug("bbb");
// Assert that config1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(otherFilePath, config2);
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
File.Copy(otherFilePath, configFilePath);
File.Delete(otherFilePath);
reloadWaiter.WaitForReload();
Assert.True(reloadWaiter.DidReload);
}
logger.Debug("ccc");
// Assert that config2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigNoReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2, assertDidReload: false);
logger.Debug("ccc");
// Assert that includedConfig1 is still loaded.
AssertDebugLastMessage("debug", "ccc");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestIncludedConfigReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestIncludedConfigNoReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Info' writeTo='debug' /></rules>
</nlog>";
string includedConfig1 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string includedConfig2 = @"<nlog autoReload='true'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string includedConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(includedConfigFilePath, includedConfig1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2, assertDidReload: false);
logger.Debug("bbb");
// Assert that mainConfig1 is still loaded.
AssertDebugLastMessage("debug", "bbb");
WriteConfigFile(mainConfigFilePath, mainConfig1);
ChangeAndReloadConfigFile(includedConfigFilePath, includedConfig2);
logger.Debug("ccc");
// Assert that includedConfig2 is loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2);
logger.Debug("ccc");
// Assert that included2Config2 is loaded.
AssertDebugLastMessage("debug", "(ccc)");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestMainConfigReloadIncludedConfigNoReload()
{
#if NETSTANDARD
if (IsTravis())
{
Console.WriteLine("[SKIP] ReloadTests.TestMainConfigReload because we are running in Travis");
return;
}
#endif
string mainConfig1 = @"<nlog autoReload='true'>
<include file='included.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string mainConfig2 = @"<nlog autoReload='true'>
<include file='included2.nlog' />
<rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules>
</nlog>";
string included1Config = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
</nlog>";
string included2Config1 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='[${message}]' /></targets>
</nlog>";
string included2Config2 = @"<nlog autoReload='false'>
<targets><target name='debug' type='Debug' layout='(${message})' /></targets>
</nlog>";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
string mainConfigFilePath = Path.Combine(tempPath, "main.nlog");
WriteConfigFile(mainConfigFilePath, mainConfig1);
string included1ConfigFilePath = Path.Combine(tempPath, "included.nlog");
WriteConfigFile(included1ConfigFilePath, included1Config);
string included2ConfigFilePath = Path.Combine(tempPath, "included2.nlog");
WriteConfigFile(included2ConfigFilePath, included2Config1);
try
{
LogManager.Configuration = new XmlLoggingConfiguration(mainConfigFilePath);
var logger = LogManager.GetLogger("A");
logger.Debug("aaa");
AssertDebugLastMessage("debug", "aaa");
ChangeAndReloadConfigFile(mainConfigFilePath, mainConfig2);
logger.Debug("bbb");
// Assert that mainConfig2 is loaded (which refers to included2.nlog).
AssertDebugLastMessage("debug", "[bbb]");
ChangeAndReloadConfigFile(included2ConfigFilePath, included2Config2, assertDidReload: false);
logger.Debug("ccc");
// Assert that included2Config1 is still loaded.
AssertDebugLastMessage("debug", "[ccc]");
}
finally
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
}
[Fact]
public void TestKeepVariablesOnReload()
{
string config = @"<nlog autoReload='true' keepVariablesOnReload='true'>
<variable name='var1' value='' />
<variable name='var2' value='keep_value' />
</nlog>";
LogManager.Configuration = XmlLoggingConfigurationMock.CreateFromXml(config);
LogManager.Configuration.Variables["var1"] = "new_value";
LogManager.Configuration.Variables["var3"] = "new_value3";
LogManager.Configuration = LogManager.Configuration.Reload();
Assert.Equal("new_value", LogManager.Configuration.Variables["var1"].OriginalText);
Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText);
Assert.Equal("new_value3", LogManager.Configuration.Variables["var3"].OriginalText);
}
[Fact]
public void TestResetVariablesOnReload()
{
string config = @"<nlog autoReload='true' keepVariablesOnReload='false'>
<variable name='var1' value='' />
<variable name='var2' value='keep_value' />
</nlog>";
LogManager.Configuration = XmlLoggingConfigurationMock.CreateFromXml(config);
LogManager.Configuration.Variables["var1"] = "new_value";
LogManager.Configuration.Variables["var3"] = "new_value3";
LogManager.Configuration = LogManager.Configuration.Reload();
Assert.Equal("", LogManager.Configuration.Variables["var1"].OriginalText);
Assert.Equal("keep_value", LogManager.Configuration.Variables["var2"].OriginalText);
}
[Fact]
public void TestReloadingInvalidConfiguration()
{
var validXmlConfig = @"<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='debug' />
</rules>
</nlog>";
var invalidXmlConfig = "";
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
try {
var nlogConfigFile = Path.Combine(tempPath, "NLog.config");
WriteConfigFile(nlogConfigFile, invalidXmlConfig);
var invalidConfiguration = new XmlLoggingConfiguration(nlogConfigFile);
Assert.False(invalidConfiguration.InitializeSucceeded);
WriteConfigFile(nlogConfigFile, validXmlConfig);
var validReloadedConfiguration = (XmlLoggingConfiguration)invalidConfiguration.Reload();
Assert.True(validReloadedConfiguration.InitializeSucceeded);
}
finally
{
if (Directory.Exists(tempPath))
{
Directory.Delete(tempPath, true);
}
}
}
private static void WriteConfigFile(string configFilePath, string config)
{
using (StreamWriter writer = File.CreateText(configFilePath))
writer.Write(config);
}
private static void ChangeAndReloadConfigFile(string configFilePath, string config, bool assertDidReload = true)
{
using (var reloadWaiter = new ConfigurationReloadWaiter())
{
WriteConfigFile(configFilePath, config);
reloadWaiter.WaitForReload();
if (assertDidReload)
Assert.True(reloadWaiter.DidReload, $"Config '{configFilePath}' did not reload.");
}
}
private class ConfigurationReloadWaiter : IDisposable
{
private ManualResetEvent counterEvent = new ManualResetEvent(false);
public ConfigurationReloadWaiter()
{
LogManager.ConfigurationReloaded += SignalCounterEvent(counterEvent);
}
public bool DidReload => counterEvent.WaitOne(0);
public void Dispose()
{
LogManager.ConfigurationReloaded -= SignalCounterEvent(counterEvent);
}
public void WaitForReload()
{
counterEvent.WaitOne(3000);
}
private static EventHandler<LoggingConfigurationReloadedEventArgs> SignalCounterEvent(ManualResetEvent counterEvent)
{
return (sender, e) =>
{
counterEvent.Set();
};
}
}
}
/// <summary>
/// Xml config with reload without file-reads for performance
/// </summary>
public class XmlLoggingConfigurationMock : XmlLoggingConfiguration
{
private XmlElement _xmlElement;
private string _fileName;
/// <summary>
/// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class.
/// </summary>
/// <param name="element">The XML element.</param>
/// <param name="fileName">Name of the XML file.</param>
internal XmlLoggingConfigurationMock(XmlElement element, string fileName) : base(element, fileName)
{
_xmlElement = element;
_fileName = fileName;
}
private bool _reloading;
#region Overrides of XmlLoggingConfiguration
public override LoggingConfiguration Reload()
{
if (_reloading)
{
return new XmlLoggingConfigurationMock(_xmlElement, _fileName);
}
_reloading = true;
var factory = LogManager.LogFactory;
//reloadTimer should be set for ReloadConfigOnTimer
factory.reloadTimer = new Timer((a) => { });
factory.ReloadConfigOnTimer(this);
_reloading = false;
return factory.Configuration;
}
#endregion
public static XmlLoggingConfigurationMock CreateFromXml(string configXml)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(configXml);
string currentDirectory = null;
try
{
currentDirectory = Environment.CurrentDirectory;
}
catch (SecurityException)
{
//ignore
}
return new XmlLoggingConfigurationMock(doc.DocumentElement, currentDirectory);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System
{
using System;
using System.Reflection;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection.Emit;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
{
// This is set under 3 circumstances
// 1. Multicast delegate
// 2. Secure/Wrapper delegate
// 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method
private Object _invocationList;
private IntPtr _invocationCount;
// This constructor is called from the class generated by the
// compiler generated code (This must match the constructor
// in Delegate
protected MulticastDelegate(Object target, String method) : base(target, method)
{
}
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
protected MulticastDelegate(Type target, String method) : base(target, method)
{
}
internal bool IsUnmanagedFunctionPtr()
{
return (_invocationCount == (IntPtr)(-1));
}
internal bool InvocationListLogicallyNull()
{
return (_invocationList == null) || (_invocationList is LoaderAllocator) || (_invocationList is DynamicResolver);
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
int targetIndex = 0;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
MethodInfo method = Method;
// A MethodInfo object can be a RuntimeMethodInfo, a RefEmit method (MethodBuilder, etc), or a DynamicMethod
// One can only create delegates on RuntimeMethodInfo and DynamicMethod.
// If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, throw
if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() )
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
// We can't deal with secure delegates either.
if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull())
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex);
}
else
{
DelegateSerializationHolder.DelegateEntry nextDe = null;
int invocationCount = (int)_invocationCount;
for (int i = invocationCount; --i >= 0; )
{
MulticastDelegate d = (MulticastDelegate)invocationList[i];
MethodInfo method = d.Method;
// If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, skip
if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() )
continue;
// We can't deal with secure delegates either.
if (!d.InvocationListLogicallyNull() && !d._invocationCount.IsNull() && !d._methodPtrAux.IsNull())
continue;
DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, method, targetIndex++);
if (nextDe != null)
nextDe.Entry = de;
nextDe = de;
}
// if nothing was serialized it is a delegate over a DynamicMethod, so just throw
if (nextDe == null)
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
}
}
// equals returns true IIF the delegate is not null and has the
// same target, method and invocation list as this object
public override sealed bool Equals(Object obj)
{
if (obj == null)
return false;
if (object.ReferenceEquals(this, obj))
return true;
if (!InternalEqualTypes(this, obj))
return false;
// Since this is a MulticastDelegate and we know
// the types are the same, obj should also be a
// MulticastDelegate
Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
if (_invocationCount != (IntPtr)0)
{
// there are 4 kind of delegate kinds that fall into this bucket
// 1- Multicast (_invocationList is Object[])
// 2- Secure/Wrapper (_invocationList is Delegate)
// 3- Unmanaged FntPtr (_invocationList == null)
// 4- Open virtual (_invocationCount == MethodDesc of target, _invocationList == null, LoaderAllocator, or DynamicResolver)
if (InvocationListLogicallyNull())
{
if (IsUnmanagedFunctionPtr())
{
if (!d.IsUnmanagedFunctionPtr())
return false;
return CompareUnmanagedFunctionPtrs(this, d);
}
// now we know 'this' is not a special one, so we can work out what the other is
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return Equals(d._invocationList);
return base.Equals(obj);
}
else
{
if ((_invocationList as Delegate) != null)
{
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return _invocationList.Equals(obj);
}
else
{
Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
return InvocationListEquals(d);
}
}
}
else
{
// among the several kind of delegates falling into this bucket one has got a non
// empty _invocationList (open static with special sig)
// to be equals we need to check that _invocationList matches (both null is fine)
// and call the base.Equals()
if (!InvocationListLogicallyNull())
{
if (!_invocationList.Equals(d._invocationList))
return false;
return base.Equals(d);
}
// now we know 'this' is not a special one, so we can work out what the other is
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return Equals(d._invocationList);
// now we can call on the base
return base.Equals(d);
}
}
// Recursive function which will check for equality of the invocation list.
private bool InvocationListEquals(MulticastDelegate d)
{
Debug.Assert(d != null && (_invocationList as Object[]) != null, "bogus delegate in multicast list comparison");
Object[] invocationList = _invocationList as Object[];
if (d._invocationCount != _invocationCount)
return false;
int invocationCount = (int)_invocationCount;
for (int i = 0; i < invocationCount; i++)
{
Delegate dd = (Delegate)invocationList[i];
Object[] dInvocationList = d._invocationList as Object[];
if (!dd.Equals(dInvocationList[i]))
return false;
}
return true;
}
private bool TrySetSlot(Object[] a, int index, Object o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null)
return true;
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
if (dd._methodPtr == d._methodPtr &&
dd._target == d._target &&
dd._methodPtrAux == d._methodPtrAux)
{
return true;
}
}
return false;
}
private MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
MulticastDelegate result = (MulticastDelegate)InternalAllocLike(this);
// Performance optimization - if this already points to a true multicast delegate,
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
result._methodPtr = this._methodPtr;
result._methodPtrAux = this._methodPtrAux;
}
else
{
result._methodPtr = GetMulticastInvoke();
result._methodPtrAux = GetInvokeMethod();
}
result._target = result;
result._invocationList = invocationList;
result._invocationCount = (IntPtr)invocationCount;
return result;
}
internal MulticastDelegate NewMulticastDelegate(Object[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
internal void StoreDynamicMethod(MethodInfo dynamicMethod)
{
if (_invocationCount != (IntPtr)0)
{
Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
// must be a secure/wrapper one, unwrap and save
MulticastDelegate d = (MulticastDelegate)_invocationList;
d._methodBase = dynamicMethod;
}
else
_methodBase = dynamicMethod;
}
// This method will combine this delegate with the passed delegate
// to form a new delegate.
protected override sealed Delegate CombineImpl(Delegate follow)
{
if ((Object)follow == null) // cast to object for a more efficient test
return this;
// Verify that the types are the same...
if (!InternalEqualTypes(this, follow))
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
MulticastDelegate dFollow = (MulticastDelegate)follow;
Object[] resultList;
int followCount = 1;
Object[] followList = dFollow._invocationList as Object[];
if (followList != null)
followCount = (int)dFollow._invocationCount;
int resultCount;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
resultCount = 1 + followCount;
resultList = new Object[resultCount];
resultList[0] = this;
if (followList == null)
{
resultList[1] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[1 + i] = followList[i];
}
return NewMulticastDelegate(resultList, resultCount);
}
else
{
int invocationCount = (int)_invocationCount;
resultCount = invocationCount + followCount;
resultList = null;
if (resultCount <= invocationList.Length)
{
resultList = invocationList;
if (followList == null)
{
if (!TrySetSlot(resultList, invocationCount, dFollow))
resultList = null;
}
else
{
for (int i = 0; i < followCount; i++)
{
if (!TrySetSlot(resultList, invocationCount + i, followList[i]))
{
resultList = null;
break;
}
}
}
}
if (resultList == null)
{
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
resultList = new Object[allocCount];
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
if (followList == null)
{
resultList[invocationCount] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[invocationCount + i] = followList[i];
}
}
return NewMulticastDelegate(resultList, resultCount, true);
}
}
private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Object[] thisInvocationList = _invocationList as Object[];
int allocCount = thisInvocationList.Length;
while (allocCount/2 >= invocationCount - deleteCount)
allocCount /= 2;
Object[] newInvocationList = new Object[allocCount];
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
return newInvocationList;
}
private bool EqualInvocationLists(Object[] a, Object[] b, int start, int count)
{
for (int i = 0; i < count; i++)
{
if (!(a[start + i].Equals(b[i])))
return false;
}
return true;
}
// This method currently looks backward on the invocation list
// for an element that has Delegate based equality with value. (Doesn't
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
protected override sealed Delegate RemoveImpl(Delegate value)
{
// There is a special case were we are removing using a delegate as
// the value we need to check for this case
//
MulticastDelegate v = value as MulticastDelegate;
if (v == null)
return this;
if (v._invocationList as Object[] == null)
{
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
// they are both not real Multicast
if (this.Equals(value))
return null;
}
else
{
int invocationCount = (int)_invocationCount;
for (int i = invocationCount; --i >= 0; )
{
if (value.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
return (Delegate)invocationList[1-i];
}
else
{
Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
return NewMulticastDelegate(list, invocationCount-1, true);
}
}
}
}
}
else
{
Object[] invocationList = _invocationList as Object[];
if (invocationList != null) {
int invocationCount = (int)_invocationCount;
int vInvocationCount = (int)v._invocationCount;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
{
if (EqualInvocationLists(invocationList, v._invocationList as Object[], i, vInvocationCount))
{
if (invocationCount - vInvocationCount == 0)
{
// Special case - no values left
return null;
}
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
return (Delegate)invocationList[i != 0 ? 0 : invocationCount-1];
}
else
{
Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount);
return NewMulticastDelegate(list, invocationCount - vInvocationCount, true);
}
}
}
}
}
return this;
}
// This method returns the Invocation list of this multicast delegate.
public override sealed Delegate[] GetInvocationList()
{
Contract.Ensures(Contract.Result<Delegate[]>() != null);
Delegate[] del;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
del = new Delegate[1];
del[0] = this;
}
else
{
// Create an array of delegate copies and each
// element into the array
del = new Delegate[(int)_invocationCount];
for (int i = 0; i < del.Length; i++)
del[i] = (Delegate)invocationList[i];
}
return del;
}
public static bool operator ==(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 == null;
return d1.Equals(d2);
}
public static bool operator !=(MulticastDelegate d1, MulticastDelegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
return !d1.Equals(d2);
}
public override sealed int GetHashCode()
{
if (IsUnmanagedFunctionPtr())
return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux);
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
return base.GetHashCode();
}
else
{
int hash = 0;
for (int i = 0; i < (int)_invocationCount; i++)
{
hash = hash*33 + invocationList[i].GetHashCode();
}
return hash;
}
}
internal override Object GetTarget()
{
if (_invocationCount != (IntPtr)0)
{
// _invocationCount != 0 we are in one of these cases:
// - Multicast -> return the target of the last delegate in the list
// - Secure/wrapper delegate -> return the target of the inner delegate
// - unmanaged function pointer - return null
// - virtual open delegate - return null
if (InvocationListLogicallyNull())
{
// both open virtual and ftn pointer return null for the target
return null;
}
else
{
Object[] invocationList = _invocationList as Object[];
if (invocationList != null)
{
int invocationCount = (int)_invocationCount;
return ((Delegate)invocationList[invocationCount - 1]).GetTarget();
}
else
{
Delegate receiver = _invocationList as Delegate;
if (receiver != null)
return receiver.GetTarget();
}
}
}
return base.GetTarget();
}
protected override MethodInfo GetMethodImpl()
{
if (_invocationCount != (IntPtr)0 && _invocationList != null)
{
// multicast case
Object[] invocationList = _invocationList as Object[];
if (invocationList != null)
{
int index = (int)_invocationCount - 1;
return ((Delegate)invocationList[index]).Method;
}
MulticastDelegate innerDelegate = _invocationList as MulticastDelegate;
if (innerDelegate != null)
{
// must be a secure/wrapper delegate
return innerDelegate.GetMethodImpl();
}
}
else if (IsUnmanagedFunctionPtr())
{
// we handle unmanaged function pointers here because the generic ones (used for WinRT) would otherwise
// be treated as open delegates by the base implementation, resulting in failure to get the MethodInfo
if ((_methodBase == null) || !(_methodBase is MethodInfo))
{
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
// we are returning the 'Invoke' method of this delegate so use this.GetType() for the exact type
RuntimeType reflectedType = GetType() as RuntimeType;
declaringType = reflectedType;
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
return (MethodInfo)_methodBase;
}
// Otherwise, must be an inner delegate of a SecureDelegate of an open virtual method. In that case, call base implementation
return base.GetMethodImpl();
}
// this should help inlining
[System.Diagnostics.DebuggerNonUserCode]
private void ThrowNullThisInDelegateToInstance()
{
throw new ArgumentException(Environment.GetResourceString("Arg_DlgtNullInst"));
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosed(Object target, IntPtr methodPtr)
{
if (target == null)
ThrowNullThisInDelegateToInstance();
this._target = target;
this._methodPtr = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosedStatic(Object target, IntPtr methodPtr)
{
this._target = target;
this._methodPtr = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorRTClosed(Object target, IntPtr methodPtr)
{
this._target = target;
this._methodPtr = AdjustTarget(target, methodPtr);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = methodPtr;
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
realDelegate.CtorClosed(target, methodPtr);
this._invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
this._invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
realDelegate.CtorClosedStatic(target, methodPtr);
this._invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
this._invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorRTClosed(target, methodPtr);
this._invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
this._invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorOpened(target, methodPtr, shuffleThunk);
this._invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
this._invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = GetCallStub(methodPtr);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorVirtualDispatch(target, methodPtr, shuffleThunk);
this._invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
this._invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle)
{
this._target = target;
this._methodPtr = methodPtr;
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = methodPtr;
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle)
{
this._target = this;
this._methodPtr = shuffleThunk;
this._methodPtrAux = GetCallStub(methodPtr);
this._methodBase = System.Runtime.InteropServices.GCHandle.InternalGet(gchandle);
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using SteamKit2;
using System.Net;
using Newtonsoft.Json;
namespace SteamAPI
{
public class TradeOffers
{
public SteamID BotId;
private SteamWeb SteamWeb;
public List<ulong> OurPendingTradeOffers;
private List<ulong> ReceivedPendingTradeOffers;
private List<ulong> HandledTradeOffers;
private List<ulong> AwaitingConfirmationTradeOffers;
private string AccountApiKey;
private bool ShouldCheckPendingTradeOffers;
private int TradeOfferRefreshRate;
public TradeOffers(SteamID botId, SteamWeb steamWeb, string accountApiKey, int tradeOfferRefreshRate, List<ulong> pendingTradeOffers = null)
{
this.BotId = botId;
this.SteamWeb = steamWeb;
this.AccountApiKey = accountApiKey;
this.ShouldCheckPendingTradeOffers = true;
this.TradeOfferRefreshRate = tradeOfferRefreshRate;
if (pendingTradeOffers == null)
this.OurPendingTradeOffers = new List<ulong>();
else
this.OurPendingTradeOffers = pendingTradeOffers;
this.ReceivedPendingTradeOffers = new List<ulong>();
this.HandledTradeOffers = new List<ulong>();
this.AwaitingConfirmationTradeOffers = new List<ulong>();
new Thread(CheckPendingTradeOffers).Start();
}
/// <summary>
/// Create a new trade offer session.
/// </summary>
/// <param name="partnerId">The SteamID of the user you want to send a trade offer to.</param>
/// <returns>A 'Trade' object in which you can apply further actions</returns>
public Trade CreateTrade(SteamID partnerId)
{
return new Trade(this, partnerId, SteamWeb);
}
public class Trade
{
private TradeOffers TradeOffers;
private CookieContainer cookies = new CookieContainer();
private SteamWeb steamWeb;
private SteamID partnerId;
public TradeStatus tradeStatus;
public Trade(TradeOffers tradeOffers, SteamID partnerId, SteamWeb steamWeb)
{
this.TradeOffers = tradeOffers;
this.partnerId = partnerId;
this.steamWeb = steamWeb;
tradeStatus = new TradeStatus();
tradeStatus.version = 1;
tradeStatus.newversion = true;
tradeStatus.me = new TradeStatusUser(ref tradeStatus);
tradeStatus.them = new TradeStatusUser(ref tradeStatus);
}
/// <summary>
/// Send the current trade offer with a token.
/// </summary>
/// <param name="message">Message to send with trade offer.</param>
/// <param name="token">Trade offer token.</param>
/// <returns>-1 if response fails to deserialize (general error), 0 if no tradeofferid exists (Steam error), or the Trade Offer ID of the newly created trade offer.</returns>
public ulong SendTradeWithToken(string message, string token)
{
return SendTrade(message, token);
}
/// <summary>
/// Send the current trade offer.
/// </summary>
/// <param name="message">Message to send with trade offer.</param>
/// <param name="token">Optional trade offer token.</param>
/// <returns>-1 if response fails to deserialize (general error), 0 if no tradeofferid exists (Steam error), or the Trade Offer ID of the newly created trade offer.</returns>
public ulong SendTrade(string message, string token = "")
{
var url = "https://steamcommunity.com/tradeoffer/new/send";
var referer = "https://steamcommunity.com/tradeoffer/new/?partner=" + partnerId.AccountID;
var data = new NameValueCollection();
data.Add("sessionid", steamWeb.SessionId);
data.Add("serverid", "1");
data.Add("partner", partnerId.ConvertToUInt64().ToString());
data.Add("tradeoffermessage", message);
data.Add("json_tradeoffer", JsonConvert.SerializeObject(this.tradeStatus));
data.Add("trade_offer_create_params", token == "" ? "{}" : "{\"trade_offer_access_token\":\"" + token + "\"}");
try
{
string response = RetryWebRequest(steamWeb, url, "POST", data, true, referer);
dynamic jsonResponse = JsonConvert.DeserializeObject<dynamic>(response);
try
{
ulong tradeOfferId = Convert.ToUInt64(jsonResponse.tradeofferid);
this.TradeOffers.AddPendingTradeOfferToList(tradeOfferId);
return tradeOfferId;
}
catch
{
return 0;
}
}
catch
{
return 0;
}
}
/// <summary>
/// Add a bot's item to the trade offer.
/// </summary>
/// <param name="asset">TradeAsset object</param>
/// <returns>True if item hasn't been added already, false if it has.</returns>
public bool AddMyItem(TradeAsset asset)
{
return tradeStatus.me.AddItem(asset);
}
/// <summary>
/// Add a bot's item to the trade offer.
/// </summary>
/// <param name="appId">App ID of item</param>
/// <param name="contextId">Context ID of item</param>
/// <param name="assetId">Asset (unique) ID of item</param>
/// <param name="amount">Amount to add (default = 1)</param>
/// <returns>True if item hasn't been added already, false if it has.</returns>
public bool AddMyItem(int appId, ulong contextId, ulong assetId, int amount = 1)
{
var asset = new TradeAsset(appId, contextId, assetId, amount);
return tradeStatus.me.AddItem(asset);
}
/// <summary>
/// Add a user's item to the trade offer.
/// </summary>
/// <param name="asset">TradeAsset object</param>
/// <returns>True if item hasn't been added already, false if it has.</returns>
public bool AddOtherItem(TradeAsset asset)
{
return tradeStatus.them.AddItem(asset);
}
/// <summary>
/// Add a user's item to the trade offer.
/// </summary>
/// <param name="appId">App ID of item</param>
/// <param name="contextId">Context ID of item</param>
/// <param name="assetId">Asset (unique) ID of item</param>
/// <param name="amount">Amount to add (default = 1)</param>
/// <returns>True if item hasn't been added already, false if it has.</returns>
public bool AddOtherItem(int appId, ulong contextId, ulong assetId, int amount = 1)
{
var asset = new TradeAsset(appId, contextId, assetId, amount);
return tradeStatus.them.AddItem(asset);
}
public class TradeStatus
{
public bool newversion { get; set; }
public int version { get; set; }
public TradeStatusUser me { get; set; }
public TradeStatusUser them { get; set; }
[JsonIgnore]
public string message { get; set; }
[JsonIgnore]
public ulong tradeid { get; set; }
}
public class TradeStatusUser
{
public List<TradeAsset> assets { get; set; }
public List<TradeAsset> currency = new List<TradeAsset>();
public bool ready { get; set; }
[JsonIgnore]
public TradeStatus tradeStatus;
[JsonIgnore]
public SteamID steamId;
public TradeStatusUser(ref TradeStatus tradeStatus)
{
this.tradeStatus = tradeStatus;
ready = false;
assets = new List<TradeAsset>();
}
public bool AddItem(TradeAsset asset)
{
if (!assets.Contains(asset))
{
tradeStatus.version++;
assets.Add(asset);
return true;
}
return false;
}
public bool AddItem(int appId, ulong contextId, ulong assetId, int amount = 1)
{
var asset = new TradeAsset(appId, contextId, assetId, amount);
return AddItem(asset);
}
}
public class TradeAsset
{
public int appid;
public string contextid;
public int amount;
public string assetid;
public TradeAsset(int appId, ulong contextId, ulong itemId, int amount)
{
this.appid = appId;
this.contextid = contextId.ToString();
this.assetid = itemId.ToString();
this.amount = amount;
}
public TradeAsset(int appId, string contextId, string itemId, int amount)
{
this.appid = appId;
this.contextid = contextId;
this.assetid = itemId;
this.amount = amount;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
TradeAsset other = obj as TradeAsset;
if ((Object)other == null)
return false;
return Equals(other);
}
public bool Equals(TradeAsset other)
{
return (this.appid == other.appid) &&
(this.contextid == other.contextid) &&
(this.amount == other.amount) &&
(this.assetid == other.assetid);
}
public override int GetHashCode()
{
return (Convert.ToUInt64(appid) ^ Convert.ToUInt64(contextid) ^ Convert.ToUInt64(amount) ^ Convert.ToUInt64(assetid)).GetHashCode();
}
}
}
/// <summary>
/// Accepts a pending trade offer.
/// </summary>
/// <param name="tradeOfferId">The ID of the trade offer</param>
/// <returns>True if successful, false if not</returns>
public bool AcceptTrade(ulong tradeOfferId)
{
GetTradeOfferAPI.GetTradeOfferResponse tradeOfferResponse = GetTradeOffer(tradeOfferId);
return AcceptTrade(tradeOfferResponse.Offer);
}
private bool AcceptTrade(TradeOffer tradeOffer)
{
var tradeOfferId = tradeOffer.Id;
var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/accept";
var referer = "http://steamcommunity.com/tradeoffer/" + tradeOfferId + "/";
var data = new NameValueCollection();
data.Add("sessionid", SteamWeb.SessionId);
data.Add("serverid", "1");
data.Add("tradeofferid", tradeOfferId.ToString());
data.Add("partner", tradeOffer.OtherSteamId.ToString());
string response = RetryWebRequest(SteamWeb, url, "POST", data, true, referer);
if (string.IsNullOrEmpty(response))
{
return ValidateTradeAccept(tradeOffer);
}
else
{
try
{
dynamic json = JsonConvert.DeserializeObject(response);
var id = json.tradeid;
return true;
}
catch
{
return ValidateTradeAccept(tradeOffer);
}
}
}
/// <summary>
/// Declines a pending trade offer
/// </summary>
/// <param name="tradeOfferId">The trade offer ID</param>
/// <returns>True if successful, false if not</returns>
public bool DeclineTrade(ulong tradeOfferId)
{
return DeclineTrade(GetTradeOffer(tradeOfferId).Offer);
}
/// <summary>
/// Declines a pending trade offer
/// </summary>
/// <param name="tradeOffer">The trade offer object</param>
/// <returns>True if successful, false if not</returns>
public bool DeclineTrade(TradeOffer tradeOffer)
{
var url = "https://steamcommunity.com/tradeoffer/" + tradeOffer.Id + "/decline";
var referer = "http://steamcommunity.com/";
var data = new NameValueCollection();
data.Add("sessionid", SteamWeb.SessionId);
data.Add("serverid", "1");
string response = RetryWebRequest(SteamWeb, url, "POST", data, true, referer);
try
{
dynamic json = JsonConvert.DeserializeObject(response);
var id = json.tradeofferid;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// Cancels a pending sent trade offer
/// </summary>
/// <param name="tradeOffer">The trade offer object</param>
/// <returns>True if successful, false if not</returns>
public bool CancelTrade(TradeOffer tradeOffer)
{
return CancelTrade(tradeOffer.Id);
}
/// <summary>
/// Cancels a pending sent trade offer
/// </summary>
/// <param name="tradeOfferId">The trade offer ID</param>
/// <returns>True if successful, false if not</returns>
public bool CancelTrade(ulong tradeOfferId)
{
var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/cancel";
var referer = "http://steamcommunity.com/";
var data = new NameValueCollection();
data.Add("sessionid", SteamWeb.SessionId);
string response = RetryWebRequest(SteamWeb, url, "POST", data, true, referer);
try
{
dynamic json = JsonConvert.DeserializeObject(response);
var id = json.tradeofferid;
}
catch
{
return false;
}
return true;
}
/// <summary>
/// Get a list of incoming trade offers.
/// </summary>
/// <returns>An 'int' list of trade offer IDs</returns>
public List<ulong> GetIncomingTradeOffers()
{
List<ulong> IncomingTradeOffers = new List<ulong>();
var url = "http://steamcommunity.com/profiles/" + BotId.ConvertToUInt64() + "/tradeoffers/";
var html = RetryWebRequest(SteamWeb, url, "GET", null);
var reg = new Regex("ShowTradeOffer\\((.*?)\\);");
var matches = reg.Matches(html);
foreach (Match match in matches)
{
if (match.Success)
{
var tradeId = Convert.ToUInt64(match.Groups[1].Value.Replace("'", ""));
if (!IncomingTradeOffers.Contains(tradeId))
IncomingTradeOffers.Add(tradeId);
}
}
return IncomingTradeOffers;
}
public GetTradeOfferAPI.GetTradeOfferResponse GetTradeOffer(ulong tradeOfferId)
{
string url = String.Format("https://api.steampowered.com/IEconService/GetTradeOffer/v1/?key={0}&tradeofferid={1}&language={2}", AccountApiKey, tradeOfferId, "en_us");
string response = RetryWebRequest(SteamWeb, url, "GET", null, false, "http://steamcommunity.com");
var result = JsonConvert.DeserializeObject<GetTradeOfferAPI>(response);
if (result.Response != null && result.Response.Offer != null)
{
return result.Response;
}
return null;
}
/// <summary>
/// Get list of trade offers from API
/// </summary>
/// <param name="getActive">Set this to true to get active-only trade offers</param>
/// <returns>list of trade offers</returns>
public List<TradeOffer> GetTradeOffers(bool getActive = false)
{
var temp = new List<TradeOffer>();
var url = "https://api.steampowered.com/IEconService/GetTradeOffers/v1/?key=" + AccountApiKey + "&get_sent_offers=1&get_received_offers=1";
if (getActive)
{
url += "&active_only=1&time_historical_cutoff=" + (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
}
else
{
url += "&active_only=0";
}
var response = RetryWebRequest(SteamWeb, url, "GET", null, false, "http://steamcommunity.com");
var json = JsonConvert.DeserializeObject<dynamic>(response);
var sentTradeOffers = json.response.trade_offers_sent;
if (sentTradeOffers != null)
{
foreach (var tradeOffer in sentTradeOffers)
{
TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer));
temp.Add(tempTrade);
}
}
var receivedTradeOffers = json.response.trade_offers_received;
if (receivedTradeOffers != null)
{
foreach (var tradeOffer in receivedTradeOffers)
{
TradeOffer tempTrade = JsonConvert.DeserializeObject<TradeOffer>(Convert.ToString(tradeOffer));
temp.Add(tempTrade);
}
}
return temp;
}
public enum TradeOfferState
{
Invalid = 1,
Active = 2,
Accepted = 3,
Countered = 4,
Expired = 5,
Canceled = 6,
Declined = 7,
InvalidItems = 8,
NeedsConfirmation = 9,
CanceledBySecondFactor = 10,
InEscrow = 11
}
public enum TradeOfferConfirmationMethod
{
Invalid = 0,
Email = 1,
MobileApp = 2
}
public class GetTradeOfferAPI
{
[JsonProperty("response")]
public GetTradeOfferResponse Response { get; set; }
public class GetTradeOfferResponse
{
[JsonProperty("offer")]
public TradeOffer Offer { get; set; }
[JsonProperty("descriptions")]
public TradeOfferDescriptions[] Descriptions { get; set; }
}
}
public class TradeOffer
{
[JsonProperty("tradeofferid")]
public ulong Id { get; set; }
[JsonProperty("accountid_other")]
public ulong OtherAccountId { get; set; }
public ulong OtherSteamId
{
get
{
return new SteamID(String.Format("STEAM_0:{0}:{1}", OtherAccountId & 1, OtherAccountId >> 1)).ConvertToUInt64();
}
set
{
OtherSteamId = value;
}
}
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("expiration_time")]
public ulong ExpirationTime { get; set; }
[JsonProperty("trade_offer_state")]
private int state { get; set; }
public TradeOfferState State { get { return (TradeOfferState)state; } set { state = (int)value; } }
[JsonProperty("items_to_give")]
private CEconAsset[] itemsToGive { get; set; }
public CEconAsset[] ItemsToGive
{
get
{
if (itemsToGive == null)
{
return new CEconAsset[0];
}
return itemsToGive;
}
set
{
itemsToGive = value;
}
}
[JsonProperty("items_to_receive")]
private CEconAsset[] itemsToReceive { get; set; }
public CEconAsset[] ItemsToReceive
{
get
{
if (itemsToReceive == null)
{
return new CEconAsset[0];
}
return itemsToReceive;
}
set
{
itemsToReceive = value;
}
}
[JsonProperty("is_our_offer")]
public bool IsOurOffer { get; set; }
[JsonProperty("time_created")]
public int TimeCreated { get; set; }
[JsonProperty("time_updated")]
public int TimeUpdated { get; set; }
[JsonProperty("from_real_time_trade")]
public bool FromRealTimeTrade { get; set; }
[JsonProperty("escrow_end_date")]
public int EscrowEndDate { get; set; }
[JsonProperty("confirmation_method")]
private int confirmationMethod { get; set; }
public TradeOfferConfirmationMethod ConfirmationMethod { get { return (TradeOfferConfirmationMethod)confirmationMethod; } set { confirmationMethod = (int)value; } }
public class CEconAsset
{
[JsonProperty("appid")]
public int AppId { get; set; }
[JsonProperty("contextid")]
public ulong ContextId { get; set; }
[JsonProperty("assetid")]
public ulong AssetId { get; set; }
[JsonProperty("currencyid")]
public ulong CurrencyId { get; set; }
[JsonProperty("classid")]
public ulong ClassId { get; set; }
[JsonProperty("instanceid")]
public ulong InstanceId { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("missing")]
public bool IsMissing { get; set; }
}
}
public class TradeOfferDescriptions
{
[JsonProperty("appid")]
public int AppId { get; set; }
[JsonProperty("classid")]
public long ClassId { get; set; }
[JsonProperty("instanceid")]
public long InstanceId { get; set; }
[JsonProperty("currency")]
public bool IsCurrency { get; set; }
[JsonProperty("background_color")]
public string BackgroundColor { get; set; }
[JsonProperty("icon_url")]
public string IconUrl { get; set; }
[JsonProperty("icon_url_large")]
public string IconUrlLarge { get; set; }
[JsonProperty("descriptions")]
public DescriptionsData[] Descriptions { get; set; }
[JsonProperty("tradable")]
public bool IsTradable { get; set; }
[JsonProperty("actions")]
public ActionsData[] Actions { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("name_color")]
public string NameColor { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("market_name")]
public string MarketName { get; set; }
[JsonProperty("market_hash_name")]
public string MarketHashName { get; set; }
[JsonProperty("market_actions")]
public MarketActionsData[] MarketActions { get; set; }
[JsonProperty("commodity")]
public bool IsCommodity { get; set; }
public class DescriptionsData
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class ActionsData
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class MarketActionsData
{
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}
/// <summary>
/// Manually validate if a trade offer went through by checking /inventoryhistory/
/// </summary>
/// <param name="tradeOffer">A 'TradeOffer' object</param>
/// <returns>True if the trade offer was successfully accepted, false if otherwise</returns>
public bool ValidateTradeAccept(TradeOffer tradeOffer)
{
try
{
var history = GetTradeHistory();
foreach (var completedTrade in history)
{
if (tradeOffer.ItemsToGive.Length == completedTrade.GivenItems.Count && tradeOffer.ItemsToReceive.Length == completedTrade.ReceivedItems.Count)
{
var numFoundGivenItems = 0;
var numFoundReceivedItems = 0;
var foundItemIds = new List<ulong>();
foreach (var historyItem in completedTrade.GivenItems)
{
foreach (var tradeOfferItem in tradeOffer.ItemsToGive)
{
if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
{
if (!foundItemIds.Contains(tradeOfferItem.AssetId))
{
foundItemIds.Add(tradeOfferItem.AssetId);
numFoundGivenItems++;
}
}
}
}
foreach (var historyItem in completedTrade.ReceivedItems)
{
foreach (var tradeOfferItem in tradeOffer.ItemsToReceive)
{
if (tradeOfferItem.ClassId == historyItem.ClassId && tradeOfferItem.InstanceId == historyItem.InstanceId)
{
if (!foundItemIds.Contains(tradeOfferItem.AssetId))
{
foundItemIds.Add(tradeOfferItem.AssetId);
numFoundReceivedItems++;
}
}
}
}
if (numFoundGivenItems == tradeOffer.ItemsToGive.Length && numFoundReceivedItems == tradeOffer.ItemsToReceive.Length)
{
return true;
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error validating trade:");
Console.WriteLine(ex);
}
return false;
}
/// <summary>
/// Retrieves completed trades from /inventoryhistory/
/// </summary>
/// <param name="limit">Max number of trades to retrieve</param>
/// <returns>A List of 'TradeHistory' objects</returns>
public List<TradeHistory> GetTradeHistory(int limit = 0, int numPages = 1)
{
var tradeHistoryPages = new Dictionary<int, TradeHistory[]>();
for (int i = 0; i < numPages; i++)
{
var tradeHistoryPageList = new TradeHistory[30];
try
{
var url = "http://steamcommunity.com/profiles/" + BotId.ConvertToUInt64() + "/inventoryhistory/?p=" + i;
var html = RetryWebRequest(SteamWeb, url, "GET", null);
// TODO: handle rgHistoryCurrency as well
Regex reg = new Regex("rgHistoryInventory = (.*?)};");
Match m = reg.Match(html);
if (m.Success)
{
var json = m.Groups[1].Value + "}";
var schemaResult = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<ulong, Dictionary<ulong, TradeHistory.HistoryItem>>>>(json);
var trades = new Regex("HistoryPageCreateItemHover\\((.*?)\\);");
var tradeMatches = trades.Matches(html);
foreach (Match match in tradeMatches)
{
if (match.Success)
{
var historyString = match.Groups[1].Value.Replace("'", "").Replace(" ", "");
var split = historyString.Split(',');
var tradeString = split[0];
var tradeStringSplit = tradeString.Split('_');
var tradeNum = Convert.ToInt32(tradeStringSplit[0].Replace("trade", ""));
if (limit > 0 && tradeNum >= limit) break;
if (tradeHistoryPageList[tradeNum] == null)
{
tradeHistoryPageList[tradeNum] = new TradeHistory();
}
var tradeHistoryItem = tradeHistoryPageList[tradeNum];
var appId = Convert.ToInt32(split[1]);
var contextId = Convert.ToUInt64(split[2]);
var itemId = Convert.ToUInt64(split[3]);
var amount = Convert.ToInt32(split[4]);
var historyItem = schemaResult[appId][contextId][itemId];
if (historyItem.OwnerId == 0)
tradeHistoryItem.ReceivedItems.Add(historyItem);
else
tradeHistoryItem.GivenItems.Add(historyItem);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error retrieving trade history:");
Console.WriteLine(ex);
}
tradeHistoryPages.Add(i, tradeHistoryPageList);
}
var tradeHistoryList = new List<TradeHistory>();
foreach (var tradeHistoryPage in tradeHistoryPages.Values)
{
foreach (var tradeHistory in tradeHistoryPage)
{
tradeHistoryList.Add(tradeHistory);
}
}
return tradeHistoryList;
}
public class TradeHistory
{
public List<HistoryItem> ReceivedItems { get; set; }
public List<HistoryItem> GivenItems { get; set; }
public TradeHistory()
{
ReceivedItems = new List<HistoryItem>();
GivenItems = new List<HistoryItem>();
}
public class HistoryItem
{
private Trade.TradeAsset tradeAsset = null;
public Trade.TradeAsset TradeAsset
{
get
{
if (tradeAsset == null)
{
tradeAsset = new Trade.TradeAsset(AppId, ContextId, Id, Amount);
}
return tradeAsset;
}
set
{
tradeAsset = value;
}
}
[JsonProperty("id")]
public ulong Id { get; set; }
[JsonProperty("contextid")]
public ulong ContextId { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
[JsonProperty("owner")]
private dynamic owner { get; set; }
public ulong OwnerId
{
get
{
ulong ownerId = 0;
ulong.TryParse(Convert.ToString(owner), out ownerId);
return ownerId;
}
set
{
owner = value.ToString();
}
}
[JsonProperty("appid")]
public int AppId { get; set; }
[JsonProperty("classid")]
public ulong ClassId { get; set; }
[JsonProperty("instanceid")]
public ulong InstanceId { get; set; }
[JsonProperty("is_currency")]
public bool IsCurrency { get; set; }
[JsonProperty("icon_url")]
public string IconUrl { get; set; }
[JsonProperty("icon_url_large")]
public string IconUrlLarge { get; set; }
[JsonProperty("icon_drag_url")]
public string IconDragUrl { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("market_hash_name")]
public string MarketHashName { get; set; }
[JsonProperty("market_name")]
public string MarketName { get; set; }
[JsonProperty("name_color")]
public string NameColor { get; set; }
[JsonProperty("background_color")]
public string BackgroundColor { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("tradable")]
public bool IsTradable { get; set; }
[JsonProperty("marketable")]
public bool IsMarketable { get; set; }
[JsonProperty("commodity")]
public bool IsCommodity { get; set; }
[JsonProperty("market_tradable_restriction")]
public int MarketTradableRestriction { get; set; }
[JsonProperty("market_marketable_restriction")]
public int MarketMarketableRestriction { get; set; }
[JsonProperty("fraudwarnings")]
public dynamic FraudWarnings { get; set; }
[JsonProperty("descriptions")]
private dynamic descriptions { get; set; }
public DescriptionsData[] Descriptions
{
get
{
if (!string.IsNullOrEmpty(Convert.ToString(descriptions)))
{
try
{
return JsonConvert.DeserializeObject<DescriptionsData[]>(descriptions);
}
catch
{
}
}
return new DescriptionsData[0];
}
set
{
descriptions = JsonConvert.SerializeObject(value);
}
}
[JsonProperty("actions")]
private dynamic actions { get; set; }
public ActionsData[] Actions
{
get
{
if (!string.IsNullOrEmpty(Convert.ToString(actions)))
{
try
{
return JsonConvert.DeserializeObject<ActionsData[]>(actions);
}
catch
{
}
}
return new ActionsData[0];
}
set
{
descriptions = JsonConvert.SerializeObject(value);
}
}
[JsonProperty("tags")]
public TagsData[] Tags { get; set; }
[JsonProperty("app_data")]
public dynamic AppData { get; set; }
public class DescriptionsData
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
[JsonProperty("color")]
public string Color { get; set; }
[JsonProperty("app_data")]
public dynamic AppData { get; set; }
}
public class ActionsData
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("link")]
public string Link { get; set; }
}
public class TagsData
{
[JsonProperty("internal_name")]
public string InternalName { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("category_name")]
public string CategoryName { get; set; }
[JsonProperty("color")]
public string Color { get; set; }
}
}
}
public void AddPendingTradeOfferToList(ulong tradeOfferId)
{
OurPendingTradeOffers.Add(tradeOfferId);
}
private void RemovePendingTradeOfferFromList(ulong tradeOfferId)
{
OurPendingTradeOffers.Remove(tradeOfferId);
}
public void StopCheckingPendingTradeOffers()
{
this.ShouldCheckPendingTradeOffers = false;
}
private void CheckPendingTradeOffers()
{
new Thread(() =>
{
while (ShouldCheckPendingTradeOffers)
{
var tradeOffers = GetTradeOffers(true);
foreach (var tradeOffer in tradeOffers)
{
if (tradeOffer.IsOurOffer)
{
if (!OurPendingTradeOffers.Contains(tradeOffer.Id))
{
OurPendingTradeOffers.Add(tradeOffer.Id);
}
}
else if (!tradeOffer.IsOurOffer && !ReceivedPendingTradeOffers.Contains(tradeOffer.Id))
{
var args = new TradeOfferEventArgs();
args.TradeOffer = tradeOffer;
if (tradeOffer.State == TradeOfferState.Active)
{
ReceivedPendingTradeOffers.Add(tradeOffer.Id);
OnTradeOfferReceived(args);
}
}
}
Thread.Sleep(TradeOfferRefreshRate);
}
}).Start();
while (ShouldCheckPendingTradeOffers)
{
var checkingThreads = new List<Thread>();
foreach (var tradeOfferId in OurPendingTradeOffers.ToList())
{
var thread = new Thread(() =>
{
var pendingTradeOffer = GetTradeOffer(tradeOfferId);
if (pendingTradeOffer != null)
{
if (pendingTradeOffer.Offer.State != TradeOfferState.Active)
{
var args = new TradeOfferEventArgs();
args.TradeOffer = pendingTradeOffer.Offer;
// check if trade offer has been accepted/declined, or items unavailable (manually validate)
if (pendingTradeOffer.Offer.State == TradeOfferState.Accepted)
{
// fire event
OnTradeOfferAccepted(args);
// remove from list
OurPendingTradeOffers.Remove(pendingTradeOffer.Offer.Id);
}
else if (pendingTradeOffer.Offer.State != TradeOfferState.Active && pendingTradeOffer.Offer.State != TradeOfferState.Accepted)
{
if (pendingTradeOffer.Offer.State == TradeOfferState.NeedsConfirmation)
{
// fire event
OnTradeOfferNeedsConfirmation(args);
}
else if (pendingTradeOffer.Offer.State == TradeOfferState.Invalid || pendingTradeOffer.Offer.State == TradeOfferState.InvalidItems)
{
// fire event
OnTradeOfferInvalid(args);
}
else if (pendingTradeOffer.Offer.State != TradeOfferState.InEscrow)
{
// fire event
OnTradeOfferDeclined(args);
}
if (pendingTradeOffer.Offer.State != TradeOfferState.InEscrow)
{
// remove from list only if not in escrow
OurPendingTradeOffers.Remove(pendingTradeOffer.Offer.Id);
}
}
}
}
});
checkingThreads.Add(thread);
thread.Start();
}
foreach (var thread in checkingThreads)
{
thread.Join();
}
Thread.Sleep(TradeOfferRefreshRate);
}
}
protected virtual void OnTradeOfferReceived(TradeOfferEventArgs e)
{
if (!HandledTradeOffers.Contains(e.TradeOffer.Id))
{
TradeOfferStatusEventHandler handler = TradeOfferReceived;
if (handler != null)
{
handler(this, e);
}
HandledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferAccepted(TradeOfferEventArgs e)
{
if (!HandledTradeOffers.Contains(e.TradeOffer.Id))
{
TradeOfferStatusEventHandler handler = TradeOfferAccepted;
if (handler != null)
{
handler(this, e);
}
HandledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferDeclined(TradeOfferEventArgs e)
{
if (!HandledTradeOffers.Contains(e.TradeOffer.Id))
{
TradeOfferStatusEventHandler handler = TradeOfferDeclined;
if (handler != null)
{
handler(this, e);
}
HandledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferInvalid(TradeOfferEventArgs e)
{
if (!HandledTradeOffers.Contains(e.TradeOffer.Id))
{
TradeOfferStatusEventHandler handler = TradeOfferInvalid;
if (handler != null)
{
handler(this, e);
}
HandledTradeOffers.Add(e.TradeOffer.Id);
}
}
protected virtual void OnTradeOfferNeedsConfirmation(TradeOfferEventArgs e)
{
if (!AwaitingConfirmationTradeOffers.Contains(e.TradeOffer.Id))
{
TradeOfferStatusEventHandler handler = TradeOfferNeedsConfirmation;
if (handler != null)
{
handler(this, e);
}
AwaitingConfirmationTradeOffers.Add(e.TradeOffer.Id);
}
}
public event TradeOfferStatusEventHandler TradeOfferReceived;
public event TradeOfferStatusEventHandler TradeOfferAccepted;
public event TradeOfferStatusEventHandler TradeOfferDeclined;
public event TradeOfferStatusEventHandler TradeOfferInvalid;
public event TradeOfferStatusEventHandler TradeOfferNeedsConfirmation;
public class TradeOfferEventArgs : EventArgs
{
public TradeOffer TradeOffer { get; set; }
}
public delegate void TradeOfferStatusEventHandler(Object sender, TradeOfferEventArgs e);
private static string RetryWebRequest(SteamWeb steamWeb, string url, string method, NameValueCollection data, bool ajax = false, string referer = "")
{
for (int i = 0; i < 10; i++)
{
try
{
var response = steamWeb.Request(url, method, data, ajax, referer);
using (System.IO.Stream responseStream = response.GetResponseStream())
{
using (var reader = new System.IO.StreamReader(responseStream))
{
string result = reader.ReadToEnd();
if (string.IsNullOrEmpty(result))
{
Console.WriteLine("Web request failed (status: {0}). Retrying...", response.StatusCode);
Thread.Sleep(1000);
}
else
{
return result;
}
}
}
}
catch (WebException ex)
{
try
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code: {0}, {1}", (int)((HttpWebResponse)ex.Response).StatusCode, ((HttpWebResponse)ex.Response).StatusDescription);
}
Console.WriteLine("Error: {0}", new System.IO.StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
}
catch
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
return "";
}
}
}
| |
using J2N.Threading.Atomic;
using J2N.Runtime.CompilerServices;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 BinaryDocValues = Lucene.Net.Index.BinaryDocValues;
using IBits = Lucene.Net.Util.IBits;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using NumericDocValues = Lucene.Net.Index.NumericDocValues;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using SortedDocValues = Lucene.Net.Index.SortedDocValues;
using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues;
using StringHelper = Lucene.Net.Util.StringHelper;
/// <summary>
/// Reads Lucene 3.x norms format and exposes it via <see cref="Index.DocValues"/> API.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Only for reading existing 3.x indexes")]
internal class Lucene3xNormsProducer : DocValuesProducer
{
/// <summary>
/// Norms header placeholder. </summary>
internal static readonly sbyte[] NORMS_HEADER = { (sbyte)'N', (sbyte)'R', (sbyte)'M', -1 };
/// <summary>
/// Extension of norms file. </summary>
internal const string NORMS_EXTENSION = "nrm";
/// <summary>
/// Extension of separate norms file. </summary>
internal const string SEPARATE_NORMS_EXTENSION = "s";
private readonly IDictionary<string, NormsDocValues> norms = new Dictionary<string, NormsDocValues>();
// any .nrm or .sNN files we have open at any time.
// TODO: just a list, and double-close() separate norms files?
internal readonly ISet<IndexInput> openFiles = new JCG.HashSet<IndexInput>(IdentityEqualityComparer<IndexInput>.Default);
// points to a singleNormFile
internal IndexInput singleNormStream;
internal readonly int maxdoc;
private readonly AtomicInt64 ramBytesUsed;
// note: just like segmentreader in 3.x, we open up all the files here (including separate norms) up front.
// but we just don't do any seeks or reading yet.
public Lucene3xNormsProducer(Directory dir, SegmentInfo info, FieldInfos fields, IOContext context)
{
Directory separateNormsDir = info.Dir; // separate norms are never inside CFS
maxdoc = info.DocCount;
string segmentName = info.Name;
bool success = false;
try
{
long nextNormSeek = NORMS_HEADER.Length; //skip header (header unused for now)
foreach (FieldInfo fi in fields)
{
if (fi.HasNorms)
{
string fileName = GetNormFilename(info, fi.Number);
Directory d = HasSeparateNorms(info, fi.Number) ? separateNormsDir : dir;
// singleNormFile means multiple norms share this file
bool singleNormFile = IndexFileNames.MatchesExtension(fileName, NORMS_EXTENSION);
IndexInput normInput = null;
long normSeek;
if (singleNormFile)
{
normSeek = nextNormSeek;
if (singleNormStream == null)
{
singleNormStream = d.OpenInput(fileName, context);
openFiles.Add(singleNormStream);
}
// All norms in the .nrm file can share a single IndexInput since
// they are only used in a synchronized context.
// If this were to change in the future, a clone could be done here.
normInput = singleNormStream;
}
else
{
normInput = d.OpenInput(fileName, context);
openFiles.Add(normInput);
// if the segment was created in 3.2 or after, we wrote the header for sure,
// and don't need to do the sketchy file size check. otherwise, we check
// if the size is exactly equal to maxDoc to detect a headerless file.
// NOTE: remove this check in Lucene 5.0!
string version = info.Version;
bool isUnversioned = (version == null || StringHelper.VersionComparer.Compare(version, "3.2") < 0) && normInput.Length == maxdoc;
if (isUnversioned)
{
normSeek = 0;
}
else
{
normSeek = NORMS_HEADER.Length;
}
}
NormsDocValues norm = new NormsDocValues(this, normInput, normSeek);
norms[fi.Name] = norm;
nextNormSeek += maxdoc; // increment also if some norms are separate
}
}
// TODO: change to a real check? see LUCENE-3619
if (Debugging.AssertsEnabled) Debugging.Assert(singleNormStream == null || nextNormSeek == singleNormStream.Length, () => singleNormStream != null ? "len: " + singleNormStream.Length + " expected: " + nextNormSeek : "null");
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(openFiles);
}
}
ramBytesUsed = new AtomicInt64();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(openFiles);
}
finally
{
norms.Clear();
openFiles.Clear();
}
}
}
private static string GetNormFilename(SegmentInfo info, int number)
{
if (HasSeparateNorms(info, number))
{
long gen = Convert.ToInt64(info.GetAttribute(Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + number), CultureInfo.InvariantCulture);
return IndexFileNames.FileNameFromGeneration(info.Name, SEPARATE_NORMS_EXTENSION + number, gen);
}
else
{
// single file for all norms
return IndexFileNames.SegmentFileName(info.Name, "", NORMS_EXTENSION);
}
}
private static bool HasSeparateNorms(SegmentInfo info, int number)
{
string v = info.GetAttribute(Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + number);
if (v == null)
{
return false;
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(Convert.ToInt64(v, CultureInfo.InvariantCulture) != SegmentInfo.NO);
return true;
}
}
// holds a file+offset pointing to a norms, and lazy-loads it
// to a singleton NumericDocValues instance
private sealed class NormsDocValues
{
private readonly Lucene3xNormsProducer outerInstance;
private readonly IndexInput file;
private readonly long offset;
private NumericDocValues instance;
public NormsDocValues(Lucene3xNormsProducer outerInstance, IndexInput normInput, long normSeek)
{
this.outerInstance = outerInstance;
this.file = normInput;
this.offset = normSeek;
}
internal NumericDocValues Instance
{
get
{
lock (this)
{
if (instance == null)
{
var bytes = new byte[outerInstance.maxdoc];
// some norms share fds
lock (file)
{
file.Seek(offset);
file.ReadBytes(bytes, 0, bytes.Length, false);
}
// we are done with this file
if (file != outerInstance.singleNormStream)
{
outerInstance.openFiles.Remove(file);
file.Dispose();
}
outerInstance.ramBytesUsed.AddAndGet(RamUsageEstimator.SizeOf(bytes));
instance = new NumericDocValuesAnonymousInnerClassHelper(this, bytes);
}
return instance;
}
}
}
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
private readonly byte[] bytes;
public NumericDocValuesAnonymousInnerClassHelper(NormsDocValues outerInstance, byte[] bytes)
{
this.bytes = bytes;
}
public override long Get(int docID)
{
return bytes[docID];
}
}
}
public override NumericDocValues GetNumeric(FieldInfo field)
{
var dv = norms[field.Name];
if (Debugging.AssertsEnabled) Debugging.Assert(dv != null);
return dv.Instance;
}
public override BinaryDocValues GetBinary(FieldInfo field)
{
throw new InvalidOperationException();
}
public override SortedDocValues GetSorted(FieldInfo field)
{
throw new InvalidOperationException();
}
public override SortedSetDocValues GetSortedSet(FieldInfo field)
{
throw new InvalidOperationException();
}
public override IBits GetDocsWithField(FieldInfo field)
{
throw new InvalidOperationException();
}
public override long RamBytesUsed() => ramBytesUsed;
public override void CheckIntegrity() { }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using Aga.Controls.Tree;
using HtmlHelp;
using HtmlHelp.UIComponents;
using System.Collections;
using System.Collections.ObjectModel;
using System.Drawing;
namespace ActiveWare
{
public partial class HelpBrowser : UserControl
{
private TreeModel _model;
private HtmlHelpSystem currentHelpSystem = null;
private PleaseWait pleaseWait = null;
private ArrayList helpSystems;
public event TocSelectedEventHandler TocSelected;
private Collection<Node> chmNode;
public HelpBrowser()
{
InitializeComponent();
_model = new TreeModel();
_tree.Model = _model;
helpSystems = new ArrayList();
}
public void AddHelp(string title, HtmlHelpSystem helpFile)
{
helpSystems.Add(helpFile);
Node node = new Node(title);
node.Image = hhImages.Images[3];
node.Object = helpFile;
_model.Nodes.Add(node);
}
public void AddHelp(string title, string fileName)
{
HtmlHelpSystem helpFile = new HtmlHelpSystem();
helpFile.OpenFile(fileName);
helpSystems.Add(helpFile);
/*
phpHelpFile =
mysqlHelpFile = new HtmlHelpSystem();
phpHelpFile.OpenFile();
mysqlHelpFile.OpenFile("help/mysql_5.0_en.chm");
*/
Node node = new Node(title);
node.Image = hhImages.Images[3];
node.Object = helpFile;
_model.Nodes.Add(node);
}
/// <summary>
/// Fireing the on selected event
/// </summary>
/// <param name="e">event parameters</param>
protected virtual void OnTocSelected(TocEventArgs e)
{
if (TocSelected != null)
{
TocSelected(this, e);
}
}
/// <summary>
/// Recursively builds the toc tree and fills the treeview
/// </summary>
/// <param name="tocItems">list of toc-items</param>
/// <param name="col">treenode collection of the current level</param>
/// <param name="filter">information type/category filter</param>
private void BuildTOC(ArrayList tocItems, Collection<Node> nodes)
{
for (int i = 0; i < tocItems.Count; i++)
{
TOCItem curItem = (TOCItem)tocItems[i];
Node newNode = new Node(curItem.Name);
newNode.Object = curItem;
if (curItem.Children.Count > 0)
newNode.Image = hhImages.Images[0];
else
newNode.Image = hhImages.Images[2];
//newNode.Image = hhImages.Images[curItem.ImageIndex];
nodes.Add(newNode);
if (curItem.Children.Count > 0)
{
BuildTOC(curItem.Children, newNode.Nodes);
}
// check if we have a book/folder which doesn't have any children
// after applied filter.
if ((curItem.Children.Count > 0) && (newNode.Nodes.Count <= 0))
{
// check if the item has a local value
// if not, this don't display this item in the tree
if (curItem.Local.Length > 0)
{
nodes.Add(newNode);
}
}
else
{
nodes.Add(newNode);
}
}
}
private void _tree_Expanding(object sender, TreeViewAdvEventArgs e)
{
if (e.Node != null)
{
if ((e.Node.Children.Count > 0) && (e.Node.Parent != null) && (e.Node.Parent.Parent != null))
{
if (e.Node.Tag is Node)
(e.Node.Tag as Node).Image = hhImages.Images[1];
}
if (e.Node.Tag != null)
{
if ((e.Node.Tag as Node).Object != null)
{
if ((e.Node.Tag as Node).Nodes.Count == 0)
{
bool createCache = false;
foreach (var item in helpSystems)
{
HtmlHelpSystem help = (item as HtmlHelpSystem);
if ((e.Node.Tag as Node).Object == help)
createCache = true;
}
if (createCache)
{
_tree.LoadOnDemand = false;
currentHelpSystem = ((e.Node.Tag as Node).Object as HtmlHelpSystem);
chmNode = (e.Node.Tag as Node).Nodes;
backgroundWorker.RunWorkerAsync();
pleaseWait = new PleaseWait();
pleaseWait.ShowDialog();
}
}
}
}
}
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
_tree.BeginUpdate();
BuildTOC(currentHelpSystem.TableOfContents.TOC, chmNode);
_tree.EndUpdate();
backgroundWorker.CancelAsync();
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pleaseWait.Close();
}
private void _tree_Collapsing(object sender, TreeViewAdvEventArgs e)
{
if (e.Node != null)
{
if ((e.Node.Children.Count > 0) && (e.Node.Parent != null) && (e.Node.Parent.Parent != null))
{
if (e.Node.Tag is Node)
(e.Node.Tag as Node).Image = hhImages.Images[0];
}
}
}
private void button1_Click(object sender, EventArgs e)
{
//IndexItem item = phpHelpFile.Index.SearchIndex("echo?", IndexType.KeywordLinks);
//Console.WriteLine(item.IndentKeyWord);
}
private void _tree_SelectionChanged(object sender, EventArgs e)
{
if (_tree.SelectedNode != null)
if (_tree.SelectedNode.Tag != null)
if ((_tree.SelectedNode.Tag is Node))
if ((_tree.SelectedNode.Tag as Node).Object is TOCItem)
OnTocSelected(new TocEventArgs((TOCItem)((_tree.SelectedNode.Tag as Node).Object)));
}
private void _tree_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawRectangle(new Pen(Color.Red), new Rectangle(0, 0, this.Width - 1, this.Height - 1));
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* 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.
******************************************************************************/
/**
* Functions used for computing contact points, distance queries, and TOI queries. Collision methods
* are non-static for pooling speed, retrieve a collision object from the {@link SingletonPool}.
* Should not be constructed.
*
* @author Daniel Murphy
*/
using System.Diagnostics;
using SharpBox2D.Collision.Shapes;
using SharpBox2D.Common;
using SharpBox2D.Pooling;
namespace SharpBox2D.Collision
{
public class Collision
{
public static readonly int NULL_FEATURE = int.MaxValue;
private IWorldPool pool;
public Collision(IWorldPool argPool)
{
incidentEdge[0] = new ClipVertex();
incidentEdge[1] = new ClipVertex();
clipPoints1[0] = new ClipVertex();
clipPoints1[1] = new ClipVertex();
clipPoints2[0] = new ClipVertex();
clipPoints2[1] = new ClipVertex();
pool = argPool;
}
private DistanceInput input = new DistanceInput();
private SimplexCache cache = new SimplexCache();
private DistanceOutput output = new DistanceOutput();
/**
* Determine if two generic shapes overlap.
*
* @param shapeA
* @param shapeB
* @param xfA
* @param xfB
* @return
*/
public bool testOverlap(Shape shapeA, int indexA, Shape shapeB, int indexB,
Transform xfA, Transform xfB)
{
input.proxyA.set(shapeA, indexA);
input.proxyB.set(shapeB, indexB);
input.transformA.set(xfA);
input.transformB.set(xfB);
input.useRadii = true;
cache.count = 0;
pool.getDistance().distance(output, cache, input);
// djm note: anything significant about 10.0f?
return output.distance < 10.0f*Settings.EPSILON;
}
/**
* Compute the point states given two manifolds. The states pertain to the transition from
* manifold1 to manifold2. So state1 is either persist or remove while state2 is either add or
* persist.
*
* @param state1
* @param state2
* @param manifold1
* @param manifold2
*/
public static void getPointStates(PointState[] state1, PointState[] state2,
Manifold manifold1, Manifold manifold2)
{
for (int i = 0; i < Settings.maxManifoldPoints; i++)
{
state1[i] = PointState.NULL_STATE;
state2[i] = PointState.NULL_STATE;
}
// Detect persists and removes.
for (int i = 0; i < manifold1.pointCount; i++)
{
ContactID id = manifold1.points[i].id;
state1[i] = PointState.REMOVE_STATE;
for (int j = 0; j < manifold2.pointCount; j++)
{
if (manifold2.points[j].id.isEqual(id))
{
state1[i] = PointState.PERSIST_STATE;
break;
}
}
}
// Detect persists and adds
for (int i = 0; i < manifold2.pointCount; i++)
{
ContactID id = manifold2.points[i].id;
state2[i] = PointState.ADD_STATE;
for (int j = 0; j < manifold1.pointCount; j++)
{
if (manifold1.points[j].id.isEqual(id))
{
state2[i] = PointState.PERSIST_STATE;
break;
}
}
}
}
/**
* Clipping for contact manifolds. Sutherland-Hodgman clipping.
*
* @param vOut
* @param vIn
* @param normal
* @param offset
* @return
*/
public static int clipSegmentToLine(ClipVertex[] vOut, ClipVertex[] vIn,
Vec2 normal, float offset, int vertexIndexA)
{
// Start with no output points
int numOut = 0;
ClipVertex vIn0 = vIn[0];
ClipVertex vIn1 = vIn[1];
Vec2 vIn0v = vIn0.v;
Vec2 vIn1v = vIn1.v;
// Calculate the distance of end points to the line
float distance0 = Vec2.dot(normal, vIn0v) - offset;
float distance1 = Vec2.dot(normal, vIn1v) - offset;
// If the points are behind the plane
if (distance0 <= 0.0f)
{
vOut[numOut++].set(vIn0);
}
if (distance1 <= 0.0f)
{
vOut[numOut++].set(vIn1);
}
// If the points are on different sides of the plane
if (distance0*distance1 < 0.0f)
{
// Find intersection point of edge and plane
float interp = distance0/(distance0 - distance1);
ClipVertex vOutNO = vOut[numOut];
// vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v);
vOutNO.v.x = vIn0v.x + interp*(vIn1v.x - vIn0v.x);
vOutNO.v.y = vIn0v.y + interp*(vIn1v.y - vIn0v.y);
// VertexA is hitting edgeB.
vOutNO.id.indexA = (byte) vertexIndexA;
vOutNO.id.indexB = vIn0.id.indexB;
vOutNO.id.typeA = (byte) ContactID.Type.VERTEX;
vOutNO.id.typeB = (byte) ContactID.Type.FACE;
++numOut;
}
return numOut;
}
// #### COLLISION STUFF (not from collision.h or collision.cpp) ####
// djm pooling
private static Vec2 d = new Vec2();
/**
* Compute the collision manifold between two circles.
*
* @param manifold
* @param circle1
* @param xfA
* @param circle2
* @param xfB
*/
public void collideCircles(Manifold manifold, CircleShape circle1,
Transform xfA, CircleShape circle2, Transform xfB)
{
manifold.pointCount = 0;
// before inline:
// Transform.mulToOut(xfA, circle1.m_p, pA);
// Transform.mulToOut(xfB, circle2.m_p, pB);
// d.set(pB).subLocal(pA);
// float distSqr = d.x * d.x + d.y * d.y;
// after inline:
Vec2 circle1p = circle1.m_p;
Vec2 circle2p = circle2.m_p;
float pAx = (xfA.q.c*circle1p.x - xfA.q.s*circle1p.y) + xfA.p.x;
float pAy = (xfA.q.s*circle1p.x + xfA.q.c*circle1p.y) + xfA.p.y;
float pBx = (xfB.q.c*circle2p.x - xfB.q.s*circle2p.y) + xfB.p.x;
float pBy = (xfB.q.s*circle2p.x + xfB.q.c*circle2p.y) + xfB.p.y;
float dx = pBx - pAx;
float dy = pBy - pAy;
float distSqr = dx*dx + dy*dy;
// end inline
float radius = circle1.m_radius + circle2.m_radius;
if (distSqr > radius*radius)
{
return;
}
manifold.type = ManifoldType.CIRCLES;
manifold.localPoint.set(circle1p);
manifold.localNormal.setZero();
manifold.pointCount = 1;
manifold.points[0].localPoint.set(circle2p);
manifold.points[0].id.zero();
}
// djm pooling, and from above
/**
* Compute the collision manifold between a polygon and a circle.
*
* @param manifold
* @param polygon
* @param xfA
* @param circle
* @param xfB
*/
public void collidePolygonAndCircle(Manifold manifold, PolygonShape polygon,
Transform xfA, CircleShape circle, Transform xfB)
{
manifold.pointCount = 0;
// Vec2 v = circle.m_p;
// Compute circle position in the frame of the polygon.
// before inline:
// Transform.mulToOutUnsafe(xfB, circle.m_p, c);
// Transform.mulTransToOut(xfA, c, cLocal);
// float cLocalx = cLocal.x;
// float cLocaly = cLocal.y;
// after inline:
Vec2 circlep = circle.m_p;
Rot xfBq = xfB.q;
Rot xfAq = xfA.q;
float cx = (xfBq.c*circlep.x - xfBq.s*circlep.y) + xfB.p.x;
float cy = (xfBq.s*circlep.x + xfBq.c*circlep.y) + xfB.p.y;
float px = cx - xfA.p.x;
float py = cy - xfA.p.y;
float cLocalx = (xfAq.c*px + xfAq.s*py);
float cLocaly = (-xfAq.s*px + xfAq.c*py);
// end inline
// Find the min separating edge.
int normalIndex = 0;
float separation = -float.MaxValue;
float radius = polygon.m_radius + circle.m_radius;
int vertexCount = polygon.m_count;
float s;
Vec2[] vertices = polygon.m_vertices;
Vec2[] normals = polygon.m_normals;
for (int i = 0; i < vertexCount; i++)
{
// before inline
// temp.set(cLocal).subLocal(vertices[i]);
// float s = Vec2.dot(normals[i], temp);
// after inline
Vec2 vertex = vertices[i];
float tempx = cLocalx - vertex.x;
float tempy = cLocaly - vertex.y;
s = normals[i].x*tempx + normals[i].y*tempy;
if (s > radius)
{
// early ref
return;
}
if (s > separation)
{
separation = s;
normalIndex = i;
}
}
// Vertices that subtend the incident face.
int vertIndex1 = normalIndex;
int vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;
Vec2 v1 = vertices[vertIndex1];
Vec2 v2 = vertices[vertIndex2];
// If the center is inside the polygon ...
if (separation < Settings.EPSILON)
{
manifold.pointCount = 1;
manifold.type = ManifoldType.FACE_A;
// before inline:
// manifold.localNormal.set(normals[normalIndex]);
// manifold.localPoint.set(v1).addLocal(v2).mulLocal(.5f);
// manifold.points[0].localPoint.set(circle.m_p);
// after inline:
Vec2 normal = normals[normalIndex];
manifold.localNormal.x = normal.x;
manifold.localNormal.y = normal.y;
manifold.localPoint.x = (v1.x + v2.x)*.5f;
manifold.localPoint.y = (v1.y + v2.y)*.5f;
ManifoldPoint mpoint = manifold.points[0];
mpoint.localPoint.x = circlep.x;
mpoint.localPoint.y = circlep.y;
mpoint.id.zero();
// end inline
return;
}
// Compute barycentric coordinates
// before inline:
// temp.set(cLocal).subLocal(v1);
// temp2.set(v2).subLocal(v1);
// float u1 = Vec2.dot(temp, temp2);
// temp.set(cLocal).subLocal(v2);
// temp2.set(v1).subLocal(v2);
// float u2 = Vec2.dot(temp, temp2);
// after inline:
float tempX = cLocalx - v1.x;
float tempY = cLocaly - v1.y;
float temp2X = v2.x - v1.x;
float temp2Y = v2.y - v1.y;
float u1 = tempX*temp2X + tempY*temp2Y;
float temp3X = cLocalx - v2.x;
float temp3Y = cLocaly - v2.y;
float temp4X = v1.x - v2.x;
float temp4Y = v1.y - v2.y;
float u2 = temp3X*temp4X + temp3Y*temp4Y;
// end inline
if (u1 <= 0f)
{
// inlined
float dx = cLocalx - v1.x;
float dy = cLocaly - v1.y;
if (dx*dx + dy*dy > radius*radius)
{
return;
}
manifold.pointCount = 1;
manifold.type = ManifoldType.FACE_A;
// before inline:
// manifold.localNormal.set(cLocal).subLocal(v1);
// after inline:
manifold.localNormal.x = cLocalx - v1.x;
manifold.localNormal.y = cLocaly - v1.y;
// end inline
manifold.localNormal.normalize();
manifold.localPoint.set(v1);
manifold.points[0].localPoint.set(circlep);
manifold.points[0].id.zero();
}
else if (u2 <= 0.0f)
{
// inlined
float dx = cLocalx - v2.x;
float dy = cLocaly - v2.y;
if (dx*dx + dy*dy > radius*radius)
{
return;
}
manifold.pointCount = 1;
manifold.type = ManifoldType.FACE_A;
// before inline:
// manifold.localNormal.set(cLocal).subLocal(v2);
// after inline:
manifold.localNormal.x = cLocalx - v2.x;
manifold.localNormal.y = cLocaly - v2.y;
// end inline
manifold.localNormal.normalize();
manifold.localPoint.set(v2);
manifold.points[0].localPoint.set(circlep);
manifold.points[0].id.zero();
}
else
{
// Vec2 faceCenter = 0.5f * (v1 + v2);
// (temp is faceCenter)
// before inline:
// temp.set(v1).addLocal(v2).mulLocal(.5f);
//
// temp2.set(cLocal).subLocal(temp);
// separation = Vec2.dot(temp2, normals[vertIndex1]);
// if (separation > radius) {
// return;
// }
// after inline:
float fcx = (v1.x + v2.x)*.5f;
float fcy = (v1.y + v2.y)*.5f;
float tx = cLocalx - fcx;
float ty = cLocaly - fcy;
Vec2 normal = normals[vertIndex1];
separation = tx*normal.x + ty*normal.y;
if (separation > radius)
{
return;
}
// end inline
manifold.pointCount = 1;
manifold.type = ManifoldType.FACE_A;
manifold.localNormal.set(normals[vertIndex1]);
manifold.localPoint.x = fcx; // (faceCenter)
manifold.localPoint.y = fcy;
manifold.points[0].localPoint.set(circlep);
manifold.points[0].id.zero();
}
}
// djm pooling, and from above
private Vec2 temp;
private Transform xf;
private Vec2 n;
private Vec2 v1;
/**
* Find the max separation between poly1 and poly2 using edge normals from poly1.
*
* @param edgeIndex
* @param poly1
* @param xf1
* @param poly2
* @param xf2
* @return
*/
public void findMaxSeparation(EdgeResults results, PolygonShape poly1,
Transform xf1, PolygonShape poly2, Transform xf2)
{
int count1 = poly1.m_count;
int count2 = poly2.m_count;
Vec2[] n1s = poly1.m_normals;
Vec2[] v1s = poly1.m_vertices;
Vec2[] v2s = poly2.m_vertices;
Transform.mulTransToOutUnsafe(xf2, xf1, ref xf);
Rot xfq = xf.q;
int bestIndex = 0;
float maxSeparation = -float.MaxValue;
for (int i = 0; i < count1; i++)
{
// Get poly1 normal in frame2.
Rot.mulToOutUnsafe(xfq, n1s[i], ref n);
Transform.mulToOutUnsafe(xf, v1s[i], ref v1);
// Find deepest point for normal i.
float si = float.MaxValue;
for (int j = 0; j < count2; ++j)
{
Vec2 v2sj = v2s[j];
float sij = n.x*(v2sj.x - v1.x) + n.y*(v2sj.y - v1.y);
if (sij < si)
{
si = sij;
}
}
if (si > maxSeparation)
{
maxSeparation = si;
bestIndex = i;
}
}
results.edgeIndex = bestIndex;
results.separation = maxSeparation;
}
public void findIncidentEdge(ClipVertex[] c, PolygonShape poly1,
Transform xf1, int edge1, PolygonShape poly2, Transform xf2)
{
int count1 = poly1.m_count;
Vec2[] normals1 = poly1.m_normals;
int count2 = poly2.m_count;
Vec2[] vertices2 = poly2.m_vertices;
Vec2[] normals2 = poly2.m_normals;
Debug.Assert(0 <= edge1 && edge1 < count1);
ClipVertex c0 = c[0];
ClipVertex c1 = c[1];
Rot xf1q = xf1.q;
Rot xf2q = xf2.q;
// Get the normal of the reference edge in poly2's frame.
// Vec2 normal1 = MulT(xf2.R, Mul(xf1.R, normals1[edge1]));
// before inline:
// Rot.mulToOutUnsafe(xf1.q, normals1[edge1], normal1); // temporary
// Rot.mulTrans(xf2.q, normal1, normal1);
// after inline:
Vec2 v = normals1[edge1];
float tempx = xf1q.c*v.x - xf1q.s*v.y;
float tempy = xf1q.s*v.x + xf1q.c*v.y;
float normal1x = xf2q.c*tempx + xf2q.s*tempy;
float normal1y = -xf2q.s*tempx + xf2q.c*tempy;
// end inline
// Find the incident edge on poly2.
int index = 0;
float minDot = float.MaxValue;
for (int i = 0; i < count2; ++i)
{
Vec2 b = normals2[i];
float dot = normal1x*b.x + normal1y*b.y;
if (dot < minDot)
{
minDot = dot;
index = i;
}
}
// Build the clip vertices for the incident edge.
int i1 = index;
int i2 = i1 + 1 < count2 ? i1 + 1 : 0;
// c0.v = Mul(xf2, vertices2[i1]);
Vec2 v1 = vertices2[i1];
Vec2 @ref = c0.v;
@ref.x = (xf2q.c*v1.x - xf2q.s*v1.y) + xf2.p.x;
@ref.y = (xf2q.s*v1.x + xf2q.c*v1.y) + xf2.p.y;
c0.v = @ref;
c0.id.indexA = (byte) edge1;
c0.id.indexB = (byte) i1;
c0.id.typeA = (byte) ContactID.Type.FACE;
c0.id.typeB = (byte) ContactID.Type.VERTEX;
// c1.v = Mul(xf2, vertices2[i2]);
Vec2 v2 = vertices2[i2];
Vec2 out1 = c1.v;
out1.x = (xf2q.c*v2.x - xf2q.s*v2.y) + xf2.p.x;
out1.y = (xf2q.s*v2.x + xf2q.c*v2.y) + xf2.p.y;
c1.id.indexA = (byte) edge1;
c1.id.indexB = (byte) i2;
c1.id.typeA = (byte) ContactID.Type.FACE;
c1.id.typeB = (byte) ContactID.Type.VERTEX;
}
private EdgeResults results1 = new EdgeResults();
private EdgeResults results2 = new EdgeResults();
private ClipVertex[] incidentEdge = new ClipVertex[2];
private Vec2 localTangent = new Vec2();
private Vec2 localNormal = new Vec2();
private Vec2 planePoint = new Vec2();
private Vec2 tangent = new Vec2();
private Vec2 v11 = new Vec2();
private Vec2 v12 = new Vec2();
private ClipVertex[] clipPoints1 = new ClipVertex[2];
private ClipVertex[] clipPoints2 = new ClipVertex[2];
/**
* Compute the collision manifold between two polygons.
*
* @param manifold
* @param polygon1
* @param xf1
* @param polygon2
* @param xf2
*/
public void collidePolygons(Manifold manifold, PolygonShape polyA,
Transform xfA, PolygonShape polyB, Transform xfB)
{
// Find edge normal of max separation on A - return if separating axis is found
// Find edge normal of max separation on B - return if separation axis is found
// Choose reference edge as min(minA, minB)
// Find incident edge
// Clip
// The normal points from 1 to 2
manifold.pointCount = 0;
float totalRadius = polyA.m_radius + polyB.m_radius;
findMaxSeparation(results1, polyA, xfA, polyB, xfB);
if (results1.separation > totalRadius)
{
return;
}
findMaxSeparation(results2, polyB, xfB, polyA, xfA);
if (results2.separation > totalRadius)
{
return;
}
PolygonShape poly1; // reference polygon
PolygonShape poly2; // incident polygon
Transform xf1, xf2;
int edge1; // reference edge
bool flip;
float k_tol = 0.1f*Settings.linearSlop;
if (results2.separation > results1.separation + k_tol)
{
poly1 = polyB;
poly2 = polyA;
xf1 = xfB;
xf2 = xfA;
edge1 = results2.edgeIndex;
manifold.type = ManifoldType.FACE_B;
flip = true;
}
else
{
poly1 = polyA;
poly2 = polyB;
xf1 = xfA;
xf2 = xfB;
edge1 = results1.edgeIndex;
manifold.type = ManifoldType.FACE_A;
flip = false;
}
Rot xf1q = xf1.q;
findIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2);
int count1 = poly1.m_count;
Vec2[] vertices1 = poly1.m_vertices;
int iv1 = edge1;
int iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;
v11.set(vertices1[iv1]);
v12.set(vertices1[iv2]);
localTangent.x = v12.x - v11.x;
localTangent.y = v12.y - v11.y;
localTangent.normalize();
// Vec2 localNormal = Vec2.cross(dv, 1.0f);
localNormal.x = 1f*localTangent.y;
localNormal.y = -1f*localTangent.x;
// Vec2 planePoint = 0.5f * (v11+ v12);
planePoint.x = (v11.x + v12.x)*.5f;
planePoint.y = (v11.y + v12.y)*.5f;
// Rot.mulToOutUnsafe(xf1.q, localTangent, tangent);
tangent.x = xf1q.c*localTangent.x - xf1q.s*localTangent.y;
tangent.y = xf1q.s*localTangent.x + xf1q.c*localTangent.y;
// Vec2.crossToOutUnsafe(tangent, 1f, normal);
float normalx = 1f*tangent.y;
float normaly = -1f*tangent.x;
Transform.mulToOut(xf1, v11, ref v11);
Transform.mulToOut(xf1, v12, ref v12);
// v11 = Mul(xf1, v11);
// v12 = Mul(xf1, v12);
// Face offset
// float frontOffset = Vec2.dot(normal, v11);
// inlined
float frontOffset = normalx*v11.x + normaly*v11.y;
// Side offsets, extended by polytope skin thickness.
// float sideOffset1 = -Vec2.dot(tangent, v11) + totalRadius;
// float sideOffset2 = Vec2.dot(tangent, v12) + totalRadius;
// inlined
float sideOffset1 = -(tangent.x*v11.x + tangent.y*v11.y) + totalRadius;
float sideOffset2 = tangent.x*v12.x + tangent.y*v12.y + totalRadius;
// Clip incident edge against extruded edge1 side edges.
// ClipVertex clipPoints1[2];
// ClipVertex clipPoints2[2];
int np;
// Clip to box side 1
// np = ClipSegmentToLine(clipPoints1, incidentEdge, -sideNormal, sideOffset1);
tangent.negateLocal();
np = clipSegmentToLine(clipPoints1, incidentEdge, tangent, sideOffset1, iv1);
tangent.negateLocal();
if (np < 2)
{
return;
}
// Clip to negative box side 1
np = clipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2);
if (np < 2)
{
return;
}
// Now clipPoints2 contains the clipped points.
manifold.localNormal.set(localNormal);
manifold.localPoint.set(planePoint);
int pointCount = 0;
for (int i = 0; i < Settings.maxManifoldPoints; ++i)
{
// float separation = Vec2.dot(normal, clipPoints2[i].v) - frontOffset;
// inlined
float separation = normalx*clipPoints2[i].v.x + normaly*clipPoints2[i].v.y - frontOffset;
if (separation <= totalRadius)
{
ManifoldPoint cp = manifold.points[pointCount];
// cp.m_localPoint = MulT(xf2, clipPoints2[i].v);
// inlined
Vec2 localPoint = cp.localPoint;
float px = clipPoints2[i].v.x - xf2.p.x;
float py = clipPoints2[i].v.y - xf2.p.y;
localPoint.x = (xf2.q.c*px + xf2.q.s*py);
localPoint.y = (-xf2.q.s*px + xf2.q.c*py);
cp.localPoint = localPoint;
cp.id.set(clipPoints2[i].id);
if (flip)
{
// Swap features
cp.id.flip();
}
++pointCount;
}
}
manifold.pointCount = pointCount;
}
private Vec2 Q;
private Vec2 e;
private ContactID cf = new ContactID();
private Vec2 e1;
// Compute contact points for edge versus circle.
// This accounts for edge connectivity.
public void collideEdgeAndCircle(Manifold manifold, EdgeShape edgeA, Transform xfA,
CircleShape circleB, Transform xfB)
{
manifold.pointCount = 0;
// Compute circle in frame of edge
// Vec2 Q = MulT(xfA, Mul(xfB, circleB.m_p));
Transform.mulToOutUnsafe(xfB, circleB.m_p, ref temp);
Transform.mulTransToOutUnsafe(xfA, temp, ref Q);
Vec2 A = edgeA.m_vertex1;
Vec2 B = edgeA.m_vertex2;
e.set(B);
e.subLocal(A);
// Barycentric coordinates
temp.set(B);
temp.subLocal(Q);
float u = Vec2.dot(e, temp);
temp.set(Q);
temp.subLocal(A);
float v = Vec2.dot(e, temp);
float radius = edgeA.m_radius + circleB.m_radius;
// ContactFeature cf;
cf.indexB = 0;
cf.typeB = (byte) ContactID.Type.VERTEX;
// Region A
float dd;
Vec2 P;
if (v <= 0.0f)
{
P = A;
d.set(Q);
d.subLocal(P);
dd = Vec2.dot(d, d);
if (dd > radius*radius)
{
return;
}
// Is there an edge connected to A?
if (edgeA.m_hasVertex0)
{
Vec2 A1 = edgeA.m_vertex0;
Vec2 B1 = A;
e1.set(B1);
e1.subLocal(A1);
temp.set(B1);
temp.subLocal(Q);
float u1 = Vec2.dot(e1, temp);
// Is the circle in Region AB of the previous edge?
if (u1 > 0.0f)
{
return;
}
}
cf.indexA = 0;
cf.typeA = (byte) ContactID.Type.VERTEX;
manifold.pointCount = 1;
manifold.type = ManifoldType.CIRCLES;
manifold.localNormal.setZero();
manifold.localPoint.set(P);
// manifold.points[0].id.key = 0;
manifold.points[0].id.set(cf);
manifold.points[0].localPoint.set(circleB.m_p);
return;
}
// Region B
if (u <= 0.0f)
{
P = B;
d.set(Q);
d.subLocal(P);
dd = Vec2.dot(d, d);
if (dd > radius*radius)
{
return;
}
// Is there an edge connected to B?
if (edgeA.m_hasVertex3)
{
Vec2 B2 = edgeA.m_vertex3;
Vec2 A2 = B;
Vec2 e2 = e1;
e2.set(B2);
e2.subLocal(A2);
temp.set(Q);
temp.subLocal(A2);
float v2 = Vec2.dot(e2, temp);
// Is the circle in Region AB of the next edge?
if (v2 > 0.0f)
{
return;
}
}
cf.indexA = 1;
cf.typeA = (byte) ContactID.Type.VERTEX;
manifold.pointCount = 1;
manifold.type = ManifoldType.CIRCLES;
manifold.localNormal.setZero();
manifold.localPoint.set(P);
// manifold.points[0].id.key = 0;
manifold.points[0].id.set(cf);
manifold.points[0].localPoint.set(circleB.m_p);
return;
}
// Region AB
float den = Vec2.dot(e, e);
Debug.Assert(den > 0.0f);
// Vec2 P = (1.0f / den) * (u * A + v * B);
P = A;
P.mulLocal(u);
temp.set(B);
temp.mulLocal(v);
P.addLocal(temp);
P.mulLocal(1.0f/den);
d.set(Q);
d.subLocal(P);
dd = Vec2.dot(d, d);
if (dd > radius*radius)
{
return;
}
n.x = -e.y;
n.y = e.x;
temp.set(Q);
temp.subLocal(A);
if (Vec2.dot(n, temp) < 0.0f)
{
n.set(-n.x, -n.y);
}
n.normalize();
cf.indexA = 0;
cf.typeA = (byte) ContactID.Type.FACE;
manifold.pointCount = 1;
manifold.type = ManifoldType.FACE_A;
manifold.localNormal.set(n);
manifold.localPoint.set(A);
// manifold.points[0].id.key = 0;
manifold.points[0].id.set(cf);
manifold.points[0].localPoint.set(circleB.m_p);
}
private EPCollider collider = new EPCollider();
public void collideEdgeAndPolygon(Manifold manifold, EdgeShape edgeA, Transform xfA,
PolygonShape polygonB, Transform xfB)
{
collider.collide(manifold, edgeA, xfA, polygonB, xfB);
}
/**
* Java-specific class for returning edge results
*/
public class EdgeResults
{
public float separation;
public int edgeIndex;
}
/**
* Used for computing contact manifolds.
*/
public class ClipVertex
{
public Vec2 v;
public ContactID id;
public ClipVertex()
{
v = new Vec2();
id = new ContactID();
}
public void set(ClipVertex cv)
{
Vec2 v1 = cv.v;
v.x = v1.x;
v.y = v1.y;
ContactID c = cv.id;
id.indexA = c.indexA;
id.indexB = c.indexB;
id.typeA = c.typeA;
id.typeB = c.typeB;
}
}
/**
* This is used for determining the state of contact points.
*
* @author Daniel Murphy
*/
public enum PointState
{
/**
* point does not exist
*/
NULL_STATE,
/**
* point was added in the update
*/
ADD_STATE,
/**
* point persisted across the update
*/
PERSIST_STATE,
/**
* point was removed in the update
*/
REMOVE_STATE
}
/**
* This structure is used to keep track of the best separating axis.
*/
private class EPAxis
{
public EPAxisType type;
internal int index;
internal float separation;
}
/**
* This holds polygon B expressed in frame A.
*/
private class TempPolygon
{
internal Vec2[] vertices = new Vec2[Settings.maxPolygonVertices];
internal Vec2[] normals = new Vec2[Settings.maxPolygonVertices];
internal int count;
}
/**
* Reference face used for clipping
*/
private class ReferenceFace
{
internal int i1, i2;
internal Vec2 v1;
internal Vec2 v2;
internal Vec2 normal;
internal Vec2 sideNormal1;
internal float sideOffset1;
internal Vec2 sideNormal2;
internal float sideOffset2;
}
/**
* This class collides and edge and a polygon, taking into account edge adjacency.
*/
private class EPCollider
{
private TempPolygon m_polygonB = new TempPolygon();
private Transform m_xf;
private Vec2 m_centroidB;
private Vec2 m_v0;
private Vec2 m_v1;
private Vec2 m_v2;
private Vec2 m_v3;
private Vec2 m_normal0;
private Vec2 m_normal1;
private Vec2 m_normal2;
private Vec2 m_normal;
private Vec2 m_lowerLimit;
private Vec2 m_upperLimit;
private float m_radius;
private bool m_front;
public EPCollider()
{
for (int i = 0; i < 2; i++)
{
ie[i] = new ClipVertex();
clipPoints1[i] = new ClipVertex();
clipPoints2[i] = new ClipVertex();
}
}
private Vec2 edge1;
private Vec2 temp;
private Vec2 edge0;
private Vec2 edge2;
private ClipVertex[] ie = new ClipVertex[2];
private ClipVertex[] clipPoints1 = new ClipVertex[2];
private ClipVertex[] clipPoints2 = new ClipVertex[2];
private ReferenceFace rf = new ReferenceFace();
private EPAxis edgeAxis = new EPAxis();
private EPAxis polygonAxis = new EPAxis();
public void collide(Manifold manifold, EdgeShape edgeA, Transform xfA,
PolygonShape polygonB, Transform xfB)
{
Transform.mulTransToOutUnsafe(xfA, xfB, ref m_xf);
Transform.mulToOutUnsafe(m_xf, polygonB.m_centroid, ref m_centroidB);
m_v0 = edgeA.m_vertex0;
m_v1 = edgeA.m_vertex1;
m_v2 = edgeA.m_vertex2;
m_v3 = edgeA.m_vertex3;
bool hasVertex0 = edgeA.m_hasVertex0;
bool hasVertex3 = edgeA.m_hasVertex3;
edge1.set(m_v2);
edge1.subLocal(m_v1);
edge1.normalize();
m_normal1.set(edge1.y, -edge1.x);
temp.set(m_centroidB);
temp.subLocal(m_v1);
float offset1 = Vec2.dot(m_normal1, temp);
float offset0 = 0.0f, offset2 = 0.0f;
bool convex1 = false, convex2 = false;
// Is there a preceding edge?
if (hasVertex0)
{
edge0.set(m_v1);
edge0.subLocal(m_v0);
edge0.normalize();
m_normal0.set(edge0.y, -edge0.x);
convex1 = Vec2.cross(edge0, edge1) >= 0.0f;
temp.set(m_centroidB);
temp.subLocal(m_v0);
offset0 = Vec2.dot(m_normal0, temp);
}
// Is there a following edge?
if (hasVertex3)
{
edge2.set(m_v3);
edge2.subLocal(m_v2);
edge2.normalize();
m_normal2.set(edge2.y, -edge2.x);
convex2 = Vec2.cross(edge1, edge2) > 0.0f;
temp.set(m_centroidB);
temp.subLocal(m_v2);
offset2 = Vec2.dot(m_normal2,temp);
}
// Determine front or back collision. Determine collision normal limits.
if (hasVertex0 && hasVertex3)
{
if (convex1 && convex2)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal0.x;
m_lowerLimit.y = m_normal0.y;
m_upperLimit.x = m_normal2.x;
m_upperLimit.y = m_normal2.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
}
else if (convex1)
{
m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f);
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal0.x;
m_lowerLimit.y = m_normal0.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal2.x;
m_lowerLimit.y = -m_normal2.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
}
else if (convex2)
{
m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f);
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = m_normal2.x;
m_upperLimit.y = m_normal2.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = -m_normal0.x;
m_upperLimit.y = -m_normal0.y;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal2.x;
m_lowerLimit.y = -m_normal2.y;
m_upperLimit.x = -m_normal0.x;
m_upperLimit.y = -m_normal0.y;
}
}
}
else if (hasVertex0)
{
if (convex1)
{
m_front = offset0 >= 0.0f || offset1 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal0.x;
m_lowerLimit.y = m_normal0.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
}
else
{
m_front = offset0 >= 0.0f && offset1 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = -m_normal0.x;
m_upperLimit.y = -m_normal0.y;
}
}
}
else if (hasVertex3)
{
if (convex2)
{
m_front = offset1 >= 0.0f || offset2 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = m_normal2.x;
m_upperLimit.y = m_normal2.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
}
else
{
m_front = offset1 >= 0.0f && offset2 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = -m_normal2.x;
m_lowerLimit.y = -m_normal2.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
}
}
else
{
m_front = offset1 >= 0.0f;
if (m_front)
{
m_normal.x = m_normal1.x;
m_normal.y = m_normal1.y;
m_lowerLimit.x = -m_normal1.x;
m_lowerLimit.y = -m_normal1.y;
m_upperLimit.x = -m_normal1.x;
m_upperLimit.y = -m_normal1.y;
}
else
{
m_normal.x = -m_normal1.x;
m_normal.y = -m_normal1.y;
m_lowerLimit.x = m_normal1.x;
m_lowerLimit.y = m_normal1.y;
m_upperLimit.x = m_normal1.x;
m_upperLimit.y = m_normal1.y;
}
}
// Get polygonB in frameA
m_polygonB.count = polygonB.m_count;
for (int i = 0; i < polygonB.m_count; ++i)
{
Transform.mulToOutUnsafe(m_xf, polygonB.m_vertices[i], ref m_polygonB.vertices[i]);
Rot.mulToOutUnsafe(m_xf.q, polygonB.m_normals[i], ref m_polygonB.normals[i]);
}
m_radius = 2.0f*Settings.polygonRadius;
manifold.pointCount = 0;
computeEdgeSeparation(edgeAxis);
// If no valid normal can be found than this edge should not collide.
if (edgeAxis.type == EPAxisType.UNKNOWN)
{
return;
}
if (edgeAxis.separation > m_radius)
{
return;
}
computePolygonSeparation(polygonAxis);
if (polygonAxis.type != EPAxisType.UNKNOWN && polygonAxis.separation > m_radius)
{
return;
}
// Use hysteresis for jitter reduction.
float k_relativeTol = 0.98f;
float k_absoluteTol = 0.001f;
EPAxis primaryAxis;
if (polygonAxis.type == EPAxisType.UNKNOWN)
{
primaryAxis = edgeAxis;
}
else if (polygonAxis.separation > k_relativeTol*edgeAxis.separation + k_absoluteTol)
{
primaryAxis = polygonAxis;
}
else
{
primaryAxis = edgeAxis;
}
ClipVertex ie0 = ie[0];
ClipVertex ie1 = ie[1];
if (primaryAxis.type == EPAxisType.EDGE_A)
{
manifold.type = ManifoldType.FACE_A;
// Search for the polygon normal that is most anti-parallel to the edge normal.
int bestIndex = 0;
float bestValue = Vec2.dot(m_normal, m_polygonB.normals[0]);
for (int i = 1; i < m_polygonB.count; ++i)
{
float value = Vec2.dot(m_normal, m_polygonB.normals[i]);
if (value < bestValue)
{
bestValue = value;
bestIndex = i;
}
}
int i1 = bestIndex;
int i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0;
ie0.v.set(m_polygonB.vertices[i1]);
ie0.id.indexA = 0;
ie0.id.indexB = (byte) i1;
ie0.id.typeA = (byte) ContactID.Type.FACE;
ie0.id.typeB = (byte) ContactID.Type.VERTEX;
ie1.v.set(m_polygonB.vertices[i2]);
ie1.id.indexA = 0;
ie1.id.indexB = (byte) i2;
ie1.id.typeA = (byte) ContactID.Type.FACE;
ie1.id.typeB = (byte) ContactID.Type.VERTEX;
if (m_front)
{
rf.i1 = 0;
rf.i2 = 1;
rf.v1.set(m_v1);
rf.v2.set(m_v2);
rf.normal.set(m_normal1);
}
else
{
rf.i1 = 1;
rf.i2 = 0;
rf.v1.set(m_v2);
rf.v2.set(m_v1);
rf.normal.set(m_normal1);
rf.normal.negateLocal();
}
}
else
{
manifold.type = ManifoldType.FACE_B;
ie0.v.set(m_v1);
ie0.id.indexA = 0;
ie0.id.indexB = (byte) primaryAxis.index;
ie0.id.typeA = (byte) ContactID.Type.VERTEX;
ie0.id.typeB = (byte) ContactID.Type.FACE;
ie1.v.set(m_v2);
ie1.id.indexA = 0;
ie1.id.indexB = (byte) primaryAxis.index;
ie1.id.typeA = (byte) ContactID.Type.VERTEX;
ie1.id.typeB = (byte) ContactID.Type.FACE;
rf.i1 = primaryAxis.index;
rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0;
rf.v1.set(m_polygonB.vertices[rf.i1]);
rf.v2.set(m_polygonB.vertices[rf.i2]);
rf.normal.set(m_polygonB.normals[rf.i1]);
}
rf.sideNormal1.set(rf.normal.y, -rf.normal.x);
rf.sideNormal2.set(rf.sideNormal1);
rf.sideNormal2.negateLocal();
rf.sideOffset1 = Vec2.dot(rf.sideNormal1, rf.v1);
rf.sideOffset2 = Vec2.dot(rf.sideNormal2, rf.v2);
// Clip incident edge against extruded edge1 side edges.
int np;
// Clip to box side 1
np = clipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1);
if (np < Settings.maxManifoldPoints)
{
return;
}
// Clip to negative box side 1
np = clipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2);
if (np < Settings.maxManifoldPoints)
{
return;
}
// Now clipPoints2 contains the clipped points.
if (primaryAxis.type == EPAxisType.EDGE_A)
{
manifold.localNormal.set(rf.normal);
manifold.localPoint.set(rf.v1);
}
else
{
manifold.localNormal.set(polygonB.m_normals[rf.i1]);
manifold.localPoint.set(polygonB.m_vertices[rf.i1]);
}
int pointCount = 0;
for (int i = 0; i < Settings.maxManifoldPoints; ++i)
{
float separation;
temp.set(clipPoints2[i].v);
temp.subLocal(rf.v1);
separation = Vec2.dot(rf.normal, temp);
if (separation <= m_radius)
{
ManifoldPoint cp = manifold.points[pointCount];
if (primaryAxis.type == EPAxisType.EDGE_A)
{
// cp.localPoint = MulT(m_xf, clipPoints2[i].v);
Transform.mulTransToOutUnsafe(m_xf, clipPoints2[i].v, ref cp.localPoint);
cp.id.set(clipPoints2[i].id);
}
else
{
cp.localPoint.set(clipPoints2[i].v);
cp.id.typeA = clipPoints2[i].id.typeB;
cp.id.typeB = clipPoints2[i].id.typeA;
cp.id.indexA = clipPoints2[i].id.indexB;
cp.id.indexB = clipPoints2[i].id.indexA;
}
++pointCount;
}
}
manifold.pointCount = pointCount;
}
private void computeEdgeSeparation(EPAxis axis)
{
axis.type = EPAxisType.EDGE_A;
axis.index = m_front ? 0 : 1;
axis.separation = float.MaxValue;
float nx = m_normal.x;
float ny = m_normal.y;
for (int i = 0; i < m_polygonB.count; ++i)
{
Vec2 v = m_polygonB.vertices[i];
float tempx = v.x - m_v1.x;
float tempy = v.y - m_v1.y;
float s = nx*tempx + ny*tempy;
if (s < axis.separation)
{
axis.separation = s;
}
}
}
private Vec2 perp;
private Vec2 n;
private void computePolygonSeparation(EPAxis axis)
{
axis.type = EPAxisType.UNKNOWN;
axis.index = -1;
axis.separation = -float.MaxValue;
perp.x = -m_normal.y;
perp.y = m_normal.x;
for (int i = 0; i < m_polygonB.count; ++i)
{
Vec2 normalB = m_polygonB.normals[i];
Vec2 vB = m_polygonB.vertices[i];
n.x = -normalB.x;
n.y = -normalB.y;
// float s1 = Vec2.dot(n, temp.set(vB).subLocal(m_v1));
// float s2 = Vec2.dot(n, temp.set(vB).subLocal(m_v2));
float tempx = vB.x - m_v1.x;
float tempy = vB.y - m_v1.y;
float s1 = n.x*tempx + n.y*tempy;
tempx = vB.x - m_v2.x;
tempy = vB.y - m_v2.y;
float s2 = n.x*tempx + n.y*tempy;
float s = MathUtils.min(s1, s2);
if (s > m_radius)
{
// No collision
axis.type = EPAxisType.EDGE_B;
axis.index = i;
axis.separation = s;
return;
}
// Adjacency
if (n.x*perp.x + n.y*perp.y >= 0.0f)
{
temp.set(n);
temp.subLocal(m_upperLimit);
if (Vec2.dot(temp, m_normal) < -Settings.angularSlop)
{
continue;
}
}
else
{
temp.set(n);
temp.subLocal(m_lowerLimit);
if (Vec2.dot(temp, m_normal) < -Settings.angularSlop)
{
continue;
}
}
if (s > axis.separation)
{
axis.type = EPAxisType.EDGE_B;
axis.index = i;
axis.separation = s;
}
}
}
}
public enum EPVertexType
{
ISOLATED,
CONCAVE,
CONVEX
}
public enum EPAxisType
{
UNKNOWN,
EDGE_A,
EDGE_B
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="DropboxRequestHandler.cs" company="Dropbox Inc">
// Copyright (c) Dropbox Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace Dropbox.Api
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Dropbox.Api.Common;
using Dropbox.Api.Stone;
using Newtonsoft.Json.Linq;
/// <summary>
/// The object used to to make requests to the Dropbox API.
/// </summary>
internal sealed class DropboxRequestHandler : ITransport
{
private const int TokenExpirationBuffer = 300;
/// <summary>
/// The API version.
/// </summary>
private const string ApiVersion = "2";
/// <summary>
/// The dropbox API argument header.
/// </summary>
private const string DropboxApiArgHeader = "Dropbox-API-Arg";
/// <summary>
/// The dropbox API result header.
/// </summary>
private const string DropboxApiResultHeader = "Dropbox-API-Result";
/// <summary>
/// The member id of the selected user.
/// </summary>
private readonly string selectUser;
/// <summary>
/// The member id of the selected admin.
/// </summary>
private readonly string selectAdmin;
/// <summary>
/// The path root value used to make API call.
/// </summary>
private readonly PathRoot pathRoot;
/// <summary>
/// The configuration options for dropbox client.
/// </summary>
private readonly DropboxRequestHandlerOptions options;
/// <summary>
/// The default http client instance.
/// </summary>
private readonly HttpClient defaultHttpClient = new HttpClient();
/// <summary>
/// The default long poll http client instance.
/// </summary>
private readonly HttpClient defaultLongPollHttpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(480) };
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandler"/> class.
/// </summary>
/// <param name="options">The configuration options for dropbox client.</param>
/// <param name="selectUser">The member id of the selected user.</param>
/// <param name="selectAdmin">The member id of the selected admin.</param>
/// <param name="pathRoot">The path root to make requests from.</param>
public DropboxRequestHandler(
DropboxRequestHandlerOptions options,
string selectUser = null,
string selectAdmin = null,
PathRoot pathRoot = null)
{
this.options = options ?? throw new ArgumentNullException("options");
this.selectUser = selectUser;
this.selectAdmin = selectAdmin;
this.pathRoot = pathRoot;
}
/// <summary>
/// The known route styles.
/// </summary>
internal enum RouteStyle
{
/// <summary>
/// RPC style means that the argument and result of a route are contained in the
/// HTTP body.
/// </summary>
Rpc,
/// <summary>
/// Download style means that the route argument goes in a <c>Dropbox-API-Args</c>
/// header, and the result comes back in a <c>Dropbox-API-Result</c> header. The
/// HTTP response body contains a binary payload.
/// </summary>
Download,
/// <summary>
/// Upload style means that the route argument goes in a <c>Dropbox-API-Arg</c>
/// header. The HTTP request body contains a binary payload. The result comes
/// back in a <c>Dropbox-API-Result</c> header.
/// </summary>
Upload,
}
/// <summary>
/// Sends the upload request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<TResponse> ITransport.SendRpcRequestAsync<TRequest, TResponse, TError>(
TRequest request,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Rpc, serializedArg)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
return JsonReader.Read(res.ObjectResult, responseDecoder);
}
/// <summary>
/// Sends the upload request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="body">The content to be uploaded.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<TResponse> ITransport.SendUploadRequestAsync<TRequest, TResponse, TError>(
TRequest request,
Stream body,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder, true);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Upload, serializedArg, body)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
return JsonReader.Read(res.ObjectResult, responseDecoder);
}
/// <summary>
/// Sends the download request asynchronously.
/// </summary>
/// <typeparam name="TRequest">The type of the request.</typeparam>
/// <typeparam name="TResponse">The type of the response.</typeparam>
/// <typeparam name="TError">The type of the error.</typeparam>
/// <param name="request">The request.</param>
/// <param name="host">The server host to send the request to.</param>
/// <param name="route">The route name.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="requestEncoder">The request encoder.</param>
/// <param name="responseDecoder">The response decoder.</param>
/// <param name="errorDecoder">The error decoder.</param>
/// <returns>An asynchronous task for the response.</returns>
/// <exception cref="ApiException{TError}">
/// This exception is thrown when there is an error reported by the server.
/// </exception>
async Task<IDownloadResponse<TResponse>> ITransport.SendDownloadRequestAsync<TRequest, TResponse, TError>(
TRequest request,
string host,
string route,
string auth,
IEncoder<TRequest> requestEncoder,
IDecoder<TResponse> responseDecoder,
IDecoder<TError> errorDecoder)
{
var serializedArg = JsonWriter.Write(request, requestEncoder, true);
var res = await this.RequestJsonStringWithRetry(host, route, auth, RouteStyle.Download, serializedArg)
.ConfigureAwait(false);
if (res.IsError)
{
throw StructuredException<TError>.Decode<ApiException<TError>>(
res.ObjectResult, errorDecoder, () => new ApiException<TError>(res.RequestId));
}
var response = JsonReader.Read(res.ObjectResult, responseDecoder);
return new DownloadResponse<TResponse>(response, res.HttpResponse);
}
/// <summary>
/// Uses the refresh token to obtain a new access token.
/// </summary>
/// <param name="scopeList">The scope list.</param>
/// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
public async Task<bool> RefreshAccessToken(string[] scopeList = null)
{
if (this.options.OAuth2RefreshToken == null || this.options.AppKey == null)
{
// Cannot refresh token if you do not have at a minimum refresh token and app key
return false;
}
var url = "https://api.dropbox.com/oauth2/token";
var parameters = new Dictionary<string, string>
{
{ "refresh_token", this.options.OAuth2RefreshToken },
{ "grant_type", "refresh_token" },
{ "client_id", this.options.AppKey },
};
if (!string.IsNullOrEmpty(this.options.AppSecret))
{
parameters["client_secret"] = this.options.AppSecret;
}
if (scopeList != null)
{
parameters["scope"] = string.Join(" ", scopeList);
}
var bodyContent = new FormUrlEncodedContent(parameters);
var response = await this.defaultHttpClient.PostAsync(url, bodyContent).ConfigureAwait(false);
// if response is an invalid grant, we want to throw this exception rather than the one thrown in
// response.EnsureSuccessStatusCode();
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (reason == "invalid_grant")
{
throw AuthException.Decode(reason, () => new AuthException(this.GetRequestId(response)));
}
}
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var json = JObject.Parse(await response.Content.ReadAsStringAsync());
string accessToken = json["access_token"].ToString();
DateTime tokenExpiration = DateTime.Now.AddSeconds(json["expires_in"].ToObject<int>());
this.options.OAuth2AccessToken = accessToken;
this.options.OAuth2AccessTokenExpiresAt = tokenExpiration;
return true;
}
return false;
}
/// <summary>
/// The public dispose.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Set the value for Dropbox-Api-Path-Root header.
/// </summary>
/// <param name="pathRoot">The path root object.</param>
/// <returns>A <see cref="DropboxClient"/> instance with Dropbox-Api-Path-Root header set.</returns>
internal DropboxRequestHandler WithPathRoot(PathRoot pathRoot)
{
if (pathRoot == null)
{
throw new ArgumentNullException("pathRoot");
}
return new DropboxRequestHandler(
this.options,
selectUser: this.selectUser,
selectAdmin: this.selectAdmin,
pathRoot: pathRoot);
}
/// <summary>
/// Requests the JSON string with retry.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="routeStyle">The route style.</param>
/// <param name="requestArg">The request argument.</param>
/// <param name="body">The body to upload if <paramref name="routeStyle"/>
/// is <see cref="RouteStyle.Upload"/>.</param>
/// <returns>The asynchronous task with the result.</returns>
private async Task<Result> RequestJsonStringWithRetry(
string host,
string routeName,
string auth,
RouteStyle routeStyle,
string requestArg,
Stream body = null)
{
var attempt = 0;
var hasRefreshed = false;
var maxRetries = this.options.MaxClientRetries;
var r = new Random();
if (routeStyle == RouteStyle.Upload)
{
if (body == null)
{
throw new ArgumentNullException("body");
}
// to support retry logic, the body stream must be seekable
// if it isn't we won't retry
if (!body.CanSeek)
{
maxRetries = 0;
}
}
await this.CheckAndRefreshAccessToken();
try
{
while (true)
{
try
{
return await this.RequestJsonString(host, routeName, auth, routeStyle, requestArg, body)
.ConfigureAwait(false);
}
catch (AuthException e)
{
if (e.Message == "expired_access_token")
{
if (hasRefreshed)
{
throw;
}
else
{
await this.RefreshAccessToken();
hasRefreshed = true;
}
}
else
{
// dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
// do not count a rate limiting error as an attempt
if (++attempt > maxRetries)
{
throw;
}
}
}
catch (RateLimitException)
{
throw;
}
catch (RetryException)
{
// dropbox maps 503 - ServiceUnavailable to be a rate limiting error.
// do not count a rate limiting error as an attempt
if (++attempt > maxRetries)
{
throw;
}
}
// use exponential backoff
var backoff = TimeSpan.FromSeconds(Math.Pow(2, attempt) * r.NextDouble());
#if PORTABLE40
await TaskEx.Delay(backoff);
#else
await Task.Delay(backoff).ConfigureAwait(false);
#endif
if (body != null)
{
body.Position = 0;
}
}
}
finally
{
body?.Dispose();
}
}
/// <summary>
/// Attempts to extract the value of a field named <c>error</c> from <paramref name="text"/>
/// if it is a valid JSON object.
/// </summary>
/// <param name="text">The text to check.</param>
/// <returns>The contents of the error field if present, otherwise <paramref name="text" />.</returns>
private string CheckForError(string text)
{
try
{
var obj = JObject.Parse(text);
if (obj.TryGetValue("error", out JToken error))
{
return error.ToString();
}
return text;
}
catch (Exception)
{
return text;
}
}
/// <summary>
/// Requests the JSON string.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="routeName">Name of the route.</param>
/// <param name="auth">The auth type of the route.</param>
/// <param name="routeStyle">The route style.</param>
/// <param name="requestArg">The request argument.</param>
/// <param name="body">The body to upload if <paramref name="routeStyle"/>
/// is <see cref="RouteStyle.Upload"/>.</param>
/// <returns>The asynchronous task with the result.</returns>
private async Task<Result> RequestJsonString(
string host,
string routeName,
string auth,
RouteStyle routeStyle,
string requestArg,
Stream body = null)
{
var hostname = this.options.HostMap[host];
var uri = this.GetRouteUri(hostname, routeName);
var request = new HttpRequestMessage(HttpMethod.Post, uri);
if (auth == AuthType.User || auth == AuthType.Team)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.options.OAuth2AccessToken);
}
else if (auth == AuthType.App)
{
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", this.options.OAuth2AccessToken);
}
else if (auth == AuthType.NoAuth)
{
}
else
{
throw new ArgumentException("Invalid auth type", auth);
}
request.Headers.TryAddWithoutValidation("User-Agent", this.options.UserAgent);
if (this.selectUser != null)
{
request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-User", this.selectUser);
}
if (this.selectAdmin != null)
{
request.Headers.TryAddWithoutValidation("Dropbox-Api-Select-Admin", this.selectAdmin);
}
if (this.pathRoot != null)
{
request.Headers.TryAddWithoutValidation(
"Dropbox-Api-Path-Root",
JsonWriter.Write(this.pathRoot, PathRoot.Encoder));
}
var completionOption = HttpCompletionOption.ResponseContentRead;
switch (routeStyle)
{
case RouteStyle.Rpc:
request.Content = new StringContent(requestArg, Encoding.UTF8, "application/json");
break;
case RouteStyle.Download:
request.Headers.Add(DropboxApiArgHeader, requestArg);
// This is required to force libcurl remove default content type header.
request.Content = new StringContent(string.Empty);
request.Content.Headers.ContentType = null;
completionOption = HttpCompletionOption.ResponseHeadersRead;
break;
case RouteStyle.Upload:
request.Headers.Add(DropboxApiArgHeader, requestArg);
if (body == null)
{
throw new ArgumentNullException("body");
}
request.Content = new CustomStreamContent(body);
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
break;
default:
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"Unknown route style: {0}",
routeStyle));
}
var disposeResponse = true;
var response = await this.GetHttpClient(host).SendAsync(request, completionOption).ConfigureAwait(false);
var requestId = this.GetRequestId(response);
try
{
if ((int)response.StatusCode >= 500)
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new RetryException(requestId, (int)response.StatusCode, message: text, uri: uri);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new BadInputException(requestId, text, uri);
}
else if (response.StatusCode == HttpStatusCode.Unauthorized)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw AuthException.Decode(reason, () => new AuthException(this.GetRequestId(response)));
}
else if ((int)response.StatusCode == 429)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw RateLimitException.Decode(reason, () => new RateLimitException(this.GetRequestId(response)));
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw AccessException.Decode(reason, () => new AccessException(this.GetRequestId(response)));
}
else if ((int)response.StatusCode == 422)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
throw PathRootException.Decode(reason, () => new PathRootException(this.GetRequestId(response)));
}
else if (response.StatusCode == HttpStatusCode.Conflict ||
response.StatusCode == HttpStatusCode.NotFound)
{
var reason = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return new Result
{
IsError = true,
ObjectResult = reason,
RequestId = this.GetRequestId(response),
};
}
else if ((int)response.StatusCode >= 200 && (int)response.StatusCode <= 299)
{
if (routeStyle == RouteStyle.Download)
{
disposeResponse = false;
return new Result
{
IsError = false,
ObjectResult = response.Headers.GetValues(DropboxApiResultHeader).FirstOrDefault(),
HttpResponse = response,
};
}
else
{
return new Result
{
IsError = false,
ObjectResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false),
};
}
}
else
{
var text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
text = this.CheckForError(text);
throw new HttpException(requestId, (int)response.StatusCode, text, uri);
}
}
finally
{
if (disposeResponse)
{
response.Dispose();
}
}
}
private async Task<bool> CheckAndRefreshAccessToken()
{
bool canRefresh = this.options.OAuth2RefreshToken != null && this.options.AppKey != null;
bool needsRefresh = (this.options.OAuth2AccessTokenExpiresAt.HasValue && DateTime.Now.AddSeconds(TokenExpirationBuffer) >= this.options.OAuth2AccessTokenExpiresAt.Value) ||
(this.options.OAuth2RefreshToken != null && !this.options.OAuth2AccessTokenExpiresAt.HasValue);
bool needsToken = this.options.OAuth2AccessToken == null;
if ((needsRefresh || needsToken) && canRefresh)
{
return await this.RefreshAccessToken();
}
return false;
}
/// <summary>
/// Gets the URI for a route.
/// </summary>
/// <param name="hostname">The hostname for the request.</param>
/// <param name="routeName">Name of the route.</param>
/// <returns>The uri for this route.</returns>
private Uri GetRouteUri(string hostname, string routeName)
{
var builder = new UriBuilder("https", hostname)
{
Path = "/" + ApiVersion + routeName,
};
return builder.Uri;
}
/// <summary>
/// Gets the Dropbox request id.
/// </summary>
/// <param name="response">Response.</param>
/// <returns>The request id.</returns>
private string GetRequestId(HttpResponseMessage response)
{
if (response.Headers.TryGetValues("X-Dropbox-Request-Id", out IEnumerable<string> requestId))
{
return requestId.FirstOrDefault();
}
return null;
}
/// <summary>
/// Get http client for given host.
/// </summary>
/// <param name="host">The host type.</param>
/// <returns>The <see cref="HttpClient"/>.</returns>
private HttpClient GetHttpClient(string host)
{
if (host == HostType.ApiNotify)
{
return this.options.LongPollHttpClient ?? this.defaultLongPollHttpClient;
}
else
{
return this.options.HttpClient ?? this.defaultHttpClient;
}
}
/// <summary>
/// The actual disposing logic.
/// </summary>
/// <param name="disposing">If is disposing.</param>
private void Dispose(bool disposing)
{
if (disposing)
{
// HttpClient is safe for multiple disposal.
this.defaultHttpClient.Dispose();
this.defaultLongPollHttpClient.Dispose();
}
}
/// <summary>
/// Used to return un-typed result information to the layer that can interpret the
/// object types.
/// </summary>
private class Result
{
/// <summary>
/// Gets or sets a value indicating whether this instance is an error.
/// </summary>
/// <value>
/// <c>true</c> if this instance is an error; otherwise, <c>false</c>.
/// </value>
public bool IsError { get; set; }
/// <summary>
/// Gets or sets the un-typed object result, this will be parsed into the
/// specific response or error type for the route.
/// </summary>
/// <value>
/// The object result.
/// </value>
public string ObjectResult { get; set; }
/// <summary>
/// Gets or sets the Dropbox request id.
/// </summary>
/// <value>The request id.</value>
public string RequestId { get; set; }
/// <summary>
/// Gets or sets the HTTP response, this is only set if the route was a download route.
/// </summary>
/// <value>
/// The HTTP response.
/// </value>
public HttpResponseMessage HttpResponse { get; set; }
}
/// <summary>
/// An implementation of the <see cref="T:Dropbox.Api.Stone.IDownloadResponse`1"/> interface.
/// </summary>
/// <typeparam name="TResponse">The type of the response.</typeparam>
private class DownloadResponse<TResponse> : IDownloadResponse<TResponse>
{
/// <summary>
/// The HTTP response containing the body content.
/// </summary>
private HttpResponseMessage httpResponse;
/// <summary>
/// Initializes a new instance of the <see cref="DownloadResponse{TResponse}"/> class.
/// </summary>
/// <param name="response">The response.</param>
/// <param name="httpResponseMessage">The HTTP response message.</param>
public DownloadResponse(TResponse response, HttpResponseMessage httpResponseMessage)
{
this.Response = response;
this.httpResponse = httpResponseMessage;
}
/// <summary>Gets the response.</summary>
/// <value>The response.</value>
public TResponse Response { get; private set; }
/// <summary>
/// Asynchronously gets the content as a <see cref="Stream" />.
/// </summary>
/// <returns>The downloaded content as a stream.</returns>
public Task<Stream> GetContentAsStreamAsync()
{
return this.httpResponse.Content.ReadAsStreamAsync();
}
/// <summary>
/// Asynchronously gets the content as a <see cref="byte" /> array.
/// </summary>
/// <returns>The downloaded content as a byte array.</returns>
public Task<byte[]> GetContentAsByteArrayAsync()
{
return this.httpResponse.Content.ReadAsByteArrayAsync();
}
/// <summary>
/// Asynchronously gets the content as <see cref="string" />.
/// </summary>
/// <returns>The downloaded content as a string.</returns>
public Task<string> GetContentAsStringAsync()
{
return this.httpResponse.Content.ReadAsStringAsync();
}
/// <summary>
/// Disposes of the <see cref="HttpResponseMessage"/> in this instance.
/// </summary>
public void Dispose()
{
if (this.httpResponse != null)
{
this.httpResponse.Dispose();
this.httpResponse = null;
}
}
}
}
/// <summary>
/// The stream content which doesn't dispose the underlying stream. This
/// is useful for retry.
/// </summary>
internal class CustomStreamContent : StreamContent
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomStreamContent"/> class.
/// </summary>
/// <param name="content">The stream content.</param>
public CustomStreamContent(Stream content)
: base(content)
{
}
/// <inheritdoc/>
protected override void Dispose(bool disposing)
{
// Do not dispose the stream.
}
}
/// <summary>
/// The type of api hosts.
/// </summary>
internal class HostType
{
/// <summary>
/// Host type for api.
/// </summary>
public const string Api = "api";
/// <summary>
/// Host type for api content.
/// </summary>
public const string ApiContent = "content";
/// <summary>
/// Host type for api notify.
/// </summary>
public const string ApiNotify = "notify";
}
/// <summary>
/// The type of api auth.
/// </summary>
internal class AuthType
{
/// <summary>
/// Auth type for user auth.
/// </summary>
public const string User = "user";
/// <summary>
/// Auth type for team auth.
/// </summary>
public const string Team = "team";
/// <summary>
/// Host type for app auth.
/// </summary>
public const string App = "app";
/// <summary>
/// Host type for no auth.
/// </summary>
public const string NoAuth = "noauth";
}
/// <summary>
/// The class which contains configurations for the request handler.
/// </summary>
internal sealed class DropboxRequestHandlerOptions
{
/// <summary>
/// The default api domain.
/// </summary>
private const string DefaultApiDomain = "api.dropboxapi.com";
/// <summary>
/// The default api content domain.
/// </summary>
private const string DefaultApiContentDomain = "content.dropboxapi.com";
/// <summary>
/// The default api notify domain.
/// </summary>
private const string DefaultApiNotifyDomain = "notify.dropboxapi.com";
/// <summary>
/// The base user agent, used to construct all user agent strings.
/// </summary>
private const string BaseUserAgent = "OfficialDropboxDotNetSDKv2";
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandlerOptions"/> class.
/// </summary>
/// <param name="config">The client configuration.</param>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
public DropboxRequestHandlerOptions(DropboxClientConfig config, string oauth2AccessToken, string oauth2RefreshToken, DateTime? oauth2AccessTokenExpiresAt, string appKey, string appSecret)
: this(
oauth2AccessToken,
oauth2RefreshToken,
oauth2AccessTokenExpiresAt,
appKey,
appSecret,
config.MaxRetriesOnError,
config.UserAgent,
DefaultApiDomain,
DefaultApiContentDomain,
DefaultApiNotifyDomain,
config.HttpClient,
config.LongPollHttpClient)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DropboxRequestHandlerOptions"/> class.
/// </summary>
/// <param name="oauth2AccessToken">The oauth2 access token for making client requests.</param>
/// <param name="oauth2RefreshToken">The oauth2 refresh token for refreshing access tokens.</param>
/// <param name="oauth2AccessTokenExpiresAt">The time when the current access token expires, can be null if using long-lived tokens.</param>
/// <param name="appKey">The app key to be used for refreshing tokens.</param>
/// <param name="appSecret">The app secret to be used for refreshing tokens.</param>
/// <param name="maxRetriesOnError">The maximum retries on a 5xx error.</param>
/// <param name="userAgent">The user agent to use when making requests.</param>
/// <param name="apiHostname">The hostname that will process api requests;
/// this is for internal Dropbox use only.</param>
/// <param name="apiContentHostname">The hostname that will process api content requests;
/// this is for internal Dropbox use only.</param>
/// <param name="apiNotifyHostname">The hostname that will process api notify requests;
/// this is for internal Dropbox use only.</param>
/// <param name="httpClient">The custom http client. If not provided, a default
/// http client will be created.</param>
/// <param name="longPollHttpClient">The custom http client for long poll. If not provided, a default
/// http client with longer timeout will be created.</param>
public DropboxRequestHandlerOptions(
string oauth2AccessToken,
string oauth2RefreshToken,
DateTime? oauth2AccessTokenExpiresAt,
string appKey,
string appSecret,
int maxRetriesOnError,
string userAgent,
string apiHostname,
string apiContentHostname,
string apiNotifyHostname,
HttpClient httpClient,
HttpClient longPollHttpClient)
{
var type = typeof(DropboxRequestHandlerOptions);
#if PORTABLE40
var assembly = type.Assembly;
#else
var assembly = type.GetTypeInfo().Assembly;
#endif
var name = new AssemblyName(assembly.FullName);
var sdkVersion = name.Version.ToString();
this.UserAgent = userAgent == null
? string.Join("/", BaseUserAgent, sdkVersion)
: string.Join("/", userAgent, BaseUserAgent, sdkVersion);
this.HttpClient = httpClient;
this.LongPollHttpClient = longPollHttpClient;
this.OAuth2AccessToken = oauth2AccessToken;
this.OAuth2RefreshToken = oauth2RefreshToken;
this.OAuth2AccessTokenExpiresAt = oauth2AccessTokenExpiresAt;
this.AppKey = appKey;
this.AppSecret = appSecret;
this.MaxClientRetries = maxRetriesOnError;
this.HostMap = new Dictionary<string, string>
{
{ HostType.Api, apiHostname },
{ HostType.ApiContent, apiContentHostname },
{ HostType.ApiNotify, apiNotifyHostname },
};
}
/// <summary>
/// Gets the maximum retries on a 5xx error.
/// </summary>
public int MaxClientRetries { get; private set; }
/// <summary>
/// Gets or sets the OAuth2 token.
/// </summary>
public string OAuth2AccessToken { get; set; }
/// <summary>
/// Gets get the OAuth2 refresh token.
/// </summary>
public string OAuth2RefreshToken { get; private set; }
/// <summary>
/// Gets or sets the time the access token expires at.
/// </summary>
public DateTime? OAuth2AccessTokenExpiresAt { get; set; }
/// <summary>
/// Gets the app key to use when refreshing tokens.
/// </summary>
public string AppKey { get; private set; }
/// <summary>
/// Gets the app secret to use when refreshing tokens.
/// </summary>
public string AppSecret { get; private set; }
/// <summary>
/// Gets the HTTP client use to send requests to the server.
/// </summary>
public HttpClient HttpClient { get; private set; }
/// <summary>
/// Gets the HTTP client use to send long poll requests to the server.
/// </summary>
public HttpClient LongPollHttpClient { get; private set; }
/// <summary>
/// Gets the user agent string.
/// </summary>
public string UserAgent { get; private set; }
/// <summary>
/// Gets the maps from host types to domain names.
/// </summary>
public IDictionary<string, string> HostMap { get; private set; }
}
}
| |
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Views;
using Android.Widget;
using AView = Android.Views.View;
using AListView = Android.Widget.ListView;
using Android.Graphics.Drawables;
namespace Xamarin.Forms.Platform.Android
{
public abstract class CellAdapter : BaseAdapter<object>, AdapterView.IOnItemLongClickListener, ActionMode.ICallback, AdapterView.IOnItemClickListener,
global::Android.Support.V7.View.ActionMode.ICallback
{
readonly Context _context;
ActionMode _actionMode;
Cell _actionModeContext;
bool _actionModeNeedsUpdates;
AView _contextView;
global::Android.Support.V7.View.ActionMode _supportActionMode;
protected CellAdapter(Context context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
}
internal Cell ActionModeContext
{
get { return _actionModeContext; }
set
{
if (_actionModeContext == value)
return;
if (_actionModeContext != null)
((INotifyCollectionChanged)_actionModeContext.ContextActions).CollectionChanged -= OnContextItemsChanged;
ActionModeObject = null;
_actionModeContext = value;
if (_actionModeContext != null)
{
((INotifyCollectionChanged)_actionModeContext.ContextActions).CollectionChanged += OnContextItemsChanged;
ActionModeObject = _actionModeContext.BindingContext;
}
}
}
internal object ActionModeObject { get; set; }
internal AView ContextView
{
get { return _contextView; }
set
{
if (_contextView == value)
return;
if (_contextView != null)
{
var isSelected = (bool)ActionModeContext.GetValue(ListViewAdapter.IsSelectedProperty);
if (isSelected)
SetSelectedBackground(_contextView);
else
UnsetSelectedBackground(_contextView);
}
_contextView = value;
if (_contextView != null)
SetSelectedBackground(_contextView, true);
}
}
public bool OnActionItemClicked(ActionMode mode, IMenuItem item)
{
OnActionItemClickedImpl(item);
_actionMode?.Finish();
return true;
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnActionItemClicked(global::Android.Support.V7.View.ActionMode mode, IMenuItem item)
{
OnActionItemClickedImpl(item);
_supportActionMode?.Finish();
return true;
}
public bool OnCreateActionMode(ActionMode mode, IMenu menu)
{
CreateContextMenu(menu);
return true;
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnCreateActionMode(global::Android.Support.V7.View.ActionMode mode, IMenu menu)
{
CreateContextMenu(menu);
return true;
}
public void OnDestroyActionMode(ActionMode mode)
{
OnDestroyActionModeImpl();
_actionMode.Dispose();
_actionMode = null;
}
void global::Android.Support.V7.View.ActionMode.ICallback.OnDestroyActionMode(global::Android.Support.V7.View.ActionMode mode)
{
OnDestroyActionModeImpl();
_supportActionMode.Dispose();
_supportActionMode = null;
}
public bool OnPrepareActionMode(ActionMode mode, IMenu menu)
{
return OnPrepareActionModeImpl(menu);
}
bool global::Android.Support.V7.View.ActionMode.ICallback.OnPrepareActionMode(global::Android.Support.V7.View.ActionMode mode, IMenu menu)
{
return OnPrepareActionModeImpl(menu);
}
public void OnItemClick(AdapterView parent, AView view, int position, long id)
{
if (_actionMode != null || _supportActionMode != null)
{
var listView = parent as AListView;
if (listView != null)
position -= listView.HeaderViewsCount;
HandleContextMode(view, position);
}
else
HandleItemClick(parent, view, position, id);
}
public bool OnItemLongClick(AdapterView parent, AView view, int position, long id)
{
var listView = parent as AListView;
if (listView != null)
position -= listView.HeaderViewsCount;
return HandleContextMode(view, position);
}
protected abstract Cell GetCellForPosition(int position);
protected virtual void HandleItemClick(AdapterView parent, AView view, int position, long id)
{
}
protected void SetSelectedBackground(AView view, bool isContextTarget = false)
{
int attribute = isContextTarget ? global::Android.Resource.Attribute.ColorLongPressedHighlight : global::Android.Resource.Attribute.ColorActivatedHighlight;
using (var value = new TypedValue())
{
if (_context.Theme.ResolveAttribute(attribute, value, true))
view.SetBackgroundResource(value.ResourceId);
else
view.SetBackgroundResource(global::Android.Resource.Color.HoloBlueDark);
}
}
protected void UnsetSelectedBackground(AView view)
{
view.SetBackgroundResource(0);
}
internal void CloseContextActions()
{
_actionMode?.Finish();
_supportActionMode?.Finish();
}
void CreateContextMenu(IMenu menu)
{
var changed = new PropertyChangedEventHandler(OnContextActionPropertyChanged);
var changing = new PropertyChangingEventHandler(OnContextActionPropertyChanging);
var commandChanged = new EventHandler(OnContextActionCommandCanExecuteChanged);
for (var i = 0; i < ActionModeContext.ContextActions.Count; i++)
{
MenuItem action = ActionModeContext.ContextActions[i];
IMenuItem item = menu.Add(Menu.None, i, Menu.None, action.Text);
if (action.Icon != null)
{
var iconBitmap = new BitmapDrawable(_context.Resources, ResourceManager.GetBitmap(_context.Resources, action.Icon));
if (iconBitmap != null && iconBitmap.Bitmap != null)
item.SetIcon(_context.Resources.GetDrawable(action.Icon));
}
action.PropertyChanged += changed;
action.PropertyChanging += changing;
if (action.Command != null)
action.Command.CanExecuteChanged += commandChanged;
if (!((IMenuItemController)action).IsEnabled)
item.SetEnabled(false);
}
}
bool HandleContextMode(AView view, int position)
{
if (view is EditText || view is TextView || view is SearchView)
return false;
Cell cell = GetCellForPosition(position);
if (cell == null)
return false;
if (_actionMode != null || _supportActionMode != null)
{
if (!cell.HasContextActions)
{
CloseContextActions();
return false;
}
ActionModeContext = cell;
_actionMode?.Invalidate();
_supportActionMode?.Invalidate();
}
else
{
if (!cell.HasContextActions)
return false;
ActionModeContext = cell;
var appCompatActivity = Forms.Context as FormsAppCompatActivity;
if (appCompatActivity == null)
_actionMode = ((Activity)Forms.Context).StartActionMode(this);
else
_supportActionMode = appCompatActivity.StartSupportActionMode(this);
}
ContextView = view;
return true;
}
void OnActionItemClickedImpl(IMenuItem item)
{
int index = item.ItemId;
IMenuItemController action = ActionModeContext.ContextActions[index];
action.Activate();
}
void OnContextActionCommandCanExecuteChanged(object sender, EventArgs eventArgs)
{
_actionModeNeedsUpdates = true;
_actionMode.Invalidate();
}
void OnContextActionPropertyChanged(object sender, PropertyChangedEventArgs e)
{
var action = (MenuItem)sender;
if (e.PropertyName == MenuItem.CommandProperty.PropertyName)
{
if (action.Command != null)
action.Command.CanExecuteChanged += OnContextActionCommandCanExecuteChanged;
}
else
_actionModeNeedsUpdates = true;
}
void OnContextActionPropertyChanging(object sender, PropertyChangingEventArgs e)
{
var action = (MenuItem)sender;
if (e.PropertyName == MenuItem.CommandProperty.PropertyName)
{
if (action.Command != null)
action.Command.CanExecuteChanged -= OnContextActionCommandCanExecuteChanged;
}
}
void OnContextItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
_actionModeNeedsUpdates = true;
_actionMode.Invalidate();
}
void OnDestroyActionModeImpl()
{
var changed = new PropertyChangedEventHandler(OnContextActionPropertyChanged);
var changing = new PropertyChangingEventHandler(OnContextActionPropertyChanging);
var commandChanged = new EventHandler(OnContextActionCommandCanExecuteChanged);
((INotifyCollectionChanged)ActionModeContext.ContextActions).CollectionChanged -= OnContextItemsChanged;
for (var i = 0; i < ActionModeContext.ContextActions.Count; i++)
{
MenuItem action = ActionModeContext.ContextActions[i];
action.PropertyChanged -= changed;
action.PropertyChanging -= changing;
if (action.Command != null)
action.Command.CanExecuteChanged -= commandChanged;
}
ContextView = null;
ActionModeContext = null;
_actionModeNeedsUpdates = false;
}
bool OnPrepareActionModeImpl(IMenu menu)
{
if (_actionModeNeedsUpdates)
{
_actionModeNeedsUpdates = false;
menu.Clear();
CreateContextMenu(menu);
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell.TableControl;
using Roslyn.Utilities;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Suppression
{
/// <summary>
/// Service to compute and apply bulk suppression fixes.
/// </summary>
[Export(typeof(IVisualStudioSuppressionFixService))]
internal sealed class VisualStudioSuppressionFixService : IVisualStudioSuppressionFixService
{
private readonly VisualStudioWorkspaceImpl _workspace;
private readonly IWpfTableControl _tableControl;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ExternalErrorDiagnosticUpdateSource _buildErrorDiagnosticService;
private readonly ICodeFixService _codeFixService;
private readonly IFixMultipleOccurrencesService _fixMultipleOccurencesService;
private readonly ICodeActionEditHandlerService _editHandlerService;
private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService;
private readonly IWaitIndicator _waitIndicator;
[ImportingConstructor]
public VisualStudioSuppressionFixService(
SVsServiceProvider serviceProvider,
VisualStudioWorkspaceImpl workspace,
IDiagnosticAnalyzerService diagnosticService,
ExternalErrorDiagnosticUpdateSource buildErrorDiagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandlerService,
IVisualStudioDiagnosticListSuppressionStateService suppressionStateService,
IWaitIndicator waitIndicator)
{
_workspace = workspace;
_diagnosticService = diagnosticService;
_buildErrorDiagnosticService = buildErrorDiagnosticService;
_codeFixService = codeFixService;
_suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService;
_editHandlerService = editHandlerService;
_waitIndicator = waitIndicator;
_fixMultipleOccurencesService = workspace.Services.GetService<IFixMultipleOccurrencesService>();
var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList;
_tableControl = errorList?.TableControl;
}
public bool AddSuppressions(IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
// Apply suppressions fix in global suppressions file for non-compiler diagnostics and
// in source only for compiler diagnostics.
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly: false, isAddSuppression: true);
if (!ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: false))
{
return false;
}
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: true, onlyCompilerDiagnostics: true, showPreviewChangesDialog: false);
}
public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: true, isSuppressionInSource: suppressInSource, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy projectHierarchyOpt)
{
if (_tableControl == null)
{
return false;
}
Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt);
return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: false, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true);
}
private static Func<Project, bool> GetShouldFixInProjectDelegate(VisualStudioWorkspaceImpl workspace, IVsHierarchy projectHierarchyOpt)
{
if (projectHierarchyOpt == null)
{
return p => true;
}
else
{
var projectIdsForHierarchy = workspace.ProjectTracker.ImmutableProjects
.Where(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic)
.Where(p => p.Hierarchy == projectHierarchyOpt)
.Select(p => workspace.CurrentSolution.GetProject(p.Id).Id)
.ToImmutableHashSet();
return p => projectIdsForHierarchy.Contains(p.Id);
}
}
private async Task<ImmutableArray<DiagnosticData>> GetAllBuildDiagnosticsAsync(Func<Project, bool> shouldFixInProject, CancellationToken cancellationToken)
{
var builder = ArrayBuilder<DiagnosticData>.GetInstance();
var buildDiagnostics = _buildErrorDiagnosticService.GetBuildErrors().Where(d => d.ProjectId != null && d.Severity != DiagnosticSeverity.Hidden);
var solution = _workspace.CurrentSolution;
foreach (var diagnosticsByProject in buildDiagnostics.GroupBy(d => d.ProjectId))
{
cancellationToken.ThrowIfCancellationRequested();
if (diagnosticsByProject.Key == null)
{
// Diagnostics with no projectId cannot be suppressed.
continue;
}
var project = solution.GetProject(diagnosticsByProject.Key);
if (project != null && shouldFixInProject(project))
{
var diagnosticsByDocument = diagnosticsByProject.GroupBy(d => d.DocumentId);
foreach (var group in diagnosticsByDocument)
{
var documentId = group.Key;
if (documentId == null)
{
// Project diagnostics, just add all of them.
builder.AddRange(group);
continue;
}
// For document diagnostics, build does not have the computed text span info.
// So we explicitly calculate the text span from the source text for the diagnostics.
var document = project.GetDocument(documentId);
if (document != null)
{
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var text = await tree.GetTextAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in group)
{
builder.Add(diagnostic.WithCalculatedSpan(text));
}
}
}
}
}
return builder.ToImmutableAndFree();
}
private static string GetFixTitle(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Suppress_diagnostics : ServicesVSResources.Remove_suppressions;
}
private static string GetWaitDialogMessage(bool isAddSuppression)
{
return isAddSuppression ? ServicesVSResources.Computing_suppressions_fix : ServicesVSResources.Computing_remove_suppressions_fix;
}
private IEnumerable<DiagnosticData> GetDiagnosticsToFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression)
{
var diagnosticsToFix = ImmutableHashSet<DiagnosticData>.Empty;
Action<IWaitContext> computeDiagnosticsToFix = context =>
{
var cancellationToken = context.CancellationToken;
// If we are fixing selected diagnostics in error list, then get the diagnostics from error list entry snapshots.
// Otherwise, get all diagnostics from the diagnostic service.
var diagnosticsToFixTask = selectedEntriesOnly ?
_suppressionStateService.GetSelectedItemsAsync(isAddSuppression, cancellationToken) :
GetAllBuildDiagnosticsAsync(shouldFixInProject, cancellationToken);
diagnosticsToFix = diagnosticsToFixTask.WaitAndGetResult(cancellationToken).ToImmutableHashSet();
};
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var result = InvokeWithWaitDialog(computeDiagnosticsToFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (result == WaitIndicatorResult.Canceled)
{
return null;
}
return diagnosticsToFix;
}
private bool ApplySuppressionFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly, isAddSuppression);
return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, selectedEntriesOnly, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics, showPreviewChangesDialog);
}
private bool ApplySuppressionFix(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
{
if (diagnosticsToFix == null)
{
return false;
}
diagnosticsToFix = FilterDiagnostics(diagnosticsToFix, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics);
if (diagnosticsToFix.IsEmpty())
{
// Nothing to fix.
return true;
}
ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap = null;
ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap = null;
var title = GetFixTitle(isAddSuppression);
var waitDialogMessage = GetWaitDialogMessage(isAddSuppression);
var noDiagnosticsToFix = false;
var cancelled = false;
var newSolution = _workspace.CurrentSolution;
HashSet<string> languages = null;
Action<IWaitContext> computeDiagnosticsAndFix = context =>
{
var cancellationToken = context.CancellationToken;
cancellationToken.ThrowIfCancellationRequested();
documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
cancellationToken.ThrowIfCancellationRequested();
projectDiagnosticsToFixMap = isSuppressionInSource ?
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty :
GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
.WaitAndGetResult(cancellationToken);
if (documentDiagnosticsToFixMap == null ||
projectDiagnosticsToFixMap == null ||
(documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty))
{
// Nothing to fix.
noDiagnosticsToFix = true;
return;
}
cancellationToken.ThrowIfCancellationRequested();
// Equivalence key determines what fix will be applied.
// Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed.
var equivalenceKey = isAddSuppression ?
(isSuppressionInSource ? FeaturesResources.in_Source : FeaturesResources.in_Suppression_File) :
FeaturesResources.Remove_Suppression;
// We have different suppression fixers for every language.
// So we need to group diagnostics by the containing project language and apply fixes separately.
languages = new HashSet<string>(projectDiagnosticsToFixMap.Keys.Select(p => p.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language)));
foreach (var language in languages)
{
// Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics,
// show a preview changes dialog and then apply the fix to the workspace.
cancellationToken.ThrowIfCancellationRequested();
var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language);
if (!documentDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
documentDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language);
if (!projectDiagnosticsPerLanguage.IsEmpty)
{
var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
if (suppressionFixer != null)
{
var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
newSolution = _fixMultipleOccurencesService.GetFix(
projectDiagnosticsPerLanguage,
_workspace,
suppressionFixer,
suppressionFixAllProvider,
equivalenceKey,
title,
waitDialogMessage,
cancellationToken);
if (newSolution == null)
{
// User cancelled or fixer threw an exception, so we just bail out.
cancelled = true;
return;
}
}
}
}
};
var result = InvokeWithWaitDialog(computeDiagnosticsAndFix, title, waitDialogMessage);
// Bail out if the user cancelled.
if (cancelled || result == WaitIndicatorResult.Canceled)
{
return false;
}
else if (noDiagnosticsToFix || newSolution == _workspace.CurrentSolution)
{
// No changes.
return true;
}
if (showPreviewChangesDialog)
{
newSolution = FixAllGetFixesService.PreviewChanges(
_workspace.CurrentSolution,
newSolution,
fixAllPreviewChangesTitle: title,
fixAllTopLevelHeader: title,
languageOpt: languages?.Count == 1 ? languages.Single() : null,
workspace: _workspace);
if (newSolution == null)
{
return false;
}
}
waitDialogMessage = isAddSuppression ? ServicesVSResources.Applying_suppressions_fix : ServicesVSResources.Applying_remove_suppressions_fix;
Action<IWaitContext> applyFix = context =>
{
var operations = SpecializedCollections.SingletonEnumerable(new ApplyChangesOperation(newSolution));
var cancellationToken = context.CancellationToken;
_editHandlerService.ApplyAsync(
_workspace,
fromDocument: null,
operations: operations,
title: title,
progressTracker: context.ProgressTracker,
cancellationToken: cancellationToken).Wait(cancellationToken);
};
result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage);
if (result == WaitIndicatorResult.Canceled)
{
return false;
}
// Kick off diagnostic re-analysis for affected projects so that diagnostics gets refreshed.
Task.Run(() =>
{
var reanalyzeDocuments = diagnosticsToFix.Where(d => d.DocumentId != null).Select(d => d.DocumentId).Distinct();
_diagnosticService.Reanalyze(_workspace, documentIds: reanalyzeDocuments, highPriority: true);
});
return true;
}
private static IEnumerable<DiagnosticData> FilterDiagnostics(IEnumerable<DiagnosticData> diagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics)
{
foreach (var diagnostic in diagnostics)
{
var isCompilerDiagnostic = SuppressionHelpers.IsCompilerDiagnostic(diagnostic);
if (onlyCompilerDiagnostics && !isCompilerDiagnostic)
{
continue;
}
if (isAddSuppression)
{
// Compiler diagnostics can only be suppressed in source.
if (!diagnostic.IsSuppressed &&
(isSuppressionInSource || !isCompilerDiagnostic))
{
yield return diagnostic;
}
}
else if (diagnostic.IsSuppressed)
{
yield return diagnostic;
}
}
}
private WaitIndicatorResult InvokeWithWaitDialog(
Action<IWaitContext> action, string waitDialogTitle, string waitDialogMessage)
{
var cancelled = false;
var result = _waitIndicator.Wait(
waitDialogTitle,
waitDialogMessage,
allowCancel: true,
showProgress: true,
action: waitContext =>
{
try
{
action(waitContext);
}
catch (OperationCanceledException)
{
cancelled = true;
}
});
return cancelled ? WaitIndicatorResult.Canceled : result;
}
private static ImmutableDictionary<Document, ImmutableArray<Diagnostic>> GetDocumentDiagnosticsMappedToNewSolution(ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Builder builder = null;
foreach (var kvp in documentDiagnosticsToFixMap)
{
if (kvp.Key.Project.Language != language)
{
continue;
}
var document = newSolution.GetDocument(kvp.Key.Id);
if (document != null)
{
builder = builder ?? ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
builder.Add(document, kvp.Value);
}
}
return builder != null ? builder.ToImmutable() : ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
private static ImmutableDictionary<Project, ImmutableArray<Diagnostic>> GetProjectDiagnosticsMappedToNewSolution(ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap, Solution newSolution, string language)
{
ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Builder projectDiagsBuilder = null;
foreach (var kvp in projectDiagnosticsToFixMap)
{
if (kvp.Key.Language != language)
{
continue;
}
var project = newSolution.GetProject(kvp.Key.Id);
if (project != null)
{
projectDiagsBuilder = projectDiagsBuilder ?? ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
projectDiagsBuilder.Add(project, kvp.Value);
}
}
return projectDiagsBuilder != null ? projectDiagsBuilder.ToImmutable() : ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
private static CodeFixProvider GetSuppressionFixer(IEnumerable<Diagnostic> diagnostics, string language, ICodeFixService codeFixService)
{
// Fetch the suppression fixer to apply the fix.
return codeFixService.GetSuppressionFixer(language, diagnostics.Select(d => d.Id));
}
private async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isDocumentDiagnostic = d => d.DataLocation != null && d.HasTextSpan;
var builder = ImmutableDictionary.CreateBuilder<DocumentId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isDocumentDiagnostic))
{
List<DiagnosticData> diagnosticsPerDocument;
if (!builder.TryGetValue(diagnosticData.DocumentId, out diagnosticsPerDocument))
{
diagnosticsPerDocument = new List<DiagnosticData>();
builder[diagnosticData.DocumentId] = diagnosticsPerDocument;
}
diagnosticsPerDocument.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>();
var latestDocumentDiagnosticsMapOpt = filterStaleDiagnostics ? new Dictionary<DocumentId, ImmutableHashSet<DiagnosticData>>() : null;
foreach (var group in builder.GroupBy(kvp => kvp.Key.ProjectId))
{
var projectId = group.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = group.SelectMany(kvp => kvp.Value.Select(d => d.Id)).ToImmutableHashSet();
var latestProjectDiagnostics = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false)).Where(isDocumentDiagnostic);
latestDocumentDiagnosticsMapOpt.Clear();
foreach (var kvp in latestProjectDiagnostics.Where(d => d.DocumentId != null).GroupBy(d => d.DocumentId))
{
latestDocumentDiagnosticsMapOpt.Add(kvp.Key, kvp.ToImmutableHashSet());
}
}
foreach (var documentDiagnostics in group)
{
var document = project.GetDocument(documentDiagnostics.Key);
if (document == null)
{
continue;
}
IEnumerable<DiagnosticData> documentDiagnosticsToFix;
if (filterStaleDiagnostics)
{
ImmutableHashSet<DiagnosticData> latestDocumentDiagnostics;
if (!latestDocumentDiagnosticsMapOpt.TryGetValue(document.Id, out latestDocumentDiagnostics))
{
// Ignore stale diagnostics in error list.
latestDocumentDiagnostics = ImmutableHashSet<DiagnosticData>.Empty;
}
// Filter out stale diagnostics in error list.
documentDiagnosticsToFix = documentDiagnostics.Value.Where(d => latestDocumentDiagnostics.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
documentDiagnosticsToFix = documentDiagnostics.Value;
}
if (documentDiagnosticsToFix.Any())
{
var diagnostics = await documentDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(document, diagnostics.ToImmutableArray());
}
}
}
return finalBuilder.ToImmutableDictionary();
}
private async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken)
{
Func<DiagnosticData, bool> isProjectDiagnostic = d => d.DataLocation == null && d.ProjectId != null;
var builder = ImmutableDictionary.CreateBuilder<ProjectId, List<DiagnosticData>>();
foreach (var diagnosticData in diagnosticsToFix.Where(isProjectDiagnostic))
{
List<DiagnosticData> diagnosticsPerProject;
if (!builder.TryGetValue(diagnosticData.ProjectId, out diagnosticsPerProject))
{
diagnosticsPerProject = new List<DiagnosticData>();
builder[diagnosticData.ProjectId] = diagnosticsPerProject;
}
diagnosticsPerProject.Add(diagnosticData);
}
if (builder.Count == 0)
{
return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty;
}
var finalBuilder = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>();
var latestDiagnosticsToFixOpt = filterStaleDiagnostics ? new HashSet<DiagnosticData>() : null;
foreach (var kvp in builder)
{
var projectId = kvp.Key;
var project = _workspace.CurrentSolution.GetProject(projectId);
if (project == null || !shouldFixInProject(project))
{
continue;
}
var diagnostics = kvp.Value;
IEnumerable<DiagnosticData> projectDiagnosticsToFix;
if (filterStaleDiagnostics)
{
var uniqueDiagnosticIds = diagnostics.Select(d => d.Id).ToImmutableHashSet();
var latestDiagnosticsFromDiagnosticService = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken)
.ConfigureAwait(false));
latestDiagnosticsToFixOpt.Clear();
latestDiagnosticsToFixOpt.AddRange(latestDiagnosticsFromDiagnosticService.Where(isProjectDiagnostic));
// Filter out stale diagnostics in error list.
projectDiagnosticsToFix = diagnostics.Where(d => latestDiagnosticsFromDiagnosticService.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d));
}
else
{
projectDiagnosticsToFix = diagnostics;
}
if (projectDiagnosticsToFix.Any())
{
var projectDiagnostics = await projectDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false);
finalBuilder.Add(project, projectDiagnostics.ToImmutableArray());
}
}
return finalBuilder.ToImmutableDictionary();
}
}
}
| |
// 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.Numerics.Tests
{
public class ComparisonTest
{
private const int NumberOfRandomIterations = 1;
[Fact]
public static void ComparisonTests()
{
int seed = 100;
RunTests(seed);
}
public static void RunTests(int seed)
{
Random random = new Random(seed);
RunPositiveTests(random);
RunNegativeTests(random);
}
private static void RunPositiveTests(Random random)
{
BigInteger bigInteger1, bigInteger2;
int expectedResult;
byte[] byteArray;
bool isNegative;
//1 Inputs from BigInteger Properties
// BigInteger.MinusOne, BigInteger.MinusOne
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne, 0);
// BigInteger.MinusOne, BigInteger.Zero
VerifyComparison(BigInteger.MinusOne, BigInteger.Zero, -1);
// BigInteger.MinusOne, BigInteger.One
VerifyComparison(BigInteger.MinusOne, BigInteger.One, -1);
// BigInteger.MinusOne, Large Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int64.MaxValue), 1);
// BigInteger.MinusOne, Small Negative
VerifyComparison(BigInteger.MinusOne, -1L * ((BigInteger)Int16.MaxValue), 1);
// BigInteger.MinusOne, Large Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.MinusOne, Small Number
VerifyComparison(BigInteger.MinusOne, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.MinusOne, One Less
VerifyComparison(BigInteger.MinusOne, BigInteger.MinusOne - 1, 1);
// BigInteger.Zero, BigInteger.Zero
VerifyComparison(BigInteger.Zero, BigInteger.Zero, 0);
// BigInteger.Zero, Large Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.Zero, Small Negative
VerifyComparison(BigInteger.Zero, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.Zero, Large Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.Zero, Small Number
VerifyComparison(BigInteger.Zero, (BigInteger)Int32.MaxValue - 1, -1);
// BigInteger.One, BigInteger.One
VerifyComparison(BigInteger.One, BigInteger.One, 0);
// BigInteger.One, BigInteger.MinusOne
VerifyComparison(BigInteger.One, BigInteger.MinusOne, 1);
// BigInteger.One, BigInteger.Zero
VerifyComparison(BigInteger.One, BigInteger.Zero, 1);
// BigInteger.One, Large Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue + 1), 1);
// BigInteger.One, Small Negative
VerifyComparison(BigInteger.One, -1 * ((BigInteger)Int32.MaxValue - 1), 1);
// BigInteger.One, Large Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue + 1, -1);
// BigInteger.One, Small Number
VerifyComparison(BigInteger.One, (BigInteger)Int32.MaxValue - 1, -1);
//Basic Checks
// BigInteger.MinusOne, (Int32) -1
VerifyComparison(BigInteger.MinusOne, (Int32)(-1), 0);
// BigInteger.Zero, (Int32) 0
VerifyComparison(BigInteger.Zero, (Int32)(0), 0);
// BigInteger.One, 1
VerifyComparison(BigInteger.One, (Int32)(1), 0);
//1 Inputs Around the boundary of UInt32
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue - 1, -1L * (BigInteger)UInt32.MaxValue - 1, 0);
// -1 * UInt32.MaxValue, -1 * UInt32.MaxValue -1
VerifyComparison(-1L * (BigInteger)UInt32.MaxValue, (-1L * (BigInteger)UInt32.MaxValue) - 1L, 1);
// UInt32.MaxValue, -1 * UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, -1L * (BigInteger)UInt32.MaxValue, 1);
// UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue, 0);
// UInt32.MaxValue, UInt32.MaxValue + 1
VerifyComparison((BigInteger)UInt32.MaxValue, (BigInteger)UInt32.MaxValue + 1, -1);
// UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, (BigInteger)UInt64.MaxValue, 0);
// UInt64.MaxValue + 1, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
//Other cases
// -1 * Large Bigint, -1 * Large BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue + 1), -1L * ((BigInteger)Int32.MaxValue + 1), 0);
// Large Bigint, Large Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue + 1, -1L * ((BigInteger)Int32.MaxValue + 1), 1);
// Large Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, (BigInteger)UInt32.MaxValue, 1);
// Large Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue + 1, ((BigInteger)Int32.MaxValue) + 2, -1);
// -1 * Small Bigint, -1 * Small BigInt
VerifyComparison(-1L * ((BigInteger)Int32.MaxValue - 1), -1L * ((BigInteger)Int32.MaxValue - 1), 0);
// Small Bigint, Small Negative BigInt
VerifyComparison((BigInteger)Int32.MaxValue - 1, -1L * ((BigInteger)Int32.MaxValue - 1), 1);
// Small Bigint, UInt32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, (BigInteger)UInt32.MaxValue - 1, -1);
// Small Bigint, One More
VerifyComparison((BigInteger)Int32.MaxValue - 2, ((BigInteger)Int32.MaxValue) - 1, -1);
//BigInteger vs. Int32
// One Larger (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue + 1, Int32.MaxValue, 1);
// Larger BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, Int32.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int32.MaxValue, -1);
// One Smaller (BigInteger), Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue - 1, Int32.MaxValue, -1);
// (BigInteger) Int32.MaxValue, Int32.MaxValue
VerifyComparison((BigInteger)Int32.MaxValue, Int32.MaxValue, 0);
//BigInteger vs. UInt32
// One Larger (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue + 1, UInt32.MaxValue, 1);
// Larger BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, UInt32.MaxValue, 1);
// Smaller BigInteger, UInt32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt32.MaxValue, -1);
// One Smaller (BigInteger), UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue - 1, UInt32.MaxValue, -1);
// (BigInteger UInt32.MaxValue, UInt32.MaxValue
VerifyComparison((BigInteger)UInt32.MaxValue, UInt32.MaxValue, 0);
//BigInteger vs. UInt64
// One Larger (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 1, UInt64.MaxValue, 1);
// Larger BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, UInt64.MaxValue, 1);
// Smaller BigInteger, UInt64.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int16.MaxValue - 1, UInt64.MaxValue, -1);
VerifyComparison((BigInteger)Int32.MaxValue + 1, UInt64.MaxValue, -1);
// One Smaller (BigInteger), UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue - 1, UInt64.MaxValue, -1);
// (BigInteger UInt64.MaxValue, UInt64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue, UInt64.MaxValue, 0);
//BigInteger vs. Int64
// One Smaller (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue - 1, Int64.MaxValue, -1);
// Larger BigInteger, Int64.MaxValue
VerifyComparison((BigInteger)UInt64.MaxValue + 100, Int64.MaxValue, 1);
// Smaller BigInteger, Int32.MaxValue
VerifyComparison((BigInteger)Int16.MinValue - 1, Int64.MaxValue, -1);
// (BigInteger Int64.MaxValue, Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue, Int64.MaxValue, 0);
// One Larger (BigInteger), Int64.MaxValue
VerifyComparison((BigInteger)Int64.MaxValue + 1, Int64.MaxValue, 1);
//1 Random Inputs
// Random BigInteger only differs by sign
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b2 = new BigInteger(byteArray);
if (b2 > (BigInteger)0)
{
VerifyComparison(b2, -1L * b2, 1);
}
else
{
VerifyComparison(b2, -1L * b2, -1);
}
}
// Random BigInteger, Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
expectedResult = GetRandomInputForComparison(random, out bigInteger1, out bigInteger2);
VerifyComparison(bigInteger1, bigInteger2, expectedResult);
}
// Random BigInteger
for (int i = 0; i < NumberOfRandomIterations; ++i)
{
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(new BigInteger(byteArray), isNegative, new BigInteger(byteArray), isNegative, 0);
}
//1 Identical values constructed multiple ways
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=true
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), true, 0);
// BigInteger.Zero, BigInteger constructed with a byte[] isNegative=false
VerifyComparison(BigInteger.Zero, false, new BigInteger(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.Zero, BigInteger constructed from an Int64
VerifyComparison(BigInteger.Zero, 0L, 0);
// BigInteger.Zero, BigInteger constructed from a Double
VerifyComparison(BigInteger.Zero, (BigInteger)0d, 0);
// BigInteger.Zero, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.Zero, (BigInteger)0, 0);
// BigInteger.Zero, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) + (-1 * new BigInteger(byteArray)), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, new BigInteger(byteArray) - new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 * new BigInteger(byteArray), isNegative, 0);
// BigInteger.Zero, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.Zero, false, 0 / new BigInteger(byteArray), isNegative, 0);
// BigInteger.One, BigInteger constructed with a byte[]
VerifyComparison(BigInteger.One, false, new BigInteger(new byte[] { 1, 0, 0, 0, 0, 0, 0, 0 }), false, 0);
// BigInteger.One, BigInteger constructed from an Int64
VerifyComparison(BigInteger.One, 1L, 0);
// BigInteger.One, BigInteger constructed from a Double
VerifyComparison(BigInteger.One, (BigInteger)1d, 0);
// BigInteger.One, BigInteger constructed from a Decimal
VerifyComparison(BigInteger.One, (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Addition
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, false, (((BigInteger)(-1)) * new BigInteger(byteArray)) + (new BigInteger(byteArray)) + 1, false, 0);
// BigInteger.One, BigInteger constructed with Subtraction
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
BigInteger b = new BigInteger(byteArray);
if (b > (BigInteger)0)
{
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
}
else
{
b = -1L * b;
VerifyComparison(BigInteger.One, false, (b + 1) - (b), false, 0);
b = -1L * b;
}
// BigInteger.One, BigInteger constructed with Multiplication
byteArray = GetRandomByteArray(random);
isNegative = 0 == random.Next(0, 2);
VerifyComparison(BigInteger.One, (BigInteger)1 * (BigInteger)1, 0);
// BigInteger.One, BigInteger constructed with Division
do
{
byteArray = GetRandomByteArray(random);
}
while (MyBigIntImp.IsZero(byteArray));
BigInteger b1 = new BigInteger(byteArray);
VerifyComparison(BigInteger.One, false, b1 / b1, false, 0);
}
private static void RunNegativeTests(Random random)
{
// BigInteger.Zero, 0
Assert.Equal(false, BigInteger.Zero.Equals((Object)0));
// BigInteger.Zero, null
Assert.Equal(false, BigInteger.Zero.Equals((Object)null));
// BigInteger.Zero, string
Assert.Equal(false, BigInteger.Zero.Equals((Object)"0"));
}
[Fact]
public static void IComparable_Invalid()
{
IComparable comparable = new BigInteger();
Assert.Equal(1, comparable.CompareTo(null));
Assert.Throws<ArgumentException>("obj", () => comparable.CompareTo(0)); // Obj is not a BigInteger
}
private static void VerifyComparison(BigInteger x, BigInteger y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
IComparable comparableX = x;
IComparable comparableY = y;
VerifyCompareResult(expectedResult, comparableX.CompareTo(y), "comparableX.CompareTo(y)");
VerifyCompareResult(-expectedResult, comparableY.CompareTo(x), "comparableY.CompareTo(x)");
VerifyCompareResult(expectedResult, BigInteger.Compare(x, y), "Compare(x,y)");
VerifyCompareResult(-expectedResult, BigInteger.Compare(y, x), "Compare(y,x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt32 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, Int64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, UInt64 y, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(x.ToString(), ((BigInteger)y).ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.NotEqual(x.ToString(), ((BigInteger)y).ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(((BigInteger)y).GetHashCode(), ((BigInteger)y).GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyComparison(BigInteger x, bool IsXNegative, BigInteger y, bool IsYNegative, int expectedResult)
{
bool expectedEquals = 0 == expectedResult;
bool expectedLessThan = expectedResult < 0;
bool expectedGreaterThan = expectedResult > 0;
if (IsXNegative == true)
{
x = x * -1;
}
if (IsYNegative == true)
{
y = y * -1;
}
Assert.Equal(expectedEquals, x == y);
Assert.Equal(expectedEquals, y == x);
Assert.Equal(!expectedEquals, x != y);
Assert.Equal(!expectedEquals, y != x);
Assert.Equal(expectedEquals, x.Equals(y));
Assert.Equal(expectedEquals, y.Equals(x));
Assert.Equal(expectedEquals, x.Equals((Object)y));
Assert.Equal(expectedEquals, y.Equals((Object)x));
VerifyCompareResult(expectedResult, x.CompareTo(y), "x.CompareTo(y)");
VerifyCompareResult(-expectedResult, y.CompareTo(x), "y.CompareTo(x)");
if (expectedEquals)
{
Assert.Equal(x.GetHashCode(), y.GetHashCode());
Assert.Equal(x.ToString(), y.ToString());
}
else
{
Assert.NotEqual(x.GetHashCode(), y.GetHashCode());
Assert.NotEqual(x.ToString(), y.ToString());
}
Assert.Equal(x.GetHashCode(), x.GetHashCode());
Assert.Equal(y.GetHashCode(), y.GetHashCode());
Assert.Equal(expectedLessThan, x < y);
Assert.Equal(expectedGreaterThan, y < x);
Assert.Equal(expectedGreaterThan, x > y);
Assert.Equal(expectedLessThan, y > x);
Assert.Equal(expectedLessThan || expectedEquals, x <= y);
Assert.Equal(expectedGreaterThan || expectedEquals, y <= x);
Assert.Equal(expectedGreaterThan || expectedEquals, x >= y);
Assert.Equal(expectedLessThan || expectedEquals, y >= x);
}
private static void VerifyCompareResult(int expected, int actual, string message)
{
if (0 == expected)
{
Assert.Equal(expected, actual);
}
else if (0 > expected)
{
Assert.InRange(actual, int.MinValue, -1);
}
else if (0 < expected)
{
Assert.InRange(actual, 1, int.MaxValue);
}
}
private static int GetRandomInputForComparison(Random random, out BigInteger bigInteger1, out BigInteger bigInteger2)
{
byte[] byteArray1, byteArray2;
bool sameSize = 0 == random.Next(0, 2);
if (sameSize)
{
int size = random.Next(0, 1024);
byteArray1 = GetRandomByteArray(random, size);
byteArray2 = GetRandomByteArray(random, size);
}
else
{
byteArray1 = GetRandomByteArray(random);
byteArray2 = GetRandomByteArray(random);
}
bigInteger1 = new BigInteger(byteArray1);
bigInteger2 = new BigInteger(byteArray2);
if (bigInteger1 > 0 && bigInteger2 > 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0 != byteArray2[i])
{
return -1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0 != byteArray1[i])
{
return 1;
}
}
}
}
else if ((bigInteger1 < 0 && bigInteger2 > 0) || (bigInteger1 == 0 && bigInteger2 > 0) || (bigInteger1 < 0 && bigInteger2 == 0))
{
return -1;
}
else if ((bigInteger1 > 0 && bigInteger2 < 0) || (bigInteger1 == 0 && bigInteger2 < 0) || (bigInteger1 > 0 && bigInteger2 == 0))
{
return 1;
}
else if (bigInteger1 != 0 && bigInteger2 != 0)
{
if (byteArray1.Length < byteArray2.Length)
{
for (int i = byteArray2.Length - 1; byteArray1.Length <= i; --i)
{
if (0xFF != byteArray2[i])
{
return 1;
}
}
}
else if (byteArray1.Length > byteArray2.Length)
{
for (int i = byteArray1.Length - 1; byteArray2.Length <= i; --i)
{
if (0xFF != byteArray1[i])
{
return -1;
}
}
}
}
for (int i = Math.Min(byteArray1.Length, byteArray2.Length) - 1; 0 <= i; --i)
{
if (byteArray1[i] > byteArray2[i])
{
return 1;
}
else if (byteArray1[i] < byteArray2[i])
{
return -1;
}
}
return 0;
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 1024));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShuffleUInt321()
{
var test = new ImmUnaryOpTest__ShuffleUInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local 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 ImmUnaryOpTest__ShuffleUInt321
{
private struct TestStruct
{
public Vector128<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShuffleUInt321 testClass)
{
var result = Sse2.Shuffle(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector128<UInt32> _clsVar;
private Vector128<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static ImmUnaryOpTest__ShuffleUInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public ImmUnaryOpTest__ShuffleUInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.Shuffle(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.Shuffle(
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.Shuffle(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.Shuffle), new Type[] { typeof(Vector128<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.Shuffle(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr);
var result = Sse2.Shuffle(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.Shuffle(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr));
var result = Sse2.Shuffle(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShuffleUInt321();
var result = Sse2.Shuffle(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.Shuffle(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.Shuffle(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _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(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp[1] != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (firstOp[0] != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Shuffle)}<UInt32>(Vector128<UInt32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.CodeDom;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Messaging
{
// <summary>
// This class is used on the client only.
// It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side.
//
// There is one ProxiedMessageCenter instance per OutsideRuntimeClient. There can be multiple ProxiedMessageCenter instances
// in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not
// generally done in practice.
//
// Each ProxiedMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection
// to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to
// the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together
// based on their hash code mod a reasonably large number (currently 8192).
//
// When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known
// gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to
// the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the
// connection is live.
//
// Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to
// reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily)
// dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected).
// There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes.
//
// The list of known gateways is managed by the GatewayManager class. See comments there for details...
// =======================================================================================================================================
// Locking and lock protocol:
// The ProxiedMessageCenter instance itself may be accessed by many client threads simultaneously, and each GatewayConnection instance
// is accessed by its own thread, by the thread for its Receiver, and potentially by client threads from within the ProxiedMessageCenter.
// Thus, we need locks to protect the various data structured from concurrent modifications.
//
// Each GatewayConnection instance has a "lockable" field that is used to lock local information. This lock is used by both the GatewayConnection
// thread and the Receiver thread.
//
// The ProxiedMessageCenter instance also has a "lockable" field. This lock is used by any client thread running methods within the instance.
//
// Note that we take care to ensure that client threads never need locked access to GatewayConnection state and GatewayConnection threads never need
// locked access to ProxiedMessageCenter state. Thus, we don't need to worry about lock ordering across these objects.
//
// Finally, the GatewayManager instance within the ProxiedMessageCenter has two collections, knownGateways and knownDead, that it needs to
// protect with locks. Rather than using a "lockable" field, each collection is lcoked to protect the collection.
// All sorts of threads can run within the GatewayManager, including client threads and GatewayConnection threads, so we need to
// be careful about locks here. The protocol we use is to always take GatewayManager locks last, to only take them within GatewayManager methods,
// and to always release them before returning from the method. In addition, we never simultaneously hold the knownGateways and knownDead locks,
// so there's no need to worry about the order in which we take and release those locks.
// </summary>
internal class ProxiedMessageCenter : IMessageCenter, IDisposable
{
#region Constants
internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts
internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server
#endregion
internal GrainId ClientId { get; private set; }
internal bool Running { get; private set; }
internal readonly GatewayManager GatewayManager;
internal readonly BlockingCollection<Message> PendingInboundMessages;
private readonly Dictionary<Uri, GatewayConnection> gatewayConnections;
private int numMessages;
// The grainBuckets array is used to select the connection to use when sending an ordered message to a grain.
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
private readonly WeakReference[] grainBuckets;
private readonly Logger logger;
private readonly object lockable;
public SiloAddress MyAddress { get; private set; }
public IMessagingConfiguration MessagingConfiguration { get; private set; }
private readonly QueueTrackingStatistic queueTracking;
private int numberOfConnectedGateways = 0;
private MessageFactory messageFactory;
public ProxiedMessageCenter(
ClientConfiguration config,
IPAddress localAddress,
int gen,
GrainId clientId,
IGatewayListProvider gatewayListProvider,
MessageFactory messageFactory)
{
lockable = new object();
MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen);
ClientId = clientId;
this.messageFactory = messageFactory;
Running = false;
MessagingConfiguration = config;
GatewayManager = new GatewayManager(config, gatewayListProvider);
PendingInboundMessages = new BlockingCollection<Message>();
gatewayConnections = new Dictionary<Uri, GatewayConnection>();
numMessages = 0;
grainBuckets = new WeakReference[config.ClientSenderBuckets];
logger = LogManager.GetLogger("Messaging.ProxiedMessageCenter", LoggerType.Runtime);
if (logger.IsVerbose) logger.Verbose("Proxy grain client constructed");
IntValueStatistic.FindOrCreate(StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () =>
{
lock (gatewayConnections)
{
return gatewayConnections.Values.Count(conn => conn.IsLive);
}
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking = new QueueTrackingStatistic("ClientReceiver");
}
}
public void Start()
{
Running = true;
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStartExecution();
}
if (logger.IsVerbose) logger.Verbose("Proxy grain client started");
}
public void PrepareToStop()
{
// put any pre stop logic here.
}
public void Stop()
{
Running = false;
Utils.SafeExecute(() =>
{
PendingInboundMessages.CompleteAdding();
});
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnStopExecution();
}
GatewayManager.Stop();
foreach (var gateway in gatewayConnections.Values)
{
gateway.Stop();
}
}
public void SendMessage(Message msg)
{
GatewayConnection gatewayConnection = null;
bool startRequired = false;
// If there's a specific gateway specified, use it
if (msg.TargetSilo != null)
{
Uri addr = msg.TargetSilo.ToGatewayUri();
lock (lockable)
{
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose("Creating gateway to {0} for pre-addressed message", addr);
startRequired = true;
}
}
}
// For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion.
else if (msg.TargetGrain.IsSystemTarget || msg.IsUnordered)
{
// Get the cached list of live gateways.
// Pick a next gateway name in a round robin fashion.
// See if we have a live connection to it.
// If Yes, use it.
// If not, create a new GatewayConnection and start it.
// If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames.
lock (lockable)
{
int msgNumber = numMessages;
numMessages = unchecked(numMessages + 1);
IList<Uri> gatewayNames = GatewayManager.GetLiveGateways();
int numGateways = gatewayNames.Count;
if (numGateways == 0)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
Uri addr = gatewayNames[msgNumber % numGateways];
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayUnordered, "Creating gateway to {0} for unordered message to grain {1}", addr, msg.TargetGrain);
startRequired = true;
}
// else - Fast path - we've got a live gatewayConnection to use
}
}
// Otherwise, use the buckets to ensure ordering.
else
{
var index = msg.TargetGrain.GetHashCode_Modulo((uint)grainBuckets.Length);
lock (lockable)
{
// Repeated from above, at the declaration of the grainBuckets array:
// Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket.
// Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used
// if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is
// false, then a new gateway is selected using the gateway manager, and a new connection established if necessary.
var weakRef = grainBuckets[index];
if ((weakRef != null) && weakRef.IsAlive)
{
gatewayConnection = weakRef.Target as GatewayConnection;
}
if ((gatewayConnection == null) || !gatewayConnection.IsLive)
{
var addr = GatewayManager.GetLiveGateway();
if (addr == null)
{
RejectMessage(msg, "No gateways available");
logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, GatewayManager);
return;
}
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain);
if (!gatewayConnections.TryGetValue(addr, out gatewayConnection) || !gatewayConnection.IsLive)
{
gatewayConnection = new GatewayConnection(addr, this, this.messageFactory);
gatewayConnections[addr] = gatewayConnection;
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index,
msg.TargetGrain.GetHashCode().ToString("x"));
startRequired = true;
}
grainBuckets[index] = new WeakReference(gatewayConnection);
}
}
}
if (startRequired)
{
gatewayConnection.Start();
if (!gatewayConnection.IsLive)
{
// if failed to start Gateway connection (failed to connect), try sending this msg to another Gateway.
RejectOrResend(msg);
return;
}
}
try
{
gatewayConnection.QueueRequest(msg);
if (logger.IsVerbose2) logger.Verbose2(ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, gatewayConnection.Address);
}
catch (InvalidOperationException)
{
// This exception can be thrown if the gateway connection we selected was closed since we checked (i.e., we lost the race)
// If this happens, we reject if the message is targeted to a specific silo, or try again if not
RejectOrResend(msg);
}
}
private void RejectOrResend(Message msg)
{
if (msg.TargetSilo != null)
{
RejectMessage(msg, String.Format("Target silo {0} is unavailable", msg.TargetSilo));
}
else
{
SendMessage(msg);
}
}
public Task<IGrainTypeResolver> GetTypeCodeMap(IInternalGrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetClusterTypeCodeMap();
}
public Task<Streams.ImplicitStreamSubscriberTable> GetImplicitStreamSubscriberTable(IInternalGrainFactory grainFactory)
{
var silo = GetLiveGatewaySiloAddress();
return GetTypeManager(silo, grainFactory).GetImplicitStreamSubscriberTable(silo);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public Message WaitMessage(Message.Categories type, CancellationToken ct)
{
try
{
if (ct.IsCancellationRequested)
{
return null;
}
// Don't pass CancellationToken to Take. It causes too much spinning.
Message msg = PendingInboundMessages.Take();
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnDeQueueRequest(msg);
}
#endif
return msg;
}
#if !NETSTANDARD
catch (ThreadAbortException exc)
{
// Silo may be shutting-down, so downgrade to verbose log
logger.Verbose(ErrorCode.ProxyClient_ThreadAbort, "Received thread abort exception -- exiting. {0}", exc);
Thread.ResetAbort();
return null;
}
#endif
catch (OperationCanceledException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received operation cancelled exception -- exiting. {0}", exc);
return null;
}
catch (ObjectDisposedException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Object Disposed exception -- exiting. {0}", exc);
return null;
}
catch (InvalidOperationException exc)
{
logger.Verbose(ErrorCode.ProxyClient_OperationCancelled, "Received Invalid Operation exception -- exiting. {0}", exc);
return null;
}
catch (Exception ex)
{
logger.Error(ErrorCode.ProxyClient_ReceiveError, "Unexpected error getting an inbound message", ex);
return null;
}
}
internal void QueueIncomingMessage(Message msg)
{
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectQueueStats)
{
queueTracking.OnEnQueueRequest(1, PendingInboundMessages.Count, msg);
}
#endif
PendingInboundMessages.Add(msg);
}
private void RejectMessage(Message msg, string reasonFormat, params object[] reasonParams)
{
if (!Running) return;
var reason = String.Format(reasonFormat, reasonParams);
if (msg.Direction != Message.Directions.Request)
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
}
else
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason);
QueueIncomingMessage(error);
}
}
/// <summary>
/// For testing use only
/// </summary>
public void Disconnect()
{
foreach (var connection in gatewayConnections.Values)
{
connection.Stop();
}
}
/// <summary>
/// For testing use only.
/// </summary>
public void Reconnect()
{
throw new NotImplementedException("Reconnect");
}
#region Random IMessageCenter stuff
public int SendQueueLength
{
get { return 0; }
}
public int ReceiveQueueLength
{
get { return 0; }
}
#endregion
private IClusterTypeManager GetTypeManager(SiloAddress destination, IInternalGrainFactory grainFactory)
{
return grainFactory.GetSystemTarget<IClusterTypeManager>(Constants.TypeManagerId, destination);
}
private SiloAddress GetLiveGatewaySiloAddress()
{
var gateway = GatewayManager.GetLiveGateway();
if (gateway == null)
{
throw new OrleansException("Not connected to a gateway");
}
return gateway.ToSiloAddress();
}
internal void UpdateClientId(GrainId clientId)
{
if (ClientId.Category != UniqueKey.Category.Client)
throw new InvalidOperationException("Only handshake client ID can be updated with a cluster ID.");
if (clientId.Category != UniqueKey.Category.GeoClient)
throw new ArgumentException("Handshake client ID can only be updated with a geo client.", nameof(clientId));
ClientId = clientId;
}
internal void OnGatewayConnectionOpen()
{
Interlocked.Increment(ref numberOfConnectedGateways);
}
internal void OnGatewayConnectionClosed()
{
if (Interlocked.Decrement(ref numberOfConnectedGateways) == 0)
{
GrainClient.NotifyClusterConnectionLost();
}
}
public void Dispose()
{
PendingInboundMessages.Dispose();
if (gatewayConnections != null)
foreach (var item in gatewayConnections)
{
item.Value.Dispose();
}
GatewayManager.Dispose();
}
}
}
| |
#if TODO_XAML
using System;
using System.Linq;
using Eto.Forms;
using Eto.Drawing;
using sw = Windows.UI.Xaml;
using swm = Windows.UI.Xaml.Media;
using swc = Windows.UI.Xaml.Controls;
using swi = Windows.UI.Xaml.Input;
using Eto.WinRT.CustomControls;
//using Eto.WinRT.Forms.Menu;
namespace Eto.WinRT.Forms
{
public interface IWpfWindow
{
sw.Window Control { get; }
}
/// <summary>
/// Window handler.
/// </summary>
/// <copyright>(c) 2014 by Vivek Jhaveri</copyright>
/// <copyright>(c) 2012-2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public abstract class WpfWindow<TControl, TWidget> : WpfPanel<TControl, TWidget>, IWindow, IWpfWindow
where TControl : sw.Window
where TWidget : Window
{
Icon icon;
MenuBar menu;
ToolBar toolBar;
#if TODO_XAML
swc.DockPanel main;
#endif
swc.ContentControl menuHolder;
swc.ContentControl toolBarHolder;
#if TODO_XAML
swc.DockPanel content;
#else
swc.Panel content;
#endif
Size? initialClientSize;
bool resizable = true;
bool maximizable = true;
bool minimizable = true;
protected override void Initialize ()
{
#if TODO_XAML
content = new swc.DockPanel();
#else
content = new Panel();
#endif
base.Initialize();
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
Control.SnapsToDevicePixels = true;
Control.UseLayoutRounding = true;
#if TODO_XAML
main = new swc.DockPanel();
#endif
menuHolder = new swc.ContentControl { IsTabStop = false };
toolBarHolder = new swc.ContentControl { IsTabStop = false };
content.Background = Windows.UI.Xaml.SystemColors.ControlBrush;
swc.DockPanel.SetDock (menuHolder, swc.Dock.Top);
swc.DockPanel.SetDock (toolBarHolder, swc.Dock.Top);
#if TODO_XAML
main.Children.Add (menuHolder);
main.Children.Add (toolBarHolder);
main.Children.Add (content);
Control.Content = main;
#endif
Control.Loaded += delegate
{
SetResizeMode();
if (initialClientSize != null)
{
initialClientSize = null;
SetContentSize();
}
// stop form from auto-sizing after it is shown
Control.SizeToContent = sw.SizeToContent.Manual;
Control.MoveFocus(new swi.TraversalRequest(swi.FocusNavigationDirection.Next));
};
// needed to handle Application.Terminating event
HandleEvent (Window.ClosingEvent);
}
protected override void SetContentScale(bool xscale, bool yscale)
{
base.SetContentScale(true, true);
}
public override void AttachEvent (string id)
{
switch (id) {
case Window.ClosedEvent:
Control.Closed += delegate {
Widget.OnClosed (EventArgs.Empty);
};
break;
case Window.ClosingEvent:
Control.Closing += (sender, e) => {
Widget.OnClosing (e);
if (!e.Cancel && sw.Application.Current.Windows.Count == 1) {
// last window closing, so call OnTerminating to let the app abort terminating
Application.Instance.OnTerminating (e);
}
};
break;
case Window.WindowStateChangedEvent:
Control.StateChanged += (sender, e) => Widget.OnWindowStateChanged(EventArgs.Empty);
break;
case Eto.Forms.Control.GotFocusEvent:
Control.Activated += (sender, e) => Widget.OnGotFocus(EventArgs.Empty);
break;
case Eto.Forms.Control.LostFocusEvent:
Control.Deactivated += (sender, e) => Widget.OnLostFocus(EventArgs.Empty);
break;
case Window.LocationChangedEvent:
Control.LocationChanged += (sender, e) => Widget.OnLocationChanged(EventArgs.Empty);
break;
default:
base.AttachEvent (id);
break;
}
}
protected virtual void UpdateClientSize (Size size)
{
var xdiff = Control.ActualWidth - content.ActualWidth;
var ydiff = Control.ActualHeight - content.ActualHeight;
Control.Width = size.Width + xdiff;
Control.Height = size.Height + ydiff;
Control.SizeToContent = sw.SizeToContent.Manual;
}
protected override void SetSize()
{
// don't set the minimum size of a window, just the preferred size
ContainerControl.Width = PreferredSize.Width;
ContainerControl.Height = PreferredSize.Height;
ContainerControl.MinWidth = MinimumSize.Width;
ContainerControl.MinHeight = MinimumSize.Height;
}
public ToolBar ToolBar
{
get { return toolBar; }
set
{
toolBar = value;
toolBarHolder.Content = toolBar != null ? toolBar.ControlObject : null;
}
}
public void Close ()
{
Control.Close ();
}
void CopyKeyBindings (swc.ItemCollection items)
{
foreach (var item in items.OfType<swc.MenuItem>()) {
Control.InputBindings.AddRange (item.InputBindings);
if (item.HasItems)
CopyKeyBindings (item.Items);
}
}
public MenuBar Menu
{
get { return menu; }
set
{
menu = value;
if (menu != null) {
var handler = (MenuBarHandler)menu.Handler;
menuHolder.Content = handler.Control;
Control.InputBindings.Clear ();
CopyKeyBindings (handler.Control.Items);
}
else {
menuHolder.Content = null;
}
}
}
public Icon Icon
{
get { return icon; }
set
{
icon = value;
if (value != null) {
Control.Icon = (swm.ImageSource)icon.ControlObject;
}
}
}
public virtual bool Resizable
{
get { return resizable; }
set
{
if (resizable != value) {
resizable = value;
SetResizeMode ();
}
}
}
public virtual bool Maximizable
{
get { return maximizable; }
set
{
if (maximizable != value) {
maximizable = value;
SetResizeMode ();
}
}
}
public virtual bool Minimizable
{
get { return minimizable; }
set
{
if (minimizable != value) {
minimizable = value;
SetResizeMode ();
}
}
}
protected virtual void SetResizeMode ()
{
if (resizable) Control.ResizeMode = sw.ResizeMode.CanResizeWithGrip;
else if (minimizable) Control.ResizeMode = sw.ResizeMode.CanMinimize;
else Control.ResizeMode = sw.ResizeMode.NoResize;
var hwnd = new sw.Interop.WindowInteropHelper (Control).Handle;
if (hwnd != IntPtr.Zero) {
var val = Win32.GetWindowLong(hwnd, Win32.GWL.STYLE);
if (maximizable)
val |= (uint)Win32.WS.MAXIMIZEBOX;
else
val &= ~(uint)Win32.WS.MAXIMIZEBOX;
if (minimizable)
val |= (uint)Win32.WS.MINIMIZEBOX;
else
val &= ~(uint)Win32.WS.MINIMIZEBOX;
Win32.SetWindowLong (hwnd, Win32.GWL.STYLE, val);
}
}
public virtual bool ShowInTaskbar
{
get { return Control.ShowInTaskbar; }
set { Control.ShowInTaskbar = value; }
}
public virtual bool Topmost
{
get { return Control.Topmost; }
set { Control.Topmost = value; }
}
public void Minimize ()
{
Control.WindowState = sw.WindowState.Minimized;
}
public override Size ClientSize
{
get
{
if (Control.IsLoaded)
return new Size((int)content.ActualWidth, (int)content.ActualHeight);
return initialClientSize ?? Size.Empty;
}
set
{
if (Control.IsLoaded)
UpdateClientSize(value);
else
{
initialClientSize = value;
SetContentSize();
}
}
}
void SetContentSize()
{
if (initialClientSize != null)
{
var value = initialClientSize.Value;
content.MinWidth = value.Width >= 0 ? value.Width : 0;
content.MinHeight = value.Height >= 0 ? value.Height : 0;
content.MaxWidth = value.Width >= 0 ? value.Width : double.PositiveInfinity;
content.MaxHeight = value.Height >= 0 ? value.Height : double.PositiveInfinity;
}
else
{
content.MinWidth = content.MinHeight = 0;
content.MaxWidth = content.MaxHeight = double.PositiveInfinity;
}
}
public override Size Size
{
get { return base.Size; }
set
{
Control.SizeToContent = sw.SizeToContent.Manual;
base.Size = value;
if (!Control.IsLoaded)
{
initialClientSize = null;
SetContentSize();
}
}
}
public string Title
{
get { return Control.Title; }
set { Control.Title = value; }
}
public new Point Location
{
get
{
return new Point ((int)Control.Left, (int)Control.Top);
}
set
{
Control.Left = value.X;
Control.Top = value.Y;
}
}
public WindowState WindowState
{
get
{
switch (Control.WindowState) {
case sw.WindowState.Maximized:
return WindowState.Maximized;
case sw.WindowState.Minimized:
return WindowState.Minimized;
case sw.WindowState.Normal:
return WindowState.Normal;
default:
throw new NotSupportedException ();
}
}
set
{
switch (value) {
case WindowState.Maximized:
Control.WindowState = sw.WindowState.Maximized;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.Manual;
break;
case WindowState.Minimized:
Control.WindowState = sw.WindowState.Minimized;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
break;
case WindowState.Normal:
Control.WindowState = sw.WindowState.Normal;
if (!Control.IsLoaded)
Control.SizeToContent = sw.SizeToContent.WidthAndHeight;
break;
default:
throw new NotSupportedException ();
}
}
}
public Rectangle? RestoreBounds
{
get { return Control.RestoreBounds.ToEto (); }
}
sw.Window IWpfWindow.Control
{
get { return Control; }
}
public double Opacity
{
get { return Control.Opacity; }
set
{
if (Math.Abs(value - 1.0) > 0.01f)
{
if (Control.IsLoaded)
{
#if TODO_XAML
GlassHelper.BlurBehindWindow(Control);
//GlassHelper.ExtendGlassFrame (Control);
Control.Opacity = value;
#endif
}
else
{
Control.Loaded += delegate
{
#if TODO_XAML
GlassHelper.BlurBehindWindow(Control);
//GlassHelper.ExtendGlassFrame (Control);
Control.Opacity = value;
#endif
};
}
}
else
{
Control.Opacity = value;
}
}
}
public override bool HasFocus
{
get { return Control.IsActive && ((ApplicationHandler)Application.Instance.Handler).IsActive; }
}
public WindowStyle WindowStyle
{
get { return Control.WindowStyle.ToEto (); }
set { Control.WindowStyle = value.ToWpf (); }
}
public void BringToFront ()
{
if (Control.WindowState == sw.WindowState.Minimized)
Control.WindowState = sw.WindowState.Normal;
Control.Activate ();
}
public void SendToBack ()
{
if (Topmost)
return;
var hWnd = new sw.Interop.WindowInteropHelper (Control).Handle;
if (hWnd != IntPtr.Zero)
Win32.SetWindowPos (hWnd, Win32.HWND_BOTTOM, 0, 0, 0, 0, Win32.SWP.NOSIZE | Win32.SWP.NOMOVE);
var window = sw.Application.Current.Windows.OfType<sw.Window> ().FirstOrDefault (r => r != Control);
if (window != null)
window.Focus ();
}
public override Color BackgroundColor
{
get { return Control.Background.ToEtoColor(); }
set { Control.Background = value.ToWpfBrush(Control.Background); }
}
public Screen Screen
{
get { return new Screen (Generator, new ScreenHandler (Control)); }
}
public override void SetContainerContent(sw.FrameworkElement content)
{
this.content.Children.Add(content);
}
}
}
#endif
| |
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// SharpMap is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Text;
using NetTopologySuite.Geometries;
using SharpMap.Utilities.Indexing;
using SharpMap.Utilities.SpatialIndexing;
using Common.Logging;
using ProjNet.CoordinateSystems;
using SharpMap.CoordinateSystems;
using Exception = System.Exception;
using NetTopologySuite;
namespace SharpMap.Data.Providers
{
/// <summary>
/// Shapefile dataprovider
/// </summary>
/// <remarks>
/// <para>The ShapeFile provider is used for accessing ESRI ShapeFiles. The ShapeFile should at least contain the
/// [filename].shp, [filename].idx, and if feature-data is to be used, also [filename].dbf file.</para>
/// <para>The first time the ShapeFile is accessed, SharpMap will automatically create a spatial index
/// of the shp-file, and save it as [filename].shp.sidx. If you change or update the contents of the .shp file,
/// delete the .sidx file to force SharpMap to rebuilt it. In web applications, the index will automatically
/// be cached to memory for faster access, so to reload the index, you will need to restart the web application
/// as well.</para>
/// <para>
/// M and Z values in a shapefile is ignored by SharpMap.
/// </para>
/// </remarks>
/// <example>
/// Adding a datasource to a layer:
/// <code lang="C#">
/// SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My layer");
/// myLayer.DataSource = new SharpMap.Data.Providers.ShapeFile(@"C:\data\MyShapeData.shp");
/// </code>
/// </example>
public class ShapeFile : FilterProvider, IProvider
{
readonly ILog _logger = LogManager.GetLogger(typeof(ShapeFile));
//#region Delegates
///// <summary>
///// Filter Delegate Method
///// </summary>
///// <remarks>
///// The FilterMethod delegate is used for applying a method that filters data from the dataset.
///// The method should return 'true' if the feature should be included and false if not.
///// <para>See the <see cref="FilterDelegate"/> property for more info</para>
///// </remarks>
///// <seealso cref="FilterDelegate"/>
///// <param name="dr"><see cref="SharpMap.Data.FeatureDataRow"/> to test on</param>
///// <returns>true if this feature should be included, false if it should be filtered</returns>
//public delegate bool FilterMethod(FeatureDataRow dr);
//#endregion
private ShapeFileHeader _header;
private ShapeFileIndex _index;
private CoordinateSystem _coordinateSystem;
private bool _coordsysReadFromFile;
private bool _fileBasedIndex;
private string _filename;
private string _dbfFile;
private Encoding _dbfSpecifiedEncoding;
private int _srid = -1;
//private readonly object _shapeFileLock = new object();
private GeometryFactory _factory;
private static int _memoryCacheLimit = 50000;
private static readonly object _gspLock = new object();
#if USE_MEMORYMAPPED_FILE
private static Dictionary<string,System.IO.MemoryMappedFiles.MemoryMappedFile> _memMappedFiles;
private static Dictionary<string, int> _memMappedFilesRefConter;
private bool _haveRegistredForUsage = false;
private bool _haveRegistredForShxUsage = false;
static ShapeFile()
{
_memMappedFiles = new Dictionary<string, System.IO.MemoryMappedFiles.MemoryMappedFile>();
_memMappedFilesRefConter = new Dictionary<string, int>();
SpatialIndexFactory = new QuadTreeFactory();
SpatialIndexCreationOption = SpatialIndexCreation.Recursive;
}
#else
static ShapeFile()
{
SpatialIndexFactory = new QuadTreeFactory();
#pragma warning disable CS0618 // Type or member is obsolete
SpatialIndexCreationOption = SpatialIndexCreation.Recursive;
#pragma warning restore CS0618 // Type or member is obsolete
}
#endif
private readonly bool _useMemoryCache;
private DateTime _lastCleanTimestamp = DateTime.Now;
private readonly TimeSpan _cacheExpireTimeout = TimeSpan.FromMinutes(1);
private readonly object _cacheLock = new object();
private readonly Dictionary <uint,FeatureDataRow> _cacheDataTable = new Dictionary<uint,FeatureDataRow>();
/// <summary>
/// Tree used for fast query of data
/// </summary>
private ISpatialIndex<uint> _tree;
/// <summary>
/// Initializes a ShapeFile DataProvider without a file-based spatial index.
/// </summary>
/// <param name="filename">Path to shape file</param>
public ShapeFile(string filename)
: this(filename, false)
{
}
/// <summary>
/// Initializes a ShapeFile DataProvider.
/// </summary>
/// <remarks>
/// <para>If FileBasedIndex is true, the spatial index will be read from a local copy. If it doesn't exist,
/// it will be generated and saved to [filename] + '.sidx'.</para>
/// <para>Using a file-based index is especially recommended for ASP.NET applications which will speed up
/// start-up time when the cache has been emptied.
/// </para>
/// </remarks>
/// <param name="filename">Path to shape file</param>
/// <param name="fileBasedIndex">Use file-based spatial index</param>
public ShapeFile(string filename, bool fileBasedIndex)
{
_filename = filename;
_fileBasedIndex = fileBasedIndex;
//Parse shape header
ParseHeader();
//Read projection file
ParseProjection();
//If no spatial index is wanted, just build a pseudo tree
if (!fileBasedIndex)
_tree = new AllFeaturesTree(_header.BoundingBox, (uint) _index.FeatureCount);
_dbfFile = Path.ChangeExtension(filename, ".dbf");
//Read projection file
ParseProjection();
//By default, don't enable _MemoryCache if there are a lot of features
_useMemoryCache = GetFeatureCount() <= MemoryCacheLimit;
}
/// <summary>
/// Initializes a ShapeFile DataProvider.
/// </summary>
/// <remarks>
/// <para>If FileBasedIndex is true, the spatial index will be read from a local copy. If it doesn't exist,
/// it will be generated and saved to [filename] + '.sidx'.</para>
/// <para>Using a file-based index is especially recommended for ASP.NET applications which will speed up
/// start-up time when the cache has been emptied.
/// </para>
/// </remarks>
/// <param name="filename">Path to shape file</param>
/// <param name="fileBasedIndex">Use file-based spatial index</param>
/// <param name="useMemoryCache">Use the memory cache. BEWARE in case of large shapefiles</param>
public ShapeFile(string filename, bool fileBasedIndex, bool useMemoryCache) : this(filename, fileBasedIndex,useMemoryCache,0)
{
}
/// <summary>
/// Initializes a ShapeFile DataProvider.
/// </summary>
/// <remarks>
/// <para>If FileBasedIndex is true, the spatial index will be read from a local copy. If it doesn't exist,
/// it will be generated and saved to [filename] + '.sidx'.</para>
/// <para>Using a file-based index is especially recommended for ASP.NET applications which will speed up
/// start-up time when the cache has been emptied.
/// </para>
/// </remarks>
/// <param name="filename">Path to shape file</param>
/// <param name="fileBasedIndex">Use file-based spatial index</param>
/// <param name="useMemoryCache">Use the memory cache. BEWARE in case of large shapefiles</param>
/// <param name="srid">The spatial reference id</param>
public ShapeFile(string filename, bool fileBasedIndex, bool useMemoryCache,int srid) : this(filename, fileBasedIndex)
{
_useMemoryCache = useMemoryCache;
SRID=srid;
}
/// <summary>
/// Cleans the internal memory cached, expurging the objects that are not in the viewarea anymore
/// </summary>
/// <param name="objectlist">OID of the objects in the current viewarea</param>
private void CleanInternalCache(Collection<uint> objectlist)
{
if (!_useMemoryCache)
{
return;
}
lock (_cacheLock)
{
//Only execute this if the memorycache is active and the expiretimespan has timed out
if (DateTime.Now.Subtract(_lastCleanTimestamp) > _cacheExpireTimeout)
{
var notIntersectOid = new Collection<uint>();
//identify the not intersected oid
foreach (var oid in _cacheDataTable.Keys)
{
if (!objectlist.Contains(oid))
{
notIntersectOid.Add(oid);
}
}
//Clean the cache
foreach (uint oid in notIntersectOid)
{
_cacheDataTable.Remove(oid);
}
//Reset the lastclean timestamp
_lastCleanTimestamp = DateTime.Now;
}
}
}
/// <summary>
/// Gets or sets a value indicating how many features are allowed for memory cache approach
/// </summary>
protected static int MemoryCacheLimit
{
get { return _memoryCacheLimit; }
set { _memoryCacheLimit = value; }
}
//private void ClearingOfCachedDataRequired(object sender, EventArgs e)
//{
// if (_useMemoryCache)
// lock (_cacheLock)
// {
// _cacheDataTable.Clear();
// }
//}
/// <summary>
/// Gets or sets the coordinate system of the ShapeFile. If a shapefile has
/// a corresponding [filename].prj file containing a Well-Known Text
/// description of the coordinate system this will automatically be read.
/// If this is not the case, the coordinate system will default to null.
/// </summary>
/// <exception cref="ApplicationException">An exception is thrown if the coordinate system is read from file.</exception>
public CoordinateSystem CoordinateSystem
{
get { return _coordinateSystem; }
set
{
if (_coordsysReadFromFile)
throw new ApplicationException("Coordinate system is specified in projection file and is read only");
_coordinateSystem = value;
}
}
/// <summary>
/// Gets the <see cref="SharpMap.Data.Providers.ShapeType">shape geometry type</see> in this shapefile.
/// </summary>
/// <remarks>
/// The property isn't set until the first time the datasource has been opened,
/// and will throw an exception if this property has been called since initialization.
/// <para>All the non-Null shapes in a shapefile are required to be of the same shape
/// type.</para>
/// </remarks>
public ShapeType ShapeType
{
get { return _header.ShapeType; }
}
/// <summary>
/// Gets or sets the filename of the shapefile
/// </summary>
/// <remarks>If the filename changes, indexes will be rebuilt</remarks>
public string Filename
{
get { return _filename; }
set
{
if (value == _filename)
return;
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException("value");
if (IsOpen)
Close();
_filename = value;
_fileBasedIndex = (_fileBasedIndex) && File.Exists(Path.ChangeExtension(value, SpatialIndexFactory.Extension));
_dbfFile = Path.ChangeExtension(value, ".dbf");
ParseHeader();
ParseProjection();
_tree = null;
}
}
/// <summary>
/// Gets or sets the encoding used for parsing strings from the DBase DBF file.
/// </summary>
/// <remarks>
/// The DBase default encoding is <see cref="System.Text.Encoding.UTF8"/>.
/// </remarks>
public Encoding Encoding
{
get
{
if (_dbfSpecifiedEncoding != null)
return _dbfSpecifiedEncoding;
using (var dbf = OpenDbfStream())
return dbf.Encoding;
}
set
{
_dbfSpecifiedEncoding = value;
}
}
#region Disposers and finalizers
private bool _disposed;
private static ISpatialIndexFactory<uint> _spatialIndexFactory = new QuadTreeFactory();
/// <summary>
/// Disposes the object
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
Close();
if (_tree != null)
{
if (_tree is IDisposable)
((IDisposable)_tree).Dispose();
_tree = null;
}
#if USE_MEMORYMAPPED_FILE
if (_memMappedFilesRefConter.ContainsKey(_filename))
{
_memMappedFilesRefConter[_filename]--;
if (_memMappedFilesRefConter[_filename] == 0)
{
_memMappedFiles[_filename].Dispose();
_memMappedFiles.Remove(_filename);
_memMappedFilesRefConter.Remove(_filename);
}
}
string shxFile = Path.ChangeExtension(_filename,".shx");
if (_memMappedFilesRefConter.ContainsKey(shxFile))
{
_memMappedFilesRefConter[shxFile]--;
if (_memMappedFilesRefConter[shxFile] <= 0)
{
_memMappedFiles[shxFile].Dispose();
_memMappedFilesRefConter.Remove(shxFile);
_memMappedFiles.Remove(shxFile);
}
}
#endif
}
_disposed = true;
}
}
/// <summary>
/// Finalizes the object
/// </summary>
~ShapeFile()
{
Dispose();
}
#endregion
#region IProvider Members
private Stream OpenShapefileStream()
{
Stream s;
#if USE_MEMORYMAPPED_FILE
s = CheckCreateMemoryMappedStream(_filename, ref _haveRegistredForUsage);
#else
s = new FileStream(_filename, FileMode.Open, FileAccess.Read);
#endif
return s;
}
private DbaseReader OpenDbfStream()
{
DbaseReader dbfFile = null;
if (File.Exists(_dbfFile))
{
dbfFile = new DbaseReader(_dbfFile);
if (_dbfSpecifiedEncoding != null)
dbfFile.Encoding = _dbfSpecifiedEncoding;
dbfFile.IncludeOid = IncludeOid;
dbfFile.Open();
}
return dbfFile;
}
/// <summary>
/// Gets or sets a value indicating whether the object's id
/// should be included in attribute data or not.
/// <para>The default value is <c>false</c></para>
/// </summary>
public bool IncludeOid { get; set; }
/// <summary>
/// Opens the datasource
/// </summary>
public void Open()
{
if (!File.Exists(_filename))
throw new FileNotFoundException(String.Format("Could not find file \"{0}\"", _filename));
if (!_filename.ToLower().EndsWith(".shp"))
throw (new Exception("Invalid shapefile filename: " + _filename));
//Load SpatialIndexIfNotLoaded
if (_tree == null)
{
if (_fileBasedIndex)
LoadSpatialIndex(false);
else
_tree = new AllFeaturesTree(_header.BoundingBox, (uint)_index.FeatureCount);
//using (Stream s = OpenShapefileStream())
//{
// s.Close();
//}
}
// // TODO:
// // Get a Connector. The connector returned is guaranteed to be connected and ready to go.
// // Pooling.Connector connector = Pooling.ConnectorPool.ConnectorPoolManager.RequestConnector(this,true);
// // if (!_isOpen )
// // {
//// if (File.Exists(shxFile))
//// {
////#if USE_MEMORYMAPPED_FILE
//// _fsShapeIndex = CheckCreateMemoryMappedStream(shxFile, ref _haveRegistredForShxUsage);
////#else
//// _fsShapeIndex = new FileStream(shxFile, FileMode.Open, FileAccess.Read);
////#endif
//// _brShapeIndex = new BinaryReader(_fsShapeIndex, Encoding.Unicode);
//// }
//#if USE_MEMORYMAPPED_FILE
// _fsShapeFile = CheckCreateMemoryMappedStream(_filename, ref _haveRegistredForUsage);
//#else
// _fsShapeFile = new FileStream(_filename, FileMode.Open, FileAccess.Read);
//#endif
// //_brShapeFile = new BinaryReader(_fsShapeFile);
// //// Create array to hold the index array for this open session
// ////_offsetOfRecord = new int[_featureCount];
// //_offsetOfRecord = new ShapeFileIndexEntry[_featureCount];
// //PopulateIndexes(shxFile);
// InitializeShape(_filename, _fileBasedIndex);
// if (DbaseFile != null)
// DbaseFile.Open();
// _isOpen = true;
// }
}
#if USE_MEMORYMAPPED_FILE
private Stream CheckCreateMemoryMappedStream(string filename, ref bool haveRegistredForUsage)
{
if (!_memMappedFiles.ContainsKey(filename))
{
System.IO.MemoryMappedFiles.MemoryMappedFile memMappedFile = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateFromFile(filename, FileMode.Open);
_memMappedFiles.Add(filename, memMappedFile);
}
if (!haveRegistredForUsage)
{
if (_memMappedFilesRefConter.ContainsKey(filename))
_memMappedFilesRefConter[filename]++;
else
_memMappedFilesRefConter.Add(filename, 1);
haveRegistredForUsage = true;
}
return _memMappedFiles[filename].CreateViewStream();
}
#endif
/// <summary>
/// Closes the datasource
/// </summary>
public void Close()
{ }
/// <summary>
/// Returns true if the datasource is currently open
/// </summary>
public bool IsOpen
{
get { return false; }
}
/// <summary>
/// Returns geometries whose bounding box intersects 'bbox'
/// </summary>
/// <remarks>
/// <para>Please note that this method doesn't guarantee that the geometries returned actually intersect 'bbox', but only
/// that their boundingbox intersects 'bbox'.</para>
/// <para>This method is much faster than the QueryFeatures method, because intersection tests
/// are performed on objects simplified by their boundingbox, and using the Spatial Index.</para>
/// </remarks>
/// <param name="bbox"></param>
/// <returns></returns>
public Collection<Geometry> GetGeometriesInView(Envelope bbox)
{
//Use the spatial index to get a list of features whose boundingbox intersects bbox
var objectlist = GetObjectIDsInView(bbox);
if (objectlist.Count == 0) //no features found. Return an empty set
return new Collection<Geometry>();
if (FilterDelegate != null)
return GetGeometriesInViewWithFilter(objectlist);
return GetGeometriesInViewWithoutFilter(objectlist);
}
private Collection<Geometry> GetGeometriesInViewWithFilter(Collection<uint> oids)
{
Collection<Geometry> result = null;
using (Stream s = OpenShapefileStream())
{
using (BinaryReader br = new BinaryReader(s))
{
using (DbaseReader DbaseFile = OpenDbfStream())
{
result = new Collection<Geometry>();
var table = DbaseFile.NewTable;
var tmpOids = new Collection<uint>();
foreach (var oid in oids)
{
var fdr = getFeature(oid, table, br, DbaseFile);
if (!FilterDelegate(fdr)) continue;
result.Add(fdr.Geometry);
tmpOids.Add(oid);
}
CleanInternalCache(tmpOids);
DbaseFile.Close();
}
br.Close();
}
s.Close();
}
return result;
}
private Collection<Geometry> GetGeometriesInViewWithoutFilter(Collection<uint> oids)
{
var result = new Collection<Geometry>();
using (var s = OpenShapefileStream())
{
using (var br = new BinaryReader(s))
{
using (var dbf = OpenDbfStream())
{
foreach (var oid in oids)
{
result.Add(GetGeometryByID(oid, br, dbf));
}
dbf.Close();
}
br.Close();
}
s.Close();
}
CleanInternalCache(oids);
return result;
}
/// <summary>
/// Returns all objects whose boundingbox intersects bbox.
/// </summary>
/// <remarks>
/// <para>
/// Please note that this method doesn't guarantee that the geometries returned actually intersect 'bbox', but only
/// that their boundingbox intersects 'bbox'.
/// </para>
/// </remarks>
/// <param name="bbox"></param>
/// <param name="ds"></param>
/// <returns></returns>
public void ExecuteIntersectionQuery(Envelope bbox, FeatureDataSet ds)
{
// Do true intersection query
if (DoTrueIntersectionQuery)
{
ExecuteIntersectionQuery(Factory.ToGeometry(bbox), ds);
return;
}
//Use the spatial index to get a list of features whose boundingbox intersects bbox
var objectlist = GetObjectIDsInView(bbox);
using (BinaryReader br = new BinaryReader(OpenShapefileStream()))
{
using (DbaseReader dbaseFile = OpenDbfStream())
{
var dt = dbaseFile.NewTable;
dt.BeginLoadData();
for (var i = 0; i < objectlist.Count; i++)
{
FeatureDataRow fdr;
fdr = (FeatureDataRow)dt.LoadDataRow(dbaseFile.GetValues(objectlist[i]), true);
fdr.Geometry = ReadGeometry(objectlist[i], br, dbaseFile);
//Test if the feature data row corresponds to the FilterDelegate
if (FilterDelegate != null && !FilterDelegate(fdr))
fdr.Delete();
}
dt.EndLoadData();
dt.AcceptChanges();
ds.Tables.Add(dt);
dbaseFile.Close();
}
br.Close();
}
CleanInternalCache(objectlist);
}
/// <summary>
/// Returns geometry Object IDs whose bounding box intersects 'bbox'
/// </summary>
/// <param name="bbox"></param>
/// <returns></returns>
public Collection<uint> GetObjectIDsInView(Envelope bbox)
{
if (!_tree.Box.Intersects(bbox))
return new Collection<uint>();
var needBBoxFiltering = _tree is AllFeaturesTree && !bbox.Contains(_tree.Box);
//Use the spatial index to get a list of features whose boundingbox intersects bbox
var res = _tree.Search(bbox);
if (needBBoxFiltering)
{
var tmp = new Collection<uint>();
using (var dbr = OpenDbfStream())
using (var sbr = new BinaryReader(OpenShapefileStream()))
{
foreach (var oid in res)
{
var geom = ReadGeometry(oid, sbr, dbr);
if (geom != null && bbox.Intersects(geom.EnvelopeInternal)) tmp.Add(oid);
}
}
res = tmp;
}
/*Sort oids so we get a forward only read of the shapefile*/
var ret = new List<uint>(res);
ret.Sort();
return new Collection<uint>(ret);
}
/// <summary>
/// Returns the geometry corresponding to the Object ID
/// </summary>
/// <remarks>FilterDelegate is no longer applied to this ge</remarks>
/// <param name="oid">Object ID</param>
/// <returns>The geometry at the Id</returns>
public Geometry GetGeometryByID(uint oid)
{
Geometry geom;
using (Stream s = OpenShapefileStream())
{
using (BinaryReader br = new BinaryReader(s))
{
using (DbaseReader dbf = OpenDbfStream())
{
geom = ReadGeometry(oid, br, dbf);
dbf.Close();
}
br.Close();
}
s.Close();
}
return geom;
}
/// <summary>
/// Returns the geometry corresponding to the Object ID
/// </summary>
/// <remarks>FilterDelegate is no longer applied to this ge</remarks>
/// <param name="oid">Object ID</param>
/// <param name="br"></param>
/// <param name="dbf"></param>
/// <returns>The geometry at the Id</returns>
private Geometry GetGeometryByID(uint oid, BinaryReader br, DbaseReader dbf)
{
if (_useMemoryCache)
{
FeatureDataRow fdr;
lock (_cacheLock)
{
_cacheDataTable.TryGetValue(oid, out fdr);
}
if (fdr == null)
{
fdr = getFeature(oid, dbf.NewTable, br, dbf);
}
return fdr.Geometry;
}
Geometry geom = ReadGeometry(oid, br, dbf);
return geom;
}
/// <summary>
/// Gets or sets a value indicating that for <see cref="ExecuteIntersectionQuery(NetTopologySuite.Geometries.Envelope,SharpMap.Data.FeatureDataSet)"/> the intersection of the geometries and the envelope should be tested.
/// </summary>
public bool DoTrueIntersectionQuery { get; set; }
/// <summary>
/// Gets or sets a value indicating that the provider should check if geometry belongs to a deleted record.
/// </summary>
/// <remarks>This really slows rendering performance down</remarks>
public bool CheckIfRecordIsDeleted { get; set; }
/// <summary>
/// Returns the data associated with all the geometries that are intersected by <paramref name="geom"/>.
/// </summary>
/// <param name="geom">The geometry to test intersection for</param>
/// <param name="ds">FeatureDataSet to fill data into</param>
public virtual void ExecuteIntersectionQuery(Geometry geom, FeatureDataSet ds)
{
var bbox = new Envelope(geom.EnvelopeInternal);
//Get a list of objects that possibly intersect with geom.
var objectlist = GetObjectIDsInView(bbox);
//Get a prepared geometry object
var prepGeom = NetTopologySuite.Geometries.Prepared.PreparedGeometryFactory.Prepare(geom);
using (Stream s = OpenShapefileStream())
{
using (BinaryReader br = new BinaryReader(s))
{
using (DbaseReader DbaseFile = OpenDbfStream())
{
//Get an empty table
var dt = DbaseFile.NewTable;
dt.BeginLoadData();
var tmpOids = new Collection<uint>();
//Cycle through all object ids
foreach (var oid in objectlist)
{
//Get the geometry
var testGeom = ReadGeometry(oid, br, DbaseFile);
//We do not have a geometry => we do not have a feature
if (testGeom == null)
continue;
//Does the geometry really intersect with geom?
if (!prepGeom.Intersects(testGeom))
continue;
//Get the feature data row and assign the geometry
FeatureDataRow fdr;
fdr = (FeatureDataRow)dt.LoadDataRow(DbaseFile.GetValues(oid), true);
fdr.Geometry = testGeom;
//Test if the feature data row corresponds to the FilterDelegate
if (FilterDelegate != null && !FilterDelegate(fdr))
fdr.Delete();
else
tmpOids.Add(oid);
}
dt.EndLoadData();
dt.AcceptChanges();
ds.Tables.Add(dt);
DbaseFile.Close();
CleanInternalCache(tmpOids);
}
br.Close();
}
s.Close();
}
}
/// <summary>
/// Returns the total number of features in the datasource (without any filter applied)
/// </summary>
/// <returns></returns>
public int GetFeatureCount()
{
return _index.FeatureCount;
}
/// <summary>
/// Returns the extents of the datasource
/// </summary>
/// <returns></returns>
public Envelope GetExtents()
{
if (_tree == null)
return _header.BoundingBox;
/*
throw new ApplicationException(
"File hasn't been spatially indexed. Try opening the datasource before retriving extents");
*/
return _tree.Box;
}
/// <summary>
/// Gets the connection ID of the datasource
/// </summary>
/// <remarks>
/// The connection ID of a shapefile is its filename
/// </remarks>
public string ConnectionID
{
get { return _filename; }
}
/// <summary>
/// Gets or sets the spatial reference ID (CRS)
/// </summary>
public virtual int SRID
{
get { return _srid; }
set
{
_srid = value;
lock (_gspLock)
Factory = NtsGeometryServices.Instance.CreateGeometryFactory(value);
}
}
#endregion
/// <summary>
/// Reads and parses the header of the .shp index file
/// </summary>
private void ParseHeader()
{
_header = ShapeFileHeader.Read(_filename);
var shxPath = Path.ChangeExtension(_filename, ".shx");
if (!File.Exists(shxPath))
ShapeFileIndex.Create(_filename);
_index = ShapeFileIndex.Read(shxPath);
}
/// <summary>
/// Reads and parses the projection if a projection file exists
/// </summary>
private void ParseProjection()
{
var projfile = Path.ChangeExtension(_filename, ".prj");
if (File.Exists(projfile))
{
try
{
var wkt = File.ReadAllText(projfile);
var css = (CoordinateSystemServices) Session.Instance.CoordinateSystemServices;
_coordinateSystem = css.CreateCoordinateSystem(wkt);
SRID = (int)_coordinateSystem.AuthorityCode;
_coordsysReadFromFile = true;
}
catch (Exception ex)
{
Trace.TraceWarning("Coordinate system file '" + projfile +
"' found, but could not be parsed. WKT parser returned:" + ex.Message);
throw;
}
}
else
{
if (_coordinateSystem == null)
SRID = 0;
else
{
SRID = (int) _coordinateSystem.AuthorityCode;
}
}
}
///// <summary>
///// If an index file is present (.shx) it reads the record offsets from the .shx index file and returns the information in an array.
///// IfF an indexd array is not present it works out the indexes from the data file, by going through the record headers, finding the
///// data lengths and workingout the offsets. Which ever method is used a array of index is populated to be use by the other methods.
///// This array is created when the open method is called, and removed when the close method called.
///// </summary>
//private void PopulateIndexes(string shxFile)
//{
// if (File.Exists(shxFile))
// {
// using (var brShapeIndex = new BinaryReader(File.OpenRead(shxFile)))
// {
// brShapeIndex.BaseStream.Seek(100, 0); //skip the header
// for (int x = 0; x < _featureCount; ++x)
// {
// _offsetOfRecord[x] = new ShapeFileIndexEntry(brShapeIndex);
// //_offsetOfRecord[x] = 2 * SwapByteOrder(brShapeIndex.ReadInt32()); //Read shape data position // ibuffer);
// //brShapeIndex.BaseStream.Seek(brShapeIndex.BaseStream.Position + 4, 0); //Skip content length
// }
// }
// }
// //if (_brShapeIndex != null)
// //{
// // _brShapeIndex.BaseStream.Seek(100, 0); //skip the header
// // for (int x = 0; x < _featureCount; ++x)
// // {
// // _offsetOfRecord[x] = 2 * SwapByteOrder(_brShapeIndex.ReadInt32()); //Read shape data position // ibuffer);
// // _brShapeIndex.BaseStream.Seek(_brShapeIndex.BaseStream.Position + 4, 0); //Skip content length
// // }
// //}
// else
// {
// // we need to create an index from the shape file
// // Record the current position pointer for later
// var oldPosition = _brShapeFile.BaseStream.Position;
// // Move to the start of the data
// _brShapeFile.BaseStream.Seek(100, 0); //Skip content length
// long offset = 100; // Start of the data records
// for (int x = 0; x < _featureCount; ++x)
// {
// var recordOffset = offset;
// //_offsetOfRecord[x] = (int)offset;
// _brShapeFile.BaseStream.Seek(offset + 4, 0); //Skip content length
// int dataLength = 2 * SwapByteOrder(_brShapeFile.ReadInt32());
// _offsetOfRecord[x] = new ShapeFileIndexEntry((int)recordOffset, dataLength);
// offset += dataLength; // Add Record data length
// offset += 8; // Plus add the record header size
// }
// // Return the position pointer
// _brShapeFile.BaseStream.Seek(oldPosition, 0);
// }
//}
///<summary>
///Swaps the byte order of an int32
///</summary>
/// <param name="i">Integer to swap</param>
/// <returns>Byte Order swapped int32</returns>
internal static int SwapByteOrder(int i)
{
var buffer = BitConverter.GetBytes(i);
Array.Reverse(buffer, 0, buffer.Length);
return BitConverter.ToInt32(buffer, 0);
}
/// <summary>
/// Loads a spatial index from a file. If it doesn't exist, one is created and saved
/// </summary>
/// <param name="filename"></param>
/// <returns>A spatial index</returns>
private ISpatialIndex<uint> CreateSpatialIndexFromFile(string filename)
{
var tree = SpatialIndexFactory.Load(filename);
if (tree == null)
{
tree = SpatialIndexFactory.Create(GetExtents(), GetFeatureCount(), GetAllFeatureBoundingBoxes());
tree.SaveIndex(Filename);
}
return tree;
}
//private void LoadSpatialIndex()
//{
// LoadSpatialIndex(false, false);
//}
/// <summary>
/// Options to create the <see cref="QuadTree"/> spatial index
/// </summary>
[Obsolete("Use SpatialIndexFactory")]
public enum SpatialIndexCreation
{
/// <summary>
/// Loads all the bounding boxes in builds the QuadTree from the list of nodes.
/// This is memory expensive!
/// </summary>
Recursive = 0,
/// <summary>
/// Creates a root node by the bounds of the ShapeFile and adds each node one-by-one-
/// </summary>
Linear,
/// <summary>
/// A custom implementation for the creation of an <see cref="ISpatialIndex{T}"/>
/// </summary>
/// <remarks>You cannot set this value directly, it is set internally if you set <see cref="SpatialIndexFactory"/></remarks>
Custom
}
/// <summary>
/// Gets or sets a value indicating the spatial index factory
/// </summary>
public static ISpatialIndexFactory<uint> SpatialIndexFactory
{
get { return _spatialIndexFactory; }
set
{
if (value == _spatialIndexFactory)
return;
_spatialIndexFactory = value;
#pragma warning disable 618
if (_spatialIndexFactory is QuadTreeFactory)
SpatialIndexCreationOption = QuadTreeFactory.SpatialIndexCreationOption;
else
SpatialIndexCreationOption = SpatialIndexCreation.Custom;
#pragma warning restore 618
}
}
/// <summary>
/// The Spatial index create
/// </summary>
[Obsolete("Use SpatialIndexFactory")]
public static SpatialIndexCreation SpatialIndexCreationOption { get; set; }
private void LoadSpatialIndex(bool forceRebuild)
{
// if we want a new tree, force its creation
if (_tree != null && forceRebuild)
{
_tree.DeleteIndex(_filename);
_tree = null;
}
if (forceRebuild)
{
_tree = SpatialIndexFactory.Create(GetExtents(), GetFeatureCount(), GetAllFeatureBoundingBoxes());
_tree.SaveIndex(_filename);
if (Web.HttpCacheUtility.IsWebContext)
Web.HttpCacheUtility.TryAddValue(_filename, _tree, TimeSpan.FromDays(1));
return;
}
// Is this a web application? If so lets store the index in the cache so we don't
// need to rebuild it for each request
if (Web.HttpCacheUtility.IsWebContext)
{
if (!Web.HttpCacheUtility.TryGetValue(_filename, out _tree))
{
_tree = CreateSpatialIndexFromFile(_filename);
Web.HttpCacheUtility.TryAddValue(_filename, _tree, TimeSpan.FromDays(1));
}
}
else
{
_tree = CreateSpatialIndexFromFile(_filename);
}
}
/// <summary>
/// Forces a rebuild of the spatial index. If the instance of the ShapeFile provider
/// uses a file-based index the file is rewritten to disk.
/// </summary>
public void RebuildSpatialIndex()
{
_fileBasedIndex = true;
LoadSpatialIndex(true);
}
/// <summary>
/// Reads all boundingboxes of features in the shapefile. This is used for spatial indexing.
/// </summary>
/// <returns></returns>
private IEnumerable<ISpatialIndexItem<uint>> GetAllFeatureBoundingBoxes()
{
var fsShapeFile = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read);
var shapeType = _header.ShapeType;
using (var brShapeFile = new BinaryReader(fsShapeFile, Encoding.Unicode))
{
if (shapeType == ShapeType.Point || shapeType == ShapeType.PointZ ||
shapeType == ShapeType.PointM)
{
for (var a = 0; a < _index.FeatureCount; ++a)
{
//if (recDel((uint)a)) continue;
fsShapeFile.Seek(_index.GetOffset((uint)a) + 8, 0); //skip record number and content length
if ((ShapeType) brShapeFile.ReadInt32() != ShapeType.Null)
{
yield return new QuadTree.BoxObjects
{
ID = (uint)a/*+1*/,
Box = new Envelope(new Coordinate(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()))};
}
}
}
else
{
for (var a = 0; a < _index.FeatureCount; ++a)
{
//if (recDel((uint)a)) continue;
fsShapeFile.Seek(_index.GetOffset((uint)a) + 8, 0); //skip record number and content length
if ((ShapeType) brShapeFile.ReadInt32() != ShapeType.Null)
yield return new QuadTree.BoxObjects{
ID = (uint)a /*+1*/,
Box = new Envelope(new Coordinate(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()),
new Coordinate(brShapeFile.ReadDouble(), brShapeFile.ReadDouble()))};
//boxes.Add(new BoundingBox(brShapeFile.ReadDouble(), brShapeFile.ReadDouble(),
// brShapeFile.ReadDouble(), brShapeFile.ReadDouble()));
}
}
}
//return boxes;
}
/// <summary>
/// Gets or sets the geometry factory
/// </summary>
protected GeometryFactory Factory
{
get
{
if (_srid == -1)
SRID = 0;
return _factory;
}
set
{
_factory = value;
_srid = _factory.SRID;
}
}
/// <summary>
/// Reads and parses the geometry with ID 'oid' from the ShapeFile
/// </summary>
/// <param name="oid">Object ID</param>
/// <param name="br">BinaryReader of the ShapeFileStream</param>
/// <param name="dBaseReader">dBaseReader of the DBaseFile</param>
/// <returns>geometry</returns>
private Geometry ReadGeometry(uint oid, BinaryReader br, DbaseReader dBaseReader)
{
// Do we want to receive geometries of deleted records as well?
if (CheckIfRecordIsDeleted)
{
//Test if record is deleted
if (dBaseReader.RecordDeleted(oid)) return null;
}
var diff = _index.GetOffset(oid) - br.BaseStream.Position;
br.BaseStream.Seek(diff, SeekOrigin.Current);
return ParseGeometry(Factory, _header.ShapeType, br);
}
private static Geometry ParseGeometry(GeometryFactory factory, ShapeType shapeType, BinaryReader brGeometryStream)
{
//Skip record number and content length
brGeometryStream.BaseStream.Seek(8, SeekOrigin.Current);
var type = (ShapeType)brGeometryStream.ReadInt32(); //Shape type
if (type == ShapeType.Null)
return null;
if (shapeType == ShapeType.Point || shapeType == ShapeType.PointM || shapeType == ShapeType.PointZ)
{
return factory.CreatePoint(new Coordinate(brGeometryStream.ReadDouble(), brGeometryStream.ReadDouble()));
}
if (shapeType == ShapeType.MultiPoint || shapeType == ShapeType.MultiPointM ||
shapeType == ShapeType.MultiPointZ)
{
brGeometryStream.BaseStream.Seek(32, SeekOrigin.Current); //skip min/max box
var nPoints = brGeometryStream.ReadInt32(); // get the number of points
if (nPoints == 0)
return null;
var feature = new Coordinate[nPoints];
for (var i = 0; i < nPoints; i++)
feature[i] = new Coordinate(brGeometryStream.ReadDouble(), brGeometryStream.ReadDouble());
return factory.CreateMultiPointFromCoords(feature);
}
if (shapeType == ShapeType.PolyLine || shapeType == ShapeType.Polygon ||
shapeType == ShapeType.PolyLineM || shapeType == ShapeType.PolygonM ||
shapeType == ShapeType.PolyLineZ || shapeType == ShapeType.PolygonZ)
{
brGeometryStream.BaseStream.Seek(32, SeekOrigin.Current); //skip min/max box
var nParts = brGeometryStream.ReadInt32(); // get number of parts (segments)
if (nParts == 0 || nParts < 0)
return null;
var nPoints = brGeometryStream.ReadInt32(); // get number of points
var segments = new int[nParts + 1];
//Read in the segment indexes
for (var b = 0; b < nParts; b++)
segments[b] = brGeometryStream.ReadInt32();
//add end point
segments[nParts] = nPoints;
if ((int)shapeType % 10 == 3)
{
var lineStrings = new LineString[nParts];
for (var lineID = 0; lineID < nParts; lineID++)
{
var line = new Coordinate[segments[lineID + 1] - segments[lineID]];
var offset = segments[lineID];
for (var i = segments[lineID]; i < segments[lineID + 1]; i++)
line[i - offset] = new Coordinate(brGeometryStream.ReadDouble(), brGeometryStream.ReadDouble());
lineStrings[lineID] = factory.CreateLineString(line);
}
if (lineStrings.Length == 1)
return lineStrings[0];
return factory.CreateMultiLineString(lineStrings);
}
//First read all the rings
var rings = new LinearRing[nParts];
for (var ringID = 0; ringID < nParts; ringID++)
{
var ring = new Coordinate[segments[ringID + 1] - segments[ringID]];
var offset = segments[ringID];
for (var i = segments[ringID]; i < segments[ringID + 1]; i++)
ring[i - offset] = new Coordinate(brGeometryStream.ReadDouble(), brGeometryStream.ReadDouble());
rings[ringID] = factory.CreateLinearRing(ring);
}
LinearRing exteriorRing;
var isCounterClockWise = new bool[rings.Length];
var polygonCount = 0;
for (var i = 0; i < rings.Length; i++)
{
isCounterClockWise[i] = rings[i].IsCCW();
if (!isCounterClockWise[i])
polygonCount++;
}
if (polygonCount == 1) //We only have one polygon
{
exteriorRing = rings[0];
LinearRing[] interiorRings = null;
if (rings.Length > 1)
{
interiorRings = new LinearRing[rings.Length - 1];
Array.Copy(rings, 1, interiorRings, 0, interiorRings.Length);
}
return factory.CreatePolygon(exteriorRing, interiorRings);
}
var polygons = new List<Polygon>();
exteriorRing = rings[0];
var holes = new List<LinearRing>();
for (var i = 1; i < rings.Length; i++)
{
if (!isCounterClockWise[i])
{
polygons.Add(factory.CreatePolygon(exteriorRing, holes.ToArray()));
holes.Clear();
exteriorRing = rings[i];
}
else
holes.Add(rings[i]);
}
polygons.Add(factory.CreatePolygon(exteriorRing, holes.ToArray()));
return factory.CreateMultiPolygon(polygons.ToArray());
}
throw (new ApplicationException("Shapefile type " + shapeType + " not supported"));
}
/// <summary>
/// Gets a <see cref="FeatureDataRow"/> from the datasource at the specified index
/// <para/>
/// Please note well: It is not checked whether
/// <list type="Bullet">
/// <item>the data record matches the <see cref="FilterProvider.FilterDelegate"/> assigned.</item>
/// </list>
/// </summary>
/// <param name="rowId">The object identifier for the record</param>
/// <returns>The feature data row</returns>
public FeatureDataRow GetFeature(uint rowId)
{
return GetFeature(rowId, null);
}
/// <summary>
/// Gets a datarow from the datasource at the specified index belonging to the specified datatable
/// <para/>
/// Please note well: It is not checked whether
/// <list type="Bullet">
/// <item>the data record matches the <see cref="FilterProvider.FilterDelegate"/> assigned.</item>
/// </list>
/// </summary>
/// <param name="rowId">The object identifier for the record</param>
/// <param name="dt">The datatable the feature should belong to.</param>
/// <returns>The feature data row</returns>
public FeatureDataRow GetFeature(uint rowId, FeatureDataTable dt)
{
FeatureDataRow ret;
using (Stream s = OpenShapefileStream())
{
using (BinaryReader br = new BinaryReader(s))
{
using (DbaseReader dbfReader = OpenDbfStream())
{
if (dt == null)
dt = dbfReader.NewTable;
ret = getFeature(rowId, dt, br, dbfReader);
dbfReader.Close();
}
br.Close();
}
s.Close();
}
return ret;
}
private FeatureDataRow getFeature(uint rowid, FeatureDataTable dt, BinaryReader br, DbaseReader dbfFileReader)
{
Debug.Assert(dt != null);
if (dbfFileReader != null)
{
FeatureDataRow fdr;
//MemoryCache
if (_useMemoryCache)
{
lock (_cacheLock)
{
_cacheDataTable.TryGetValue(rowid, out fdr);
}
if (fdr == null)
{
fdr = dbfFileReader.GetFeature(rowid, dt);
fdr.Geometry = ReadGeometry(rowid, br, dbfFileReader);
lock (_cacheLock)
{
// It is already present, so just pass it
if (_cacheDataTable.ContainsKey(rowid))
return fdr;
_cacheDataTable.Add(rowid, fdr);
}
}
//Make a copy to return
var fdrNew = dt.NewRow();
Array.Copy(fdr.ItemArray, 0, fdrNew.ItemArray, 0, fdr.ItemArray.Length);
//for (var i = 0; i < fdr.Table.Columns.Count; i++)
//{
// fdrNew[i] = fdr[i];
//}
fdrNew.Geometry = fdr.Geometry;
return fdr;
}
fdr = dbfFileReader.GetFeature(rowid, dt);
// GetFeature returns null if the record has deleted flag
if (fdr == null)
return null;
// Read the geometry
fdr.Geometry = ReadGeometry(rowid, br, dbfFileReader);
return fdr;
}
throw (new ApplicationException(
"An attempt was made to read DBase data from a shapefile without a valid .DBF file"));
}
}
}
| |
using Orleans.Providers.Streams.Common;
using Orleans.Runtime;
using Orleans.Serialization;
using Orleans.ServiceBus.Providers;
using Orleans.Streams;
using Orleans.TestingHost.Utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Configuration;
using TestExtensions;
using Xunit;
using Orleans.ServiceBus.Providers.Testing;
using Orleans.Hosting;
using Azure.Messaging.EventHubs;
namespace ServiceBus.Tests.EvictionStrategyTests
{
[TestCategory("EventHub"), TestCategory("Streaming")]
public class EHPurgeLogicTests
{
private CachePressureInjectionMonitor cachePressureInjectionMonitor;
private PurgeDecisionInjectionPredicate purgePredicate;
private SerializationManager serializationManager;
private EventHubAdapterReceiver receiver1;
private EventHubAdapterReceiver receiver2;
private ObjectPool<FixedSizeBuffer> bufferPool;
private TimeSpan timeOut = TimeSpan.FromSeconds(30);
private EventHubPartitionSettings ehSettings;
private ConcurrentBag<EventHubQueueCacheForTesting> cacheList;
private List<EHEvictionStrategyForTesting> evictionStrategyList;
private ITelemetryProducer telemetryProducer;
public EHPurgeLogicTests()
{
//an mock eh settings
this.ehSettings = new EventHubPartitionSettings
{
Hub = new EventHubOptions(),
Partition = "MockPartition",
ReceiverOptions = new EventHubReceiverOptions()
};
//set up cache pressure monitor and purge predicate
this.cachePressureInjectionMonitor = new CachePressureInjectionMonitor();
this.purgePredicate = new PurgeDecisionInjectionPredicate(TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(30));
//set up serialization env
var environment = SerializationTestEnvironment.InitializeWithDefaults();
this.serializationManager = environment.SerializationManager;
//set up buffer pool, small buffer size make it easy for cache to allocate multiple buffers
var oneKB = 1024;
this.bufferPool = new ObjectPool<FixedSizeBuffer>(() => new FixedSizeBuffer(oneKB));
this.telemetryProducer = NullTelemetryProducer.Instance;
}
[Fact, TestCategory("BVT")]
public async Task EventhubQueueCache_WontPurge_WhenUnderPressure()
{
InitForTesting();
var tasks = new List<Task>();
//add items into cache, make sure will allocate multiple buffers from the pool
int itemAddToCache = 100;
foreach(var cache in this.cacheList)
tasks.Add(AddDataIntoCache(cache, itemAddToCache));
await Task.WhenAll(tasks);
//set cachePressureMonitor to be underPressure
this.cachePressureInjectionMonitor.isUnderPressure = true;
//set purgePredicate to be ShouldPurge
this.purgePredicate.ShouldPurge = true;
//perform purge
IList<IBatchContainer> ignore;
this.receiver1.TryPurgeFromCache(out ignore);
this.receiver2.TryPurgeFromCache(out ignore);
//Assert
int expectedItemCountInCacheList = itemAddToCache + itemAddToCache;
Assert.Equal(expectedItemCountInCacheList, GetItemCountInAllCache(this.cacheList));
}
[Fact, TestCategory("BVT")]
public async Task EventhubQueueCache_WontPurge_WhenTimePurgePredicateSaysDontPurge()
{
InitForTesting();
var tasks = new List<Task>();
//add items into cache
int itemAddToCache = 100;
foreach (var cache in this.cacheList)
tasks.Add(AddDataIntoCache(cache, itemAddToCache));
await Task.WhenAll(tasks);
//set cachePressureMonitor to be underPressure
this.cachePressureInjectionMonitor.isUnderPressure = false;
//set purgePredicate to be ShouldPurge
this.purgePredicate.ShouldPurge = false;
//perform purge
IList<IBatchContainer> ignore;
this.receiver1.TryPurgeFromCache(out ignore);
this.receiver2.TryPurgeFromCache(out ignore);
//Assert
int expectedItemCountInCacheList = itemAddToCache + itemAddToCache;
Assert.Equal(expectedItemCountInCacheList, GetItemCountInAllCache(this.cacheList));
}
[Fact, TestCategory("BVT")]
public async Task EventhubQueueCache_WillPurge_WhenTimePurgePredicateSaysPurge_And_NotUnderPressure()
{
InitForTesting();
var tasks = new List<Task>();
//add items into cache
int itemAddToCache = 100;
foreach (var cache in this.cacheList)
tasks.Add(AddDataIntoCache(cache, itemAddToCache));
await Task.WhenAll(tasks);
//set cachePressureMonitor to be underPressure
this.cachePressureInjectionMonitor.isUnderPressure = false;
//set purgePredicate to be ShouldPurge
this.purgePredicate.ShouldPurge = true;
//perform purge
IList<IBatchContainer> ignore;
this.receiver1.TryPurgeFromCache(out ignore);
this.receiver2.TryPurgeFromCache(out ignore);
//Assert
int expectedItemCountInCaches = 0;
//items got purged
Assert.Equal(expectedItemCountInCaches, GetItemCountInAllCache(this.cacheList));
}
[Fact, TestCategory("BVT")]
public async Task EventhubQueueCache_EvictionStrategy_Behavior()
{
InitForTesting();
var tasks = new List<Task>();
//add items into cache
int itemAddToCache = 100;
foreach (var cache in this.cacheList)
tasks.Add(AddDataIntoCache(cache, itemAddToCache));
await Task.WhenAll(tasks);
//set up condition so that purge will be performed
this.cachePressureInjectionMonitor.isUnderPressure = false;
this.purgePredicate.ShouldPurge = true;
//Each cache should each have buffers allocated
this.evictionStrategyList.ForEach(strategy => Assert.True(strategy.InUseBuffers.Count > 0));
//perform purge
//after purge, inUseBuffers should be purged and return to the pool, except for the current buffer
var expectedPurgedBuffers = new List<FixedSizeBuffer>();
this.evictionStrategyList.ForEach(strategy =>
{
var purgedBufferList = strategy.InUseBuffers.ToArray<FixedSizeBuffer>();
//last one in purgedBufferList should be current buffer, which shouldn't be purged
for (int i = 0; i < purgedBufferList.Count() - 1; i++)
expectedPurgedBuffers.Add(purgedBufferList[i]);
});
IList<IBatchContainer> ignore;
this.receiver1.TryPurgeFromCache(out ignore);
this.receiver2.TryPurgeFromCache(out ignore);
//Each cache should have all buffers purged, except for current buffer
this.evictionStrategyList.ForEach(strategy => Assert.Single(strategy.InUseBuffers));
var oldBuffersInCaches = new List<FixedSizeBuffer>();
this.evictionStrategyList.ForEach(strategy => {
foreach (var inUseBuffer in strategy.InUseBuffers)
oldBuffersInCaches.Add(inUseBuffer);
});
//add items into cache again
itemAddToCache = 100;
foreach (var cache in this.cacheList)
tasks.Add(AddDataIntoCache(cache, itemAddToCache));
await Task.WhenAll(tasks);
//block pool should have purged buffers returned by now, and used those to allocate buffer for new item
var newBufferAllocated = new List<FixedSizeBuffer>();
this.evictionStrategyList.ForEach(strategy => {
foreach (var inUseBuffer in strategy.InUseBuffers)
newBufferAllocated.Add(inUseBuffer);
});
//remove old buffer in cache, to get newly allocated buffers after purge
newBufferAllocated.RemoveAll(buffer => oldBuffersInCaches.Contains(buffer));
//purged buffer should return to the pool after purge, and used to allocate new buffer
expectedPurgedBuffers.ForEach(buffer => Assert.Contains(buffer, newBufferAllocated));
}
private void InitForTesting()
{
this.cacheList = new ConcurrentBag<EventHubQueueCacheForTesting>();
this.evictionStrategyList = new List<EHEvictionStrategyForTesting>();
var monitorDimensions = new EventHubReceiverMonitorDimensions
{
EventHubPartition = this.ehSettings.Partition,
EventHubPath = this.ehSettings.Hub.Path,
};
this.receiver1 = new EventHubAdapterReceiver(this.ehSettings, this.CacheFactory, this.CheckPointerFactory, NullLoggerFactory.Instance,
new DefaultEventHubReceiverMonitor(monitorDimensions, this.telemetryProducer), new LoadSheddingOptions(), this.telemetryProducer);
this.receiver2 = new EventHubAdapterReceiver(this.ehSettings, this.CacheFactory, this.CheckPointerFactory, NullLoggerFactory.Instance,
new DefaultEventHubReceiverMonitor(monitorDimensions, this.telemetryProducer), new LoadSheddingOptions(), this.telemetryProducer);
this.receiver1.Initialize(this.timeOut);
this.receiver2.Initialize(this.timeOut);
}
private int GetItemCountInAllCache(ConcurrentBag<EventHubQueueCacheForTesting> caches)
{
int itemCount = 0;
foreach (var cache in caches)
{
itemCount += cache.ItemCount;
}
return itemCount;
}
private async Task AddDataIntoCache(EventHubQueueCacheForTesting cache, int count)
{
await Task.Delay(10);
List<EventData> messages = Enumerable.Range(0, count)
.Select(i => MakeEventData(i))
.ToList();
cache.Add(messages, DateTime.UtcNow);
}
private EventData MakeEventData(long sequenceNumber)
{
byte[] ignore = { 12, 23 };
var now = DateTime.UtcNow;
var eventData = new TestEventData(ignore,
offset: now.Ticks,
sequenceNumber: sequenceNumber,
enqueuedTime: now);
return eventData;
}
private class TestEventData : EventData
{
public TestEventData(ReadOnlyMemory<byte> eventBody, IDictionary<string, object> properties = null, IReadOnlyDictionary<string, object> systemProperties = null, long sequenceNumber = long.MinValue, long offset = long.MinValue, DateTimeOffset enqueuedTime = default, string partitionKey = null) : base(eventBody, properties, systemProperties, sequenceNumber, offset, enqueuedTime, partitionKey)
{
}
}
private Task<IStreamQueueCheckpointer<string>> CheckPointerFactory(string partition)
{
return Task.FromResult<IStreamQueueCheckpointer<string>>(NoOpCheckpointer.Instance);
}
private IEventHubQueueCache CacheFactory(string partition, IStreamQueueCheckpointer<string> checkpointer, ILoggerFactory loggerFactory, ITelemetryProducer telemetryProducer)
{
var cacheLogger = loggerFactory.CreateLogger($"{typeof(EventHubQueueCacheForTesting)}.{partition}");
var evictionStrategy = new EHEvictionStrategyForTesting(cacheLogger, null, null, this.purgePredicate);
this.evictionStrategyList.Add(evictionStrategy);
var cache = new EventHubQueueCacheForTesting(
this.bufferPool,
new MockEventHubCacheAdaptor(this.serializationManager),
evictionStrategy,
checkpointer,
cacheLogger);
cache.AddCachePressureMonitor(this.cachePressureInjectionMonitor);
this.cacheList.Add(cache);
return cache;
}
}
}
| |
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudioTools.Parsing;
using ErrorHandler = Microsoft.VisualStudio.ErrorHandler;
using VSConstants = Microsoft.VisualStudio.VSConstants;
namespace Microsoft.VisualStudioTools.Navigation {
/// <summary>
/// This is a specialized version of the LibraryNode that handles the dynamic languages
/// items. The main difference from the generic one is that it supports navigation
/// to the location inside the source code where the element is defined.
/// </summary>
internal abstract class CommonLibraryNode : LibraryNode {
private readonly IVsHierarchy _ownerHierarchy;
private readonly uint _fileId;
private readonly TextSpan _sourceSpan;
private readonly IScopeNode _scope;
private string _fileMoniker;
protected CommonLibraryNode(LibraryNode parent, IScopeNode scope, string namePrefix, IVsHierarchy hierarchy, uint itemId) :
base(parent, GetLibraryNodeName(scope, namePrefix), namePrefix + scope.Name, scope.NodeType) {
_ownerHierarchy = hierarchy;
_fileId = itemId;
// Now check if we have all the information to navigate to the source location.
if ((null != _ownerHierarchy) && (VSConstants.VSITEMID_NIL != _fileId)) {
if ((SourceLocation.Invalid != scope.Start) && (SourceLocation.Invalid != scope.End)) {
_sourceSpan = new TextSpan();
_sourceSpan.iStartIndex = scope.Start.Column - 1;
if (scope.Start.Line > 0) {
_sourceSpan.iStartLine = scope.Start.Line - 1;
}
_sourceSpan.iEndIndex = scope.End.Column;
if (scope.End.Line > 0) {
_sourceSpan.iEndLine = scope.End.Line - 1;
}
CanGoToSource = true;
}
}
_scope = scope;
}
internal IScopeNode ScopeNode {
get {
return _scope;
}
}
public TextSpan SourceSpan {
get {
return _sourceSpan;
}
}
private static string GetLibraryNodeName(IScopeNode node, string namePrefix) {
namePrefix = namePrefix.Substring(namePrefix.LastIndexOf(':') + 1); // remove filename prefix
return node.NodeType == LibraryNodeType.Members ? node.Name : string.Format(CultureInfo.InvariantCulture, "{0}{1}", namePrefix, node.Name);
}
protected CommonLibraryNode(CommonLibraryNode node) :
base(node) {
_fileId = node._fileId;
_ownerHierarchy = node._ownerHierarchy;
_fileMoniker = node._fileMoniker;
_sourceSpan = node._sourceSpan;
}
protected CommonLibraryNode(CommonLibraryNode node, string newFullName) :
base(node, newFullName) {
_scope = node._scope;
_fileId = node._fileId;
_ownerHierarchy = node._ownerHierarchy;
_fileMoniker = node._fileMoniker;
_sourceSpan = node._sourceSpan;
}
public override uint CategoryField(LIB_CATEGORY category) {
switch (category) {
case (LIB_CATEGORY)_LIB_CATEGORY2.LC_MEMBERINHERITANCE:
if (NodeType == LibraryNodeType.Members || NodeType == LibraryNodeType.Definitions) {
return (uint)_LIBCAT_MEMBERINHERITANCE.LCMI_IMMEDIATE;
}
break;
}
return base.CategoryField(category);
}
public override void GotoSource(VSOBJGOTOSRCTYPE gotoType) {
// We do not support the "Goto Reference"
if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType) {
return;
}
// There is no difference between definition and declaration, so here we
// don't check for the other flags.
IVsWindowFrame frame = null;
IntPtr documentData = FindDocDataFromRDT();
try {
// Now we can try to open the editor. We assume that the owner hierarchy is
// a project and we want to use its OpenItem method.
IVsProject3 project = _ownerHierarchy as IVsProject3;
if (null == project) {
return;
}
Guid viewGuid = VSConstants.LOGVIEWID_Code;
ErrorHandler.ThrowOnFailure(project.OpenItem(_fileId, ref viewGuid, documentData, out frame));
} finally {
if (IntPtr.Zero != documentData) {
Marshal.Release(documentData);
documentData = IntPtr.Zero;
}
}
// Make sure that the document window is visible.
ErrorHandler.ThrowOnFailure(frame.Show());
// Get the code window from the window frame.
object docView;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView));
IVsCodeWindow codeWindow = docView as IVsCodeWindow;
if (null == codeWindow) {
object docData;
ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData));
codeWindow = docData as IVsCodeWindow;
if (null == codeWindow) {
return;
}
}
// Get the primary view from the code window.
IVsTextView textView;
ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView));
// Set the cursor at the beginning of the declaration.
ErrorHandler.ThrowOnFailure(textView.SetCaretPos(_sourceSpan.iStartLine, _sourceSpan.iStartIndex));
// Make sure that the text is visible.
TextSpan visibleSpan = new TextSpan();
visibleSpan.iStartLine = _sourceSpan.iStartLine;
visibleSpan.iStartIndex = _sourceSpan.iStartIndex;
visibleSpan.iEndLine = _sourceSpan.iStartLine;
visibleSpan.iEndIndex = _sourceSpan.iStartIndex + 1;
ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(visibleSpan));
}
public override void SourceItems(out IVsHierarchy hierarchy, out uint itemId, out uint itemsCount) {
hierarchy = _ownerHierarchy;
itemId = _fileId;
itemsCount = 1;
}
public override string UniqueName {
get {
if (string.IsNullOrEmpty(_fileMoniker)) {
ErrorHandler.ThrowOnFailure(_ownerHierarchy.GetCanonicalName(_fileId, out _fileMoniker));
}
return string.Format(CultureInfo.InvariantCulture, "{0}/{1}", _fileMoniker, Name);
}
}
private IntPtr FindDocDataFromRDT() {
// Get a reference to the RDT.
IVsRunningDocumentTable rdt = Package.GetGlobalService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
if (null == rdt) {
return IntPtr.Zero;
}
// Get the enumeration of the running documents.
IEnumRunningDocuments documents;
ErrorHandler.ThrowOnFailure(rdt.GetRunningDocumentsEnum(out documents));
IntPtr documentData = IntPtr.Zero;
uint[] docCookie = new uint[1];
uint fetched;
while ((VSConstants.S_OK == documents.Next(1, docCookie, out fetched)) && (1 == fetched)) {
uint flags;
uint editLocks;
uint readLocks;
string moniker;
IVsHierarchy docHierarchy;
uint docId;
IntPtr docData = IntPtr.Zero;
try {
ErrorHandler.ThrowOnFailure(
rdt.GetDocumentInfo(docCookie[0], out flags, out readLocks, out editLocks, out moniker, out docHierarchy, out docId, out docData));
// Check if this document is the one we are looking for.
if ((docId == _fileId) && (_ownerHierarchy.Equals(docHierarchy))) {
documentData = docData;
docData = IntPtr.Zero;
break;
}
} finally {
if (IntPtr.Zero != docData) {
Marshal.Release(docData);
}
}
}
return documentData;
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Reflection;
using C1.Win.C1Preview;
using PCSUtils.Utils;
namespace MaterialManagementReport
{
[Serializable]
public class MaterialManagementReport : MarshalByRefObject, IDynamicReport
{
public MaterialManagementReport()
{
}
private string mConnectionString;
private ReportBuilder mReportBuilder;
private C1PrintPreviewControl mReportViewer;
private object mResult;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
private bool mUseReportViewerRenderEngine = true;
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseReportViewerRenderEngine; }
set { mUseReportViewerRenderEngine = value; }
}
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mstrReportDefinitionFolder; }
set { mstrReportDefinitionFolder = value; }
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get
{
return mstrReportLayoutFile;
}
set
{
mstrReportLayoutFile = value;
}
}
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
public DataTable ExecuteReport(string pstrCCNID, string pstrCategoryID, string pstrProductID)
{
DataTable dtbReportData = new DataTable();
try
{
int intCCNID = 0;
try
{
intCCNID = int.Parse(pstrCCNID);
}
catch
{
}
int intCategoryID = 0;
try
{
intCategoryID = int.Parse(pstrCategoryID);
}
catch
{
}
int intProductID = 0;
try
{
intProductID = int.Parse(pstrProductID);
}
catch
{
}
DataTable dtbTop = new DataTable("MaterialReport");
if (intProductID > 0)
dtbTop = GetOneItem(intProductID);
else
dtbTop = GetTopLevelItem(intCCNID, intCategoryID);
DataTable dtbAllChild = GetAllItems(intCCNID, intCategoryID);
dtbReportData = dtbTop.Clone();
foreach (DataRow drowData in dtbTop.Rows)
BuildData(dtbReportData, dtbAllChild, drowData, 0, intCCNID, intCategoryID);
// add number list
dtbReportData = AddNumberedListToDataTable(dtbReportData);
}
catch
{
}
return dtbReportData;
}
private void BuildData(DataTable pdtbData, DataTable pdtbAllChild, DataRow pdrowNew, int pintLevel, int pintCCNID, int pintCategoryID)
{
try
{
DataRow drowItem = pdtbData.NewRow();
foreach (DataColumn dcolData in pdtbData.Columns)
drowItem[dcolData.ColumnName] = pdrowNew[dcolData.ColumnName];
drowItem["Level"] = pintLevel;
pdtbData.Rows.Add(drowItem);
// get child
//DataTable dtbChild = GetChild(pintCCNID, pintCategoryID, int.Parse(drowItem[ITM_ProductTable.PRODUCTID_FLD].ToString()));
DataRow[] drowsChild = GetChild(pdtbAllChild, int.Parse(drowItem["ProductID"].ToString()));
foreach (DataRow drowChild in drowsChild)
BuildData(pdtbData, pdtbAllChild, drowChild, pintLevel + 1, pintCCNID, pintCategoryID);
}
catch
{
}
}
private DataRow[] GetChild(DataTable pdtbAllChilds, int pintParentID)
{
try
{
DataRow[] drowResult = pdtbAllChilds.Select("ParentID = '" + pintParentID.ToString() + "'");
return drowResult;
}
catch
{
return null;
}
}
private DataTable GetTopLevelItem(int pintCCNID, int pintCategoryID)
{
OleDbConnection cn = null;
try
{
cn = new OleDbConnection(mConnectionString);
DataTable dtbItem = new DataTable();
string strSql = "SELECT DISTINCT '0' AS 'Level', "
+ "ITM_Category.Code AS CategoryCode, "
+ "ITM_Product.Code AS 'Part No.', "
+ "ITM_Product.Description AS 'Part Name', "
+ "ITM_Product.Revision AS 'Model', "
+ "MST_UnitOfMeasure.Code AS 'Stock UM', "
+ "MST_WorkCenter.Code AS 'ProcessCode', "
+ "MST_WorkCenter.Name AS 'ProcessName',"
+ " CAST(NULL AS decimal(18,5)) AS 'BOM Qty',"
+ " CAST(NULL AS decimal(18,5)) AS 'LeadTimeOffset',"
+ " CAST(NULL AS decimal(18,5)) AS 'Shrink',"
+ " MST_Party.Code AS 'Supplier',"
+ " ITM_Product.ProductID, NULL AS 'ParentID',"
+ " ITM_Product.MakeItem"
+ " FROM ITM_Product JOIN ITM_BOM"
+ " ON ITM_Product.ProductID = ITM_BOM.ProductID"
+ " LEFT JOIN (SELECT PRO_ProductionLine.Code, PRO_ProductionLine.Name,"
+ " MST_WorkCenter.WorkCenterID, MST_WorkCenter.ProductionLineID, ITM_Routing.ProductID"
+ " FROM ITM_Routing JOIN MST_WorkCenter"
+ " ON ITM_Routing.WorkCenterID = MST_WorkCenter.WorkCenterID"
+ " LEFT JOIN PRO_ProductionLine"
+ " ON MST_WorkCenter.ProductionLineID = PRO_ProductionLine.ProductionLineID"
+ " WHERE ISNULL(MST_WorkCenter.IsMain , 0)= 1) MST_WorkCenter"
+ " ON ITM_Product.ProductID = MST_WorkCenter.ProductID"
+ " LEFT JOIN MST_Party"
+ " ON ITM_Product.PrimaryVendorID = MST_Party.PartyID"
+ " LEFT JOIN ITM_Category"
+ " ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " JOIN MST_UnitOfMeasure"
+ " ON MST_UnitOfMeasure.UnitOfMeasureID = ITM_Product.StockUMID"
+ " WHERE ITM_Product.ProductID NOT IN (SELECT ITM_BOM.ComponentID FROM ITM_BOM)"
+ " AND ITM_Product.CCNID = " + pintCCNID;
if (pintCategoryID > 0)
strSql += " AND ITM_Product.CategoryID = " + pintCategoryID;
strSql += " ORDER BY ITM_Product.ProductID";
OleDbDataAdapter odad = new OleDbDataAdapter(strSql, cn);
odad.Fill(dtbItem);
return dtbItem;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cn != null)
if (cn.State != ConnectionState.Closed)
cn.Close();
}
}
private DataTable GetAllItems(int pintCCNID, int pintCategoryID)
{
OleDbConnection cn = null;
try
{
cn = new OleDbConnection(mConnectionString);
DataTable dtbItem = new DataTable();
string strSql = "SELECT DISTINCT '1' AS 'Level', "
+ "ITM_Category.Code AS CategoryCode, "
+ " ITM_Product.Code AS 'Part No.', "
+ " ITM_Product.Description AS 'Part Name', "
+ " ITM_Product.Revision AS 'Model', "
+ " MST_UnitOfMeasure.Code AS 'Stock UM', "
+ " MST_WorkCenter.Code AS 'ProcessCode', "
+ " MST_WorkCenter.Name AS 'ProcessName',"
+ " ITM_BOM.Quantity AS 'BOM Qty', ITM_BOM.LeadTimeOffset, ITM_BOM.Shrink,"
+ " MST_Party.Code AS 'Supplier',"
+ " ITM_Product.ProductID, ITM_BOM.ProductID AS 'ParentID',"
+ " ITM_Product.MakeItem"
+ " FROM ITM_Product JOIN ITM_BOM"
+ " ON ITM_Product.ProductID = ITM_BOM.ComponentID"
+ " LEFT JOIN (SELECT PRO_ProductionLine.Code, PRO_ProductionLine.Name,"
+ " MST_WorkCenter.WorkCenterID, MST_WorkCenter.ProductionLineID, ITM_Routing.ProductID"
+ " FROM ITM_Routing JOIN MST_WorkCenter"
+ " ON ITM_Routing.WorkCenterID = MST_WorkCenter.WorkCenterID"
+ " LEFT JOIN PRO_ProductionLine"
+ " ON MST_WorkCenter.ProductionLineID = PRO_ProductionLine.ProductionLineID"
+ " WHERE ISNULL(MST_WorkCenter.IsMain , 0)= 1) MST_WorkCenter"
+ " ON ITM_Product.ProductID = MST_WorkCenter.ProductID"
+ " LEFT JOIN MST_Party"
+ " ON ITM_Product.PrimaryVendorID = MST_Party.PartyID"
+ " LEFT JOIN ITM_Category"
+ " ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " JOIN MST_UnitOfMeasure"
+ " ON MST_UnitOfMeasure.UnitOfMeasureID = ITM_Product.StockUMID"
+ " WHERE ITM_Product.CCNID = " + pintCCNID;
if (pintCategoryID > 0)
strSql += " AND ITM_Product.CategoryID = " + pintCategoryID;
strSql += " ORDER BY ITM_Product.ProductID";
OleDbDataAdapter odad = new OleDbDataAdapter(strSql, cn);
odad.Fill(dtbItem);
return dtbItem;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cn != null)
if (cn.State != ConnectionState.Closed)
cn.Close();
}
}
private DataTable GetOneItem(int pintProductID)
{
OleDbConnection cn = null;
try
{
cn = new OleDbConnection(mConnectionString);
DataTable dtbItem = new DataTable();
string strSql = "SELECT DISTINCT '0' AS 'Level', "
+ "ITM_Category.Code AS CategoryCode, "
+ "ITM_Product.Code AS 'Part No.', "
+ "ITM_Product.Description AS 'Part Name', "
+ "ITM_Product.Revision AS 'Model', "
+ "MST_UnitOfMeasure.Code AS 'Stock UM', "
+ "MST_WorkCenter.Code AS 'ProcessCode', "
+ "MST_WorkCenter.Name AS 'ProcessName',"
+ " CAST(NULL AS decimal(18,5)) AS 'BOM Qty',"
+ " CAST(NULL AS decimal(18,5)) AS 'LeadTimeOffset',"
+ " CAST(NULL AS decimal(18,5)) AS 'Shrink',"
+ " MST_Party.Code AS 'Supplier',"
+ " ITM_Product.ProductID, NULL AS 'ParentID',"
+ " ITM_Product.MakeItem"
+ " FROM ITM_Product JOIN ITM_BOM"
+ " ON ITM_Product.ProductID = ITM_BOM.ProductID"
+ " LEFT JOIN (SELECT PRO_ProductionLine.Code, PRO_ProductionLine.Name,"
+ " MST_WorkCenter.WorkCenterID, MST_WorkCenter.ProductionLineID, ITM_Routing.ProductID"
+ " FROM ITM_Routing JOIN MST_WorkCenter"
+ " ON ITM_Routing.WorkCenterID = MST_WorkCenter.WorkCenterID"
+ " LEFT JOIN PRO_ProductionLine"
+ " ON MST_WorkCenter.ProductionLineID = PRO_ProductionLine.ProductionLineID"
+ " WHERE ISNULL(MST_WorkCenter.IsMain , 0)= 1) MST_WorkCenter"
+ " ON ITM_Product.ProductID = MST_WorkCenter.ProductID"
+ " LEFT JOIN MST_Party"
+ " ON ITM_Product.PrimaryVendorID = MST_Party.PartyID"
+ " JOIN MST_UnitOfMeasure"
+ " ON MST_UnitOfMeasure.UnitOfMeasureID = ITM_Product.StockUMID"
+ " LEFT JOIN ITM_Category"
+ " ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " WHERE ITM_Product.ProductID = " + pintProductID;
OleDbDataAdapter odad = new OleDbDataAdapter(strSql, cn);
odad.Fill(dtbItem);
return dtbItem;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cn != null)
if (cn.State != ConnectionState.Closed)
cn.Close();
}
}
//**************************************************************************
/// <summary>
/// Add a column named "NumberedList" to dataTable
/// </summary>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// ThachNN
/// </Authors>
/// <History>
/// 21-Sep-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
private DataTable AddNumberedListToDataTable(DataTable pdtb)
{
try
{
DataTable dtbRet = pdtb.Copy();
DataColumn odcol = new DataColumn("NumberedList");
odcol.DataType = typeof (string);
odcol.DefaultValue = "";
dtbRet.Columns.Add(odcol);
int[] arriInputLevel = ExtractArrayOfLevelFromDataTable(pdtb);
StringCollection arrNumberedList = GetNumberedListForBOMProduct(arriInputLevel, 0, ".");
int intCount = 0;
foreach (DataRow row in dtbRet.Rows)
{
string strNumber = arrNumberedList[intCount];
string strPartNo = row["Part No."].ToString();
row["NumberedList"] = strNumber;
// indent the part no following the level
int intLevel = int.Parse(row["Level"].ToString());
for (int i = 0; i < intLevel; i++)
strPartNo = "- " + strPartNo;
row["Part No."] = strPartNo;
intCount++;
}
return dtbRet;
}
catch
{
return null;
}
}
//**************************************************************************
/// <summary>
/// Generate a list of number string (format as 1.1.2.3, ...) to append to BOM product report
/// Use only by AddNumberedListToDataTable() method
/// </summary>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// ThachNN
/// </Authors>
/// <History>
/// 21-Sep-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public static StringCollection GetNumberedListForBOMProduct(int[] parriInput,
int pintRootNumber,
string pstrDeli)
{
try
{
#region DEFINE Variables
StringCollection arrRet = new StringCollection();
int intRecordCount = parriInput.Length;
StringCollection arrParentString = new StringCollection();
for (int intCounter = 0; intCounter < intRecordCount + 1; intCounter++)
{
arrParentString.Add("");
}
int[] arriLevelHit = new int[intRecordCount + 1];
#endregion
int intPrev = pintRootNumber; // in start phase, iRootNumber is iPrev
foreach (int i in parriInput)
{
string strOut = "";
/// Update level hit count == active running number of last index
(arriLevelHit[i])++; // increase the hit count of level i
arriLevelHit[i + 1] = 0; // reset hit count of level i+1 to ZERO
if (i == pintRootNumber) // if the level is restart to iRootNumber
{
// level 0, not exist
// Parent string of level iRootNumber, alway = ""
// strOut always = "1"
arrParentString[i] = "";
strOut = "1";
}
else
{
strOut = arrParentString[i] + pstrDeli + arriLevelHit[i];
if (strOut.StartsWith("."))
strOut = strOut.Remove(0, 1);
}
intPrev = i;
arrParentString[i + 1] = strOut;
arrRet.Add(strOut);
}
return arrRet;
}
catch
{
return null;
}
}
//**************************************************************************
/// <summary>
/// Return array of int, contain level columm (named "Level") from DataTable
/// Use only by AddNumberedListToDataTable() method
/// </summary>
/// <Inputs>
/// DataTable contain column "Level"
/// </Inputs>
/// <Outputs>
/// Array of int, contain value from "Level" data column
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// ThachNN
/// </Authors>
/// <History>
/// 21-Sep-2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public static int[] ExtractArrayOfLevelFromDataTable(DataTable pdtb)
{
try
{
int[] arrintRet = new int[pdtb.Rows.Count];
int intCount = 0;
foreach (DataRow row in pdtb.Rows)
{
arrintRet[intCount] = int.Parse(row["Level"].ToString());
intCount++;
}
return arrintRet;
}
catch
{
return null;
}
}
}
}
| |
/*
Copyright (C) 2013-2015 MetaMorph Software, Inc
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
=======================
This version of the META tools is a fork of an original version produced
by Vanderbilt University's Institute for Software Integrated Systems (ISIS).
Their license statement:
Copyright (C) 2011-2014 Vanderbilt University
Developed with the sponsorship of the Defense Advanced Research Projects
Agency (DARPA) and delivered to the U.S. Government with Unlimited Rights
as defined in DFARS 252.227-7013.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this data, including any software or models in source or binary
form, as well as any drawings, specifications, and documentation
(collectively "the Data"), to deal in the Data without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Data, and to
permit persons to whom the Data 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 Data.
THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE USE OR OTHER DEALINGS IN THE DATA.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Diagnostics;
using ISIS.Web;
namespace ISIS.VehicleForge
{
/// <summary>
/// Handles authentication and request to a VehicleFORGE deployment
/// </summary>
public class VFWebClient : AuthenticatedWebClient
{
private Dictionary<string, object> m_loginQuery { get; set; }
public VFWebClient(string serverUrl, Credentials credentials)
: base(serverUrl, credentials)
{
// META-2204: Login information MUST not be sent as query parameters!
this.m_loginQuery = new Dictionary<string, object>();
}
public string AuthUrl
{
get { return "/auth/"; }
}
public override string LoginUrl
{
get { return "/auth/do_login"; }
}
public override string LogoutUrl
{
get { return "/auth/logout"; }
}
public override T SendPostRequest<T>(string url, Dictionary<string, object> query = null, string content = null, string contentType = null)
{
query = this.AppendSessionId(query);
return base.SendPostRequest<T>(url, query, content, contentType);
}
public override string SendPostRequest(string url, Dictionary<string, object> query = null, string content = null, string contentType = null)
{
query = this.AppendSessionId(query);
return base.SendPostRequest(url, query, content, contentType);
//try
//{
// query = this.AppendSessionId(query);
// return base.SendPostRequest(url, query, content, contentType);
//}
//catch (WebException webEx)
//{
// if (webEx.Status == WebExceptionStatus.Timeout)
// {
// System.Windows.Forms.MessageBox.Show(
// "Timeout WebException in VFWebClient's SendPostRequest...",
// "VF Timeout",
// System.Windows.Forms.MessageBoxButtons.OK,
// System.Windows.Forms.MessageBoxIcon.Error);
// throw new VehicleForge.VFLoginException();
// }
// else
// {
// throw webEx;
// }
//}
}
private Dictionary<string, object> AppendSessionId(Dictionary<string, object> query)
{
this.Login();
if (query == null)
{
query = new Dictionary<string, object>();
}
Cookie session_id = AuthCookies.GetCookies(new Uri(ServerUrl)).Cast<Cookie>().First(x => x.Name == "_session_id");
query["_session_id"] = session_id.Value;
return query;
}
//public override string RestUrl
//{
// get { return"/rest"; }
//}
public override void Login()
{
if (this.m_lastLogin.Add(this.SessionTimeOut) > DateTime.Now)
{
return;
}
this.m_loggedIn = false;
Trace.TraceInformation("[VFAuthentication][Login] - Logging in: {0} as {1}", ServerUrl, this.m_credentials.Username);
// META-447: trash our cookies to get a new session id
this.AuthCookies = new CookieContainer();
// get new session id
// send request without authentication
try
{
this.SendRawGetRequest(this.AuthUrl);
}
catch (WebException webEx)
{
var status = webEx.Status;
string message = string.Format("{0}{1}{2}", webEx.Message, Environment.NewLine, webEx.Status);
throw new VehicleForge.VFInvalidURLException(message, webEx);
}
try
{
// DO NOT LOG PASSWORD!
this.LoggingEnabled = false;
string credentialsUrlEncoded = String.Format(
"username={0}&password={1}",
System.Web.HttpUtility.UrlEncode(this.m_credentials.Username),
System.Web.HttpUtility.UrlEncode(this.m_credentials.Password));
// TODO: How to detect invalid credentials?
// send request without authentication
using (var respone = this.SendRawPostRequestGetResponse(
this.LoginUrl, // url
null, // META-2204 query must not have credential info
credentialsUrlEncoded, // put credential information into the content
ISIS.Web.WebClient.ContentType.FormEncoded))
{
// VehicleForge returns '200' ONLY if failure occurs, so we check what url we are pointed to (login url)
if ((int)respone.StatusCode == 200)
{
string message = string.Format("Cannot login to VehicleForge {0} as {1}", this.ServerUrl, this.m_credentials.Username);
throw new VFLoginException(message);
}
Trace.WriteLine(string.Format("{0} {1} {2}", respone.ResponseUri, respone.StatusCode, respone.IsMutuallyAuthenticated));
this.m_lastLogin = DateTime.Now;
this.m_loggedIn = true;
}
}
finally
{
// enable logging again
this.LoggingEnabled = true;
}
}
public override bool TryPing()
{
bool success = false;
try
{
this.SendGetRequest(this.ServerUrl + "/rest/user/get_user_profile");
success = true;
}
catch (Exception)
{
success = false;
}
return success;
}
public string GetProfile()
{
return this.SendGetRequest("/rest/user/get_user_profile");
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation 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 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class DomainsEditDomain {
/// <summary>
/// asyncTasks control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.EnableAsyncTasksSupport asyncTasks;
/// <summary>
/// DomainName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal DomainName;
/// <summary>
/// WebSitePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl WebSitePanel;
/// <summary>
/// WebSiteSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize WebSiteSection;
/// <summary>
/// BrowseWebSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink BrowseWebSite;
/// <summary>
/// WebSiteParkedPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl WebSiteParkedPanel;
/// <summary>
/// locDomainParkedWebSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDomainParkedWebSite;
/// <summary>
/// WebSitePointedPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl WebSitePointedPanel;
/// <summary>
/// locDomainPointWebSite control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDomainPointWebSite;
/// <summary>
/// WebSiteName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label WebSiteName;
/// <summary>
/// MailDomainPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl MailDomainPanel;
/// <summary>
/// MailDomainSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize MailDomainSection;
/// <summary>
/// MailEnabledPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl MailEnabledPanel;
/// <summary>
/// locMailDomain control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMailDomain;
/// <summary>
/// PointMailDomainPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl PointMailDomainPanel;
/// <summary>
/// locPointMailDomain control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locPointMailDomain;
/// <summary>
/// MailDomainName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label MailDomainName;
/// <summary>
/// DnsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl DnsPanel;
/// <summary>
/// DnsSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize DnsSection;
/// <summary>
/// DnsEnabledPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl DnsEnabledPanel;
/// <summary>
/// EditDnsRecords control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton EditDnsRecords;
/// <summary>
/// DisableDns control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton DisableDns;
/// <summary>
/// locDnsEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDnsEnabled;
/// <summary>
/// DnsDisabledPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl DnsDisabledPanel;
/// <summary>
/// EnableDns control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton EnableDns;
/// <summary>
/// locDnsDisabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locDnsDisabled;
/// <summary>
/// InstantAliasPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstantAliasPanel;
/// <summary>
/// InstantAliasSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize InstantAliasSection;
/// <summary>
/// InstantAliasDisabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstantAliasDisabled;
/// <summary>
/// CreateInstantAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton CreateInstantAlias;
/// <summary>
/// locInstantAliasDisabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locInstantAliasDisabled;
/// <summary>
/// InstantAliasEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl InstantAliasEnabled;
/// <summary>
/// DeleteInstantAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton DeleteInstantAlias;
/// <summary>
/// locInstantAliasEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locInstantAliasEnabled;
/// <summary>
/// locInstantAliasName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locInstantAliasName;
/// <summary>
/// InstantAliasName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label InstantAliasName;
/// <summary>
/// WebSiteAliasPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl WebSiteAliasPanel;
/// <summary>
/// locWebSiteAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locWebSiteAlias;
/// <summary>
/// WebSiteAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink WebSiteAlias;
/// <summary>
/// MailDomainAliasPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl MailDomainAliasPanel;
/// <summary>
/// locMailDomainAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize locMailDomainAlias;
/// <summary>
/// MailDomainAlias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label MailDomainAlias;
/// <summary>
/// ResellersPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlGenericControl ResellersPanel;
/// <summary>
/// ResellersSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize ResellersSection;
/// <summary>
/// AllowSubDomains control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox AllowSubDomains;
/// <summary>
/// DescribeAllowSubDomains control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize DescribeAllowSubDomains;
/// <summary>
/// buttonPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.ItemButtonPanel buttonPanel;
/// <summary>
/// btnDelete control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnDelete;
}
}
| |
using System;
using System.Collections.Generic;
using MiscUtil.Extensions;
namespace MiscUtil.Collections
{
/// <summary>
/// Represents a range of values. An IComparer{T} is used to compare specific
/// values with a start and end point. A range may be include or exclude each end
/// individually.
///
/// A range which is half-open but has the same start and end point is deemed to be empty,
/// e.g. [3,3) doesn't include 3. To create a range with a single value, use an inclusive
/// range, e.g. [3,3].
///
/// Ranges are always immutable - calls such as IncludeEnd() and ExcludeEnd() return a new
/// range without modifying this one.
/// </summary>
public sealed class Range<T>
{
readonly T start;
/// <summary>
/// The start of the range.
/// </summary>
public T Start
{
get { return start; }
}
readonly T end;
/// <summary>
/// The end of the range.
/// </summary>
public T End
{
get { return end; }
}
readonly IComparer<T> comparer;
/// <summary>
/// Comparer to use for comparisons
/// </summary>
public IComparer<T> Comparer
{
get { return comparer; }
}
readonly bool includesStart;
/// <summary>
/// Whether or not this range includes the start point
/// </summary>
public bool IncludesStart
{
get { return includesStart; }
}
readonly bool includesEnd;
/// <summary>
/// Whether or not this range includes the end point
/// </summary>
public bool IncludesEnd
{
get { return includesEnd; }
}
/// <summary>
/// Constructs a new inclusive range using the default comparer
/// </summary>
public Range(T start, T end)
: this(start, end, Comparer<T>.Default, true, true)
{
}
/// <summary>
/// Constructs a new range including both ends using the specified comparer
/// </summary>
public Range(T start, T end, IComparer<T> comparer)
: this(start, end, comparer, true, true)
{
}
/// <summary>
/// Constructs a new range, including or excluding each end as specified,
/// with the given comparer.
/// </summary>
public Range(T start, T end, IComparer<T> comparer, bool includeStart, bool includeEnd)
{
if (comparer.Compare(start, end) > 0)
{
throw new ArgumentOutOfRangeException("end", "start must be lower than end according to comparer");
}
this.start = start;
this.end = end;
this.comparer = comparer;
this.includesStart = includeStart;
this.includesEnd = includeEnd;
}
/// <summary>
/// Returns a range with the same boundaries as this, but excluding the end point.
/// When called on a range already excluding the end point, the original range is returned.
/// </summary>
public Range<T> ExcludeEnd()
{
if (!includesEnd)
{
return this;
}
return new Range<T>(start, end, comparer, includesStart, false);
}
/// <summary>
/// Returns a range with the same boundaries as this, but excluding the start point.
/// When called on a range already excluding the start point, the original range is returned.
/// </summary>
public Range<T> ExcludeStart()
{
if (!includesStart)
{
return this;
}
return new Range<T>(start, end, comparer, false, includesEnd);
}
/// <summary>
/// Returns a range with the same boundaries as this, but including the end point.
/// When called on a range already including the end point, the original range is returned.
/// </summary>
public Range<T> IncludeEnd()
{
if (includesEnd)
{
return this;
}
return new Range<T>(start, end, comparer, includesStart, true);
}
/// <summary>
/// Returns a range with the same boundaries as this, but including the start point.
/// When called on a range already including the start point, the original range is returned.
/// </summary>
public Range<T> IncludeStart()
{
if (includesStart)
{
return this;
}
return new Range<T>(start, end, comparer, true, includesEnd);
}
/// <summary>
/// Returns whether or not the range contains the given value
/// </summary>
public bool Contains(T value)
{
int lowerBound = comparer.Compare(value, start);
if (lowerBound < 0 || (lowerBound == 0 && !includesStart))
{
return false;
}
int upperBound = comparer.Compare(value, end);
return upperBound < 0 || (upperBound == 0 && includesEnd);
}
/// <summary>
/// Returns an iterator which begins at the start of this range,
/// applying the given step delegate on each iteration until the
/// end is reached or passed. The start and end points are included
/// or excluded according to this range.
/// </summary>
/// <param name="step">Delegate to apply to the "current value" on each iteration</param>
public RangeIterator<T> FromStart(Func<T, T> step)
{
return new RangeIterator<T>(this, step);
}
/// <summary>
/// Returns an iterator which begins at the end of this range,
/// applying the given step delegate on each iteration until the
/// start is reached or passed. The start and end points are included
/// or excluded according to this range.
/// </summary>
/// <param name="step">Delegate to apply to the "current value" on each iteration</param>
public RangeIterator<T> FromEnd(Func<T, T> step)
{
return new RangeIterator<T>(this, step, false);
}
#if DOTNET35
/// <summary>
/// Returns an iterator which begins at the start of this range,
/// adding the given step amount to the current value each iteration until the
/// end is reached or passed. The start and end points are included
/// or excluded according to this range. This method does not check for
/// the availability of an addition operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">Amount to add on each iteration</param>
public RangeIterator<T> UpBy(T stepAmount)
{
return new RangeIterator<T>(this, t => Operator.Add(t, stepAmount));
}
/// <summary>
/// Returns an iterator which begins at the end of this range,
/// subtracting the given step amount to the current value each iteration until the
/// start is reached or passed. The start and end points are included
/// or excluded according to this range. This method does not check for
/// the availability of a subtraction operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">Amount to subtract on each iteration. Note that
/// this is subtracted, so in a range [0,10] you would pass +2 as this parameter
/// to obtain the sequence (10, 8, 6, 4, 2, 0).
/// </param>
public RangeIterator<T> DownBy(T stepAmount)
{
return new RangeIterator<T>(this, t => Operator.Subtract(t, stepAmount), false);
}
/// <summary>
/// Returns an iterator which begins at the start of this range,
/// adding the given step amount to the current value each iteration until the
/// end is reached or passed. The start and end points are included
/// or excluded according to this range. This method does not check for
/// the availability of an addition operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">Amount to add on each iteration</param>
public RangeIterator<T> UpBy<TAmount>(TAmount stepAmount)
{
return new RangeIterator<T>(this, t => Operator.AddAlternative(t, stepAmount));
}
/// <summary>
/// Returns an iterator which begins at the end of this range,
/// subtracting the given step amount to the current value each iteration until the
/// start is reached or passed. The start and end points are included
/// or excluded according to this range. This method does not check for
/// the availability of a subtraction operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">Amount to subtract on each iteration. Note that
/// this is subtracted, so in a range [0,10] you would pass +2 as this parameter
/// to obtain the sequence (10, 8, 6, 4, 2, 0).
/// </param>
public RangeIterator<T> DownBy<TAmount>(TAmount stepAmount)
{
return new RangeIterator<T>(this, t => Operator.SubtractAlternative(t, stepAmount), false);
}
#endif
/// <summary>
/// Returns an iterator which steps through the range, applying the specified
/// step delegate on each iteration. The method determines whether to begin
/// at the start or end of the range based on whether the step delegate appears to go
/// "up" or "down". The step delegate is applied to the start point. If the result is
/// more than the start point, the returned iterator begins at the start point; otherwise
/// it begins at the end point.
/// </summary>
/// <param name="step">Delegate to apply to the "current value" on each iteration</param>
public RangeIterator<T> Step(Func<T, T> step)
{
step.ThrowIfNull("step");
bool ascending = (comparer.Compare(start, step(start)) < 0);
return ascending ? FromStart(step) : FromEnd(step);
}
#if DOTNET35
/// <summary>
/// Returns an iterator which steps through the range, adding the specified amount
/// on each iteration. If the step amount is logically negative, the returned iterator
/// begins at the start point; otherwise it begins at the end point.
/// This method does not check for
/// the availability of an addition operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">The amount to add on each iteration</param>
public RangeIterator<T> Step(T stepAmount)
{
return Step(t => Operator.Add(t, stepAmount));
}
/// <summary>
/// Returns an iterator which steps through the range, adding the specified amount
/// on each iteration. If the step amount is logically negative, the returned iterator
/// begins at the end point; otherwise it begins at the start point. This method
/// is equivalent to Step(T stepAmount), but allows an alternative type to be used.
/// The most common example of this is likely to be stepping a range of DateTimes
/// by a TimeSpan.
/// This method does not check for
/// the availability of a suitable addition operator at compile-time; if you use it
/// on a range where there is no such operator, it will fail at execution time.
/// </summary>
/// <param name="stepAmount">The amount to add on each iteration</param>
public RangeIterator<T> Step<TAmount>(TAmount stepAmount)
{
return Step(t => Operator.AddAlternative(t, stepAmount));
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
namespace Tharga.Toolkit.Console.Command.Base
{
public abstract class CommandBase : ICommandBase
{
private static readonly object SyncRoot = new object();
private readonly string _description;
private readonly string[] _names;
private IConsole _console;
protected HelpCommand HelpCommand { get; set; }
public string Name { get { return _names[0]; } }
public IEnumerable<string> Names { get { return _names; } }
public string Description { get { return _description; } }
internal IConsole Console { get { return _console; } }
internal CommandBase(IConsole console, string name, string description = null)
{
_console = console;
_names = new[] { name.ToLower() };
_description = description;
}
internal CommandBase(IConsole console, IEnumerable<string> names, string description = null)
{
_console = console;
_names = names.Select(x => x.ToLower()).ToArray();
_description = description;
}
public abstract Task<bool> InvokeAsync(string paramList);
protected abstract CommandBase GetHelpCommand();
public abstract bool CanExecute();
protected virtual string GetCanExecuteFailMessage()
{
return string.Format("You cannot execute this {0} command.", Name);
}
public virtual async Task<bool> InvokeWithCanExecuteCheckAsync(string paramList)
{
if (!CanExecute())
{
OutputWarning(GetCanExecuteFailMessage());
return true;
}
try
{
return await InvokeAsync(paramList);
}
catch (CommandEscapeException)
{
//TODO: This is used to exit an ongoing command. Is there another way, that does not use exceptions?
return false;
}
}
protected static string GetParam(string paramList, int index)
{
if (paramList == null) return null;
//Group items between delimiters " into one single string.
var verbs = GetDelimiteredVerbs(ref paramList, '\"');
var paramArray = paramList.Split(' ');
if (paramArray.Length <= index) return null;
//Put the grouped verbs back in to the original
if (verbs.Count > 0) for (var i = 0; i < paramArray.Length; i++) if (verbs.ContainsKey(paramArray[i])) paramArray[i] = verbs[paramArray[i]];
return paramArray[index];
}
private static Dictionary<string, string> GetDelimiteredVerbs(ref string paramList, char delimiter)
{
var verbs = new Dictionary<string, string>();
var pos = paramList.IndexOf(delimiter, 0);
while (pos != -1)
{
var endPos = paramList.IndexOf(delimiter, pos + 1);
var data = paramList.Substring(pos + 1, endPos - pos - 1);
var key = Guid.NewGuid().ToString();
verbs.Add(key, data);
paramList = paramList.Substring(0, pos) + key + paramList.Substring(endPos + 1);
pos = paramList.IndexOf(delimiter, pos + 1);
}
return verbs;
}
internal string QueryRootParam()
{
return QueryParam<string>("> ", null, null, false);
}
protected T DefaultQueryParam<T>(string paramName, string defaultValue = null)
{
string value;
if (!string.IsNullOrEmpty(defaultValue))
{
value = QueryParam(paramName + (defaultValue == null ? "" : "(" + defaultValue + ")"), null, () => new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(defaultValue, "") });
}
else
{
value = QueryParam(paramName + (defaultValue == null ? "" : "(" + defaultValue + ")"), null, (Func<List<KeyValuePair<string, string>>>)null);
}
var response = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value);
return response;
}
protected T QueryParam<T>(string paramName, string autoProvideValue = null, string defaultValue = null)
{
string value;
if (!string.IsNullOrEmpty(autoProvideValue))
{
value = autoProvideValue;
}
else
{
if (!string.IsNullOrEmpty(defaultValue))
{
value = QueryParam(paramName, null, () => new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>(defaultValue, defaultValue) });
}
else
{
value = QueryParam(paramName, null, (Func<List<KeyValuePair<string, string>>>)null);
}
}
var response = (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(value);
return response;
}
public void StartTask(string name, bool indeterminate, Action<ProgressConsole> action)
{
using (var pgconsole = new ProgressConsole(name, this.Console, indeterminate))
{
if(action != null)
{
action.Invoke(pgconsole);
}
}
}
protected T QueryParam<T>(string paramName, string autoProvideValue, Func<List<KeyValuePair<T, string>>> selectionDelegate)
{
return QueryParam<T>(paramName, autoProvideValue, selectionDelegate, true);
}
private T QueryParam<T>(string paramName, string autoProvideValue, Func<List<KeyValuePair<T, string>>> selectionDelegate, bool allowEscape)
{
var selection = new List<KeyValuePair<T, string>>();
if (selectionDelegate != null)
{
selection = selectionDelegate.Invoke();
var q = GetParamByString(autoProvideValue, selection);
if (q != null)
{
return q.Value.Key;
}
}
var inputManager = new InputManager(_console, this, paramName);
var response = inputManager.ReadLine(selection.ToArray(), allowEscape);
return response;
}
private static KeyValuePair<T, string>? GetParamByString<T>(string autoProvideValue, List<KeyValuePair<T, string>> selection)
{
if (!string.IsNullOrEmpty(autoProvideValue))
{
var item = selection.SingleOrDefault(x => string.Compare(x.Value, autoProvideValue, StringComparison.InvariantCultureIgnoreCase) == 0);
if (item.Value == autoProvideValue)
{
return item;
}
item = selection.SingleOrDefault(x => string.Compare(x.Key.ToString(), autoProvideValue, StringComparison.InvariantCultureIgnoreCase) == 0);
if (item.Key.ToString() == autoProvideValue)
{
return item;
}
throw new InvalidOperationException("Cannot find provided value in selection.");
}
return null;
}
public void OutputError(string message, params object[] args)
{
Output(message, ConsoleColor.Red, true, args);
}
public void OutputWarning(string message, params object[] args)
{
Output(message, ConsoleColor.Yellow, true, args);
}
public void OutputInformation(string message, params object[] args)
{
Output(message, null, true, args);
}
public void OutputEvent(string message, params object[] args)
{
lock (SyncRoot)
{
var cursorLeft = _console.CursorLeft;
if (cursorLeft != 0)
{
message = string.Format(message, args);
var lines = (int)Math.Ceiling(message.Length / (decimal)_console.BufferWidth);
_console.MoveBufferArea(0, _console.CursorTop, cursorLeft, 1, 0, _console.CursorTop + lines);
_console.SetCursorPosition(0, _console.CursorTop);
}
Output(message, ConsoleColor.Yellow, true, args);
if (cursorLeft != 0)
{
_console.SetCursorPosition(cursorLeft, _console.CursorTop);
}
}
}
public void Output(string message, ConsoleColor? color, bool line, params object[] args)
{
lock (SyncRoot)
{
var defaultColor = ConsoleColor.White;
try
{
if (color != null)
{
defaultColor = _console.ForegroundColor;
_console.ForegroundColor = color.Value;
}
if (line)
{
if (args == null)
{
_console.WriteLine(message);
}
else
{
_console.WriteLine(string.Format(message, args));
}
}
else
{
_console.Write(message, args);
}
}
finally
{
if (color != null)
{
_console.ForegroundColor = defaultColor;
}
}
}
}
internal void OutputInformationLine(string message, bool commandMode)
{
if (commandMode)
{
//By default, do not output information when in command mode
return;
}
Output(message, null, true, null);
}
public virtual void CommandRegistered(IConsole console)
{
_console = console;
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorMailModule.cs 592 2009-05-27 13:40:43Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.Web;
using System.IO;
#if NET_1_0 || NET_1_1
using System.Web.Mail;
#else
using System.Net.Mail;
using MailAttachment = System.Net.Mail.Attachment;
#endif
using IDictionary = System.Collections.IDictionary;
using ThreadPool = System.Threading.ThreadPool;
using WaitCallback = System.Threading.WaitCallback;
using Encoding = System.Text.Encoding;
using NetworkCredential = System.Net.NetworkCredential;
#endregion
public sealed class ErrorMailEventArgs : EventArgs
{
private readonly Error _error;
private readonly MailMessage _mail;
public ErrorMailEventArgs(Error error, MailMessage mail)
{
if (error == null)
throw new ArgumentNullException("error");
if (mail == null)
throw new ArgumentNullException("mail");
_error = error;
_mail = mail;
}
public Error Error
{
get { return _error; }
}
public MailMessage Mail
{
get { return _mail; }
}
}
public delegate void ErrorMailEventHandler(object sender, ErrorMailEventArgs args);
/// <summary>
/// HTTP module that sends an e-mail whenever an unhandled exception
/// occurs in an ASP.NET web application.
/// </summary>
public class ErrorMailModule : HttpModuleBase, IExceptionFiltering
{
private string _mailSender;
private string _mailRecipient;
private string _mailCopyRecipient;
private string _mailSubjectFormat;
private MailPriority _mailPriority;
private bool _reportAsynchronously;
private string _smtpServer;
private int _smtpPort;
private string _authUserName;
private string _authPassword;
private bool _noYsod;
#if !NET_1_0 && !NET_1_1
private bool _useSsl;
#endif
public event ExceptionFilterEventHandler Filtering;
public event ErrorMailEventHandler Mailing;
public event ErrorMailEventHandler Mailed;
public event ErrorMailEventHandler DisposingMail;
/// <summary>
/// Initializes the module and prepares it to handle requests.
/// </summary>
protected override void OnInit(HttpApplication application)
{
if (application == null)
throw new ArgumentNullException("application");
//
// Get the configuration section of this module.
// If it's not there then there is nothing to initialize or do.
// In this case, the module is as good as mute.
//
IDictionary config = (IDictionary) GetConfig();
if (config == null)
return;
//
// Extract the settings.
//
string mailRecipient = GetSetting(config, "to");
string mailSender = GetSetting(config, "from", mailRecipient);
string mailCopyRecipient = GetSetting(config, "cc", string.Empty);
string mailSubjectFormat = GetSetting(config, "subject", string.Empty);
MailPriority mailPriority = (MailPriority) Enum.Parse(typeof(MailPriority), GetSetting(config, "priority", MailPriority.Normal.ToString()), true);
bool reportAsynchronously = Convert.ToBoolean(GetSetting(config, "async", bool.TrueString));
string smtpServer = GetSetting(config, "smtpServer", string.Empty);
int smtpPort = Convert.ToUInt16(GetSetting(config, "smtpPort", "0"), CultureInfo.InvariantCulture);
string authUserName = GetSetting(config, "userName", string.Empty);
string authPassword = GetSetting(config, "password", string.Empty);
bool sendYsod = Convert.ToBoolean(GetSetting(config, "noYsod", bool.FalseString));
#if !NET_1_0 && !NET_1_1
bool useSsl = Convert.ToBoolean(GetSetting(config, "useSsl", bool.FalseString));
#endif
//
// Hook into the Error event of the application.
//
application.Error += new EventHandler(OnError);
ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled);
//
// Finally, commit the state of the module if we got this far.
// Anything beyond this point should not cause an exception.
//
_mailRecipient = mailRecipient;
_mailSender = mailSender;
_mailCopyRecipient = mailCopyRecipient;
_mailSubjectFormat = mailSubjectFormat;
_mailPriority = mailPriority;
_reportAsynchronously = reportAsynchronously;
_smtpServer = smtpServer;
_smtpPort = smtpPort;
_authUserName = authUserName;
_authPassword = authPassword;
_noYsod = sendYsod;
#if !NET_1_0 && !NET_1_1
_useSsl = useSsl;
#endif
}
/// <summary>
/// Determines whether the module will be registered for discovery
/// in partial trust environments or not.
/// </summary>
protected override bool SupportDiscoverability
{
get { return true; }
}
/// <summary>
/// Gets the e-mail address of the sender.
/// </summary>
protected virtual string MailSender
{
get { return _mailSender; }
}
/// <summary>
/// Gets the e-mail address of the recipient, or a
/// comma-/semicolon-delimited list of e-mail addresses in case of
/// multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailRecipient
{
get { return _mailRecipient; }
}
/// <summary>
/// Gets the e-mail address of the recipient for mail carbon
/// copy (CC), or a comma-/semicolon-delimited list of e-mail
/// addresses in case of multiple recipients.
/// </summary>
/// <remarks>
/// When using System.Web.Mail components under .NET Framework 1.x,
/// multiple recipients must be semicolon-delimited.
/// When using System.Net.Mail components under .NET Framework 2.0
/// or later, multiple recipients must be comma-delimited.
/// </remarks>
protected virtual string MailCopyRecipient
{
get { return _mailCopyRecipient; }
}
/// <summary>
/// Gets the text used to format the e-mail subject.
/// </summary>
/// <remarks>
/// The subject text specification may include {0} where the
/// error message (<see cref="Error.Message"/>) should be inserted
/// and {1} <see cref="Error.Type"/> where the error type should
/// be insert.
/// </remarks>
protected virtual string MailSubjectFormat
{
get { return _mailSubjectFormat; }
}
/// <summary>
/// Gets the priority of the e-mail.
/// </summary>
protected virtual MailPriority MailPriority
{
get { return _mailPriority; }
}
/// <summary>
/// Gets the SMTP server host name used when sending the mail.
/// </summary>
protected string SmtpServer
{
get { return _smtpServer; }
}
/// <summary>
/// Gets the SMTP port used when sending the mail.
/// </summary>
protected int SmtpPort
{
get { return _smtpPort; }
}
/// <summary>
/// Gets the user name to use if the SMTP server requires authentication.
/// </summary>
protected string AuthUserName
{
get { return _authUserName; }
}
/// <summary>
/// Gets the clear-text password to use if the SMTP server requires
/// authentication.
/// </summary>
protected string AuthPassword
{
get { return _authPassword; }
}
/// <summary>
/// Indicates whether <a href="http://en.wikipedia.org/wiki/Screens_of_death#ASP.NET">YSOD</a>
/// is attached to the e-mail or not. If <c>true</c>, the YSOD is
/// not attached.
/// </summary>
protected bool NoYsod
{
get { return _noYsod; }
}
#if !NET_1_0 && !NET_1_1
/// <summary>
/// Determines if SSL will be used to encrypt communication with the
/// mail server.
/// </summary>
protected bool UseSsl
{
get { return _useSsl; }
}
#endif
/// <summary>
/// The handler called when an unhandled exception bubbles up to
/// the module.
/// </summary>
protected virtual void OnError(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication) sender).Context;
OnError(context.Server.GetLastError(), context);
}
/// <summary>
/// The handler called when an exception is explicitly signaled.
/// </summary>
protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args)
{
OnError(args.Exception, args.Context);
}
/// <summary>
/// Reports the exception.
/// </summary>
protected virtual void OnError(Exception e, HttpContext context)
{
if (e == null)
throw new ArgumentNullException("e");
//
// Fire an event to check if listeners want to filter out
// reporting of the uncaught exception.
//
ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context);
OnFiltering(args);
if (args.Dismissed)
return;
//
// Get the last error and then report it synchronously or
// asynchronously based on the configuration.
//
Error error = new Error(e, context);
if (_reportAsynchronously)
ReportErrorAsync(error);
else
ReportError(error);
}
/// <summary>
/// Raises the <see cref="Filtering"/> event.
/// </summary>
protected virtual void OnFiltering(ExceptionFilterEventArgs args)
{
ExceptionFilterEventHandler handler = Filtering;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Schedules the error to be e-mailed asynchronously.
/// </summary>
/// <remarks>
/// The default implementation uses the <see cref="ThreadPool"/>
/// to queue the reporting.
/// </remarks>
protected virtual void ReportErrorAsync(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Schedule the reporting at a later time using a worker from
// the system thread pool. This makes the implementation
// simpler, but it might have an impact on reducing the
// number of workers available for processing ASP.NET
// requests in the case where lots of errors being generated.
//
ThreadPool.QueueUserWorkItem(new WaitCallback(ReportError), error);
}
private void ReportError(object state)
{
try
{
ReportError((Error) state);
}
//
// Catch and trace COM/SmtpException here because this
// method will be called on a thread pool thread and
// can either fail silently in 1.x or with a big band in
// 2.0. For latter, see the following MS KB article for
// details:
//
// Unhandled exceptions cause ASP.NET-based applications
// to unexpectedly quit in the .NET Framework 2.0
// http://support.microsoft.com/kb/911816
//
#if NET_1_0 || NET_1_1
catch (System.Runtime.InteropServices.COMException e)
{
Trace.WriteLine(e);
}
#else
catch (SmtpException e)
{
Trace.TraceError(e.ToString());
}
#endif
}
/// <summary>
/// Schedules the error to be e-mailed synchronously.
/// </summary>
protected virtual void ReportError(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Start by checking if we have a sender and a recipient.
// These values may be null if someone overrides the
// implementation of OnInit but does not override the
// MailSender and MailRecipient properties.
//
string sender = Mask.NullString(this.MailSender);
string recipient = Mask.NullString(this.MailRecipient);
string copyRecipient = Mask.NullString(this.MailCopyRecipient);
// TODO: Under 2.0, the sender can be defaulted via <network> configuration so consider only checking recipient here.
if (sender.Length == 0 || recipient.Length == 0)
return;
//
// Create the mail, setting up the sender and recipient and priority.
//
MailMessage mail = new MailMessage();
mail.Priority = this.MailPriority;
#if NET_1_0 || NET_1_1
mail.From = sender;
mail.To = recipient;
if (copyRecipient.Length > 0)
mail.Cc = copyRecipient;
#else
mail.From = new MailAddress(sender);
mail.To.Add(recipient);
if (copyRecipient.Length > 0)
mail.CC.Add(copyRecipient);
#endif
//
// Format the mail subject.
//
string subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}");
mail.Subject = string.Format(subjectFormat, error.Message, error.Type).
Replace('\r', ' ').Replace('\n', ' ');
//
// Format the mail body.
//
ErrorTextFormatter formatter = CreateErrorFormatter();
StringWriter bodyWriter = new StringWriter();
formatter.Format(bodyWriter, error);
mail.Body = bodyWriter.ToString();
switch (formatter.MimeType)
{
#if NET_1_0 || NET_1_1
case "text/html" : mail.BodyFormat = MailFormat.Html; break;
case "text/plain" : mail.BodyFormat = MailFormat.Text; break;
#else
case "text/html": mail.IsBodyHtml = true; break;
case "text/plain": mail.IsBodyHtml = false; break;
#endif
default :
{
throw new ApplicationException(string.Format(
"The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.",
formatter.GetType().FullName, formatter.MimeType));
}
}
#if NET_1_1
//
// If the mail needs to be delivered to a particular SMTP server
// then set-up the corresponding CDO configuration fields of the
// mail message.
//
string smtpServer = Mask.NullString(this.SmtpServer);
if (smtpServer.Length > 0)
{
IDictionary fields = mail.Fields;
fields.Add(CdoConfigurationFields.SendUsing, /* cdoSendUsingPort */ 2);
fields.Add(CdoConfigurationFields.SmtpServer, smtpServer);
int smtpPort = this.SmtpPort;
fields.Add(CdoConfigurationFields.SmtpServerPort, smtpPort <= 0 ? 25 : smtpPort);
//
// If the SMTP server requires authentication (indicated by
// non-blank user name and password settings) then set-up
// the corresponding CDO configuration fields of the mail
// message.
//
string userName = Mask.NullString(this.AuthUserName);
string password = Mask.NullString(this.AuthPassword);
if (userName.Length > 0 && password.Length > 0)
{
fields.Add(CdoConfigurationFields.SmtpAuthenticate, 1);
fields.Add(CdoConfigurationFields.SendUserName, userName);
fields.Add(CdoConfigurationFields.SendPassword, password);
}
}
#endif
MailAttachment ysodAttachment = null;
ErrorMailEventArgs args = new ErrorMailEventArgs(error, mail);
try
{
//
// If an HTML message was supplied by the web host then attach
// it to the mail if not explicitly told not to do so.
//
if (!NoYsod && error.WebHostHtmlMessage.Length > 0)
{
ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage);
if (ysodAttachment != null)
mail.Attachments.Add(ysodAttachment);
}
//
// Send off the mail with some chance to pre- or post-process
// using event.
//
OnMailing(args);
SendMail(mail);
OnMailed(args);
}
finally
{
#if NET_1_0 || NET_1_1
//
// Delete any attached files, if necessary.
//
if (ysodAttachment != null)
{
File.Delete(ysodAttachment.Filename);
mail.Attachments.Remove(ysodAttachment);
}
#endif
OnDisposingMail(args);
#if !NET_1_0 && !NET_1_1
mail.Dispose();
#endif
}
}
private static MailAttachment CreateHtmlAttachment(string name, string html)
{
Debug.AssertStringNotEmpty(name);
Debug.AssertStringNotEmpty(html);
#if NET_1_0 || NET_1_1
//
// Create a temporary file to hold the attachment. Note that
// the temporary file is created in the location returned by
// System.Web.HttpRuntime.CodegenDir. It is assumed that
// this code will have sufficient rights to create the
// temporary file in that area.
//
string fileName = name + "-" + Guid.NewGuid().ToString() + ".html";
string path = Path.Combine(HttpRuntime.CodegenDir, fileName);
try
{
using (StreamWriter attachementWriter = File.CreateText(path))
attachementWriter.Write(html);
return new MailAttachment(path);
}
catch (IOException)
{
//
// Ignore I/O errors as non-critical. It's not the
// end of the world if the attachment could not be
// created (though it would be nice). It is more
// important to get to deliver the error message!
//
return null;
}
#else
return MailAttachment.CreateAttachmentFromString(html,
name + ".html", Encoding.UTF8, "text/html");
#endif
}
/// <summary>
/// Creates the <see cref="ErrorTextFormatter"/> implementation to
/// be used to format the body of the e-mail.
/// </summary>
protected virtual ErrorTextFormatter CreateErrorFormatter()
{
return new ErrorMailHtmlFormatter();
}
/// <summary>
/// Sends the e-mail using SmtpMail or SmtpClient.
/// </summary>
protected virtual void SendMail(MailMessage mail)
{
if (mail == null)
throw new ArgumentNullException("mail");
#if NET_1_0 || NET_1_1
SmtpMail.Send(mail);
#else
//
// Under .NET Framework 2.0, the authentication settings
// go on the SmtpClient object rather than mail message
// so these have to be set up here.
//
SmtpClient client = new SmtpClient();
string host = SmtpServer ?? string.Empty;
if (host.Length > 0)
client.Host = host;
int port = SmtpPort;
if (port > 0)
client.Port = port;
string userName = AuthUserName ?? string.Empty;
string password = AuthPassword ?? string.Empty;
// TODO: Allow use of default credentials?
if (userName.Length > 0 && password.Length > 0)
client.Credentials = new NetworkCredential(userName, password);
client.EnableSsl = UseSsl;
client.Send(mail);
#endif
}
/// <summary>
/// Fires the <see cref="Mailing"/> event.
/// </summary>
protected virtual void OnMailing(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailing;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="Mailed"/> event.
/// </summary>
protected virtual void OnMailed(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = Mailed;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Fires the <see cref="DisposingMail"/> event.
/// </summary>
protected virtual void OnDisposingMail(ErrorMailEventArgs args)
{
if (args == null)
throw new ArgumentNullException("args");
ErrorMailEventHandler handler = DisposingMail;
if (handler != null)
handler(this, args);
}
/// <summary>
/// Gets the configuration object used by <see cref="OnInit"/> to read
/// the settings for module.
/// </summary>
protected virtual object GetConfig()
{
return Configuration.GetSubsection("errorMail");
}
/// <summary>
/// Builds an <see cref="Error"/> object from the last context
/// exception generated.
/// </summary>
[ Obsolete ]
protected virtual Error GetLastError(HttpContext context)
{
throw new NotSupportedException();
}
private static string GetSetting(IDictionary config, string name)
{
return GetSetting(config, name, null);
}
private static string GetSetting(IDictionary config, string name, string defaultValue)
{
Debug.Assert(config != null);
Debug.AssertStringNotEmpty(name);
string value = Mask.NullString((string) config[name]);
if (value.Length == 0)
{
if (defaultValue == null)
{
throw new ApplicationException(string.Format(
"The required configuration setting '{0}' is missing for the error mailing module.", name));
}
value = defaultValue;
}
return value;
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole, Rob Prouse
//
// 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.Globalization;
using System.IO;
using System.Reflection;
using NUnit.Common;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
#if NETSTANDARD1_3 || NETSTANDARD1_6
using System.Runtime.InteropServices;
#endif
namespace NUnitLite
{
public class TextUI
{
public ExtendedTextWriter Writer { get; private set; }
private readonly TextReader _reader;
private readonly NUnitLiteOptions _options;
private readonly bool _displayBeforeTest;
private readonly bool _displayAfterTest;
private readonly bool _displayBeforeOutput;
#region Constructor
public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options)
{
Writer = writer;
_reader = reader;
_options = options;
string labelsOption = options.DisplayTestLabels?.ToUpperInvariant() ?? "ON";
_displayBeforeTest = labelsOption == "ALL" || labelsOption == "BEFORE";
_displayAfterTest = labelsOption == "AFTER";
_displayBeforeOutput = _displayBeforeTest || _displayAfterTest || labelsOption == "ON";
}
#endregion
#region Public Methods
#region DisplayHeader
/// <summary>
/// Writes the header.
/// </summary>
public void DisplayHeader()
{
Assembly executingAssembly = GetType().GetTypeInfo().Assembly;
AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly);
Version version = assemblyName.Version;
string copyright = "Copyright (C) 2017 Charlie Poole, Rob Prouse";
string build = "";
var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>();
if (copyrightAttr != null)
copyright = copyrightAttr.Copyright;
var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
if (configAttr != null)
build = string.Format("({0})", configAttr.Configuration);
WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build));
WriteSubHeader(copyright);
Writer.WriteLine();
}
#endregion
#region DisplayTestFiles
public void DisplayTestFiles(IEnumerable<string> testFiles)
{
WriteSectionHeader("Test Files");
foreach (string testFile in testFiles)
Writer.WriteLine(ColorStyle.Default, " " + testFile);
Writer.WriteLine();
}
#endregion
#region DisplayHelp
public void DisplayHelp()
{
WriteHeader("Usage: NUNITLITE-RUNNER assembly [options]");
WriteHeader(" USER-EXECUTABLE [options]");
Writer.WriteLine();
WriteHelpLine("Runs a set of NUnitLite tests from the console.");
Writer.WriteLine();
WriteSectionHeader("Assembly:");
WriteHelpLine(" File name or path of the assembly from which to execute tests. Required");
WriteHelpLine(" when using the nunitlite-runner executable to run the tests. Not allowed");
WriteHelpLine(" when running a self-executing user test assembly.");
Writer.WriteLine();
WriteSectionHeader("Options:");
using (var sw = new StringWriter())
{
_options.WriteOptionDescriptions(sw);
Writer.Write(ColorStyle.Help, sw.ToString());
}
WriteSectionHeader("Notes:");
WriteHelpLine(" * File names may be listed by themselves, with a relative path or ");
WriteHelpLine(" using an absolute path. Any relative path is based on the current ");
WriteHelpLine(" directory or on the Documents folder if running on a under the ");
WriteHelpLine(" compact framework.");
Writer.WriteLine();
WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired");
Writer.WriteLine();
WriteHelpLine(" * Options that take values may use an equal sign or a colon");
WriteHelpLine(" to separate the option from its value.");
Writer.WriteLine();
WriteHelpLine(" * Several options that specify processing of XML output take");
WriteHelpLine(" an output specification as a value. A SPEC may take one of");
WriteHelpLine(" the following forms:");
WriteHelpLine(" --OPTION:filename");
WriteHelpLine(" --OPTION:filename;format=formatname");
Writer.WriteLine();
WriteHelpLine(" The --result option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit");
Writer.WriteLine();
WriteHelpLine(" The --explore option may use any of the following formats:");
WriteHelpLine(" nunit3 - the native XML format for NUnit 3");
WriteHelpLine(" cases - a text file listing the full names of all test cases.");
WriteHelpLine(" If --explore is used without any specification following, a list of");
WriteHelpLine(" test cases is output to the console.");
Writer.WriteLine();
}
#endregion
#region DisplayRuntimeEnvironment
/// <summary>
/// Displays info about the runtime environment.
/// </summary>
public void DisplayRuntimeEnvironment()
{
WriteSectionHeader("Runtime Environment");
#if NETSTANDARD1_3 || NETSTANDARD1_6
Writer.WriteLabelLine(" OS Version: ", RuntimeInformation.OSDescription);
Writer.WriteLabelLine(" CLR Version: ", RuntimeInformation.FrameworkDescription);
#else
Writer.WriteLabelLine(" OS Version: ", OSPlatform.CurrentPlatform);
Writer.WriteLabelLine(" CLR Version: ", Environment.Version);
#endif
Writer.WriteLine();
}
#endregion
#region DisplayTestFilters
public void DisplayTestFilters()
{
if (_options.TestList.Count > 0 || _options.WhereClauseSpecified)
{
WriteSectionHeader("Test Filters");
if (_options.TestList.Count > 0)
foreach (string testName in _options.TestList)
Writer.WriteLabelLine(" Test: ", testName);
if (_options.WhereClauseSpecified)
Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim());
Writer.WriteLine();
}
}
#endregion
#region DisplayRunSettings
public void DisplayRunSettings()
{
WriteSectionHeader("Run Settings");
if (_options.DefaultTimeout >= 0)
Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout);
#if PARALLEL
Writer.WriteLabelLine(
" Number of Test Workers: ",
_options.NumberOfTestWorkers >= 0
? _options.NumberOfTestWorkers
: Math.Max(Environment.ProcessorCount, 2));
#endif
Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? Directory.GetCurrentDirectory());
Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off");
if (_options.TeamCity)
Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages");
Writer.WriteLine();
}
#endregion
#region TestStarted
public void TestStarted(ITest test)
{
if (_displayBeforeTest && !test.IsSuite)
WriteLabelLine(test.FullName);
}
#endregion
#region TestFinished
private bool _testCreatedOutput = false;
private bool _needsNewLine = false;
public void TestFinished(ITestResult result)
{
if (result.Output.Length > 0)
{
if (_displayBeforeOutput)
WriteLabelLine(result.Test.FullName);
WriteOutput(result.Output);
if (!result.Output.EndsWith("\n"))
Writer.WriteLine();
}
if (!result.Test.IsSuite)
{
if (_displayAfterTest)
WriteLabelLineAfterTest(result.Test.FullName, result.ResultState);
}
if (result.Test is TestAssembly && _testCreatedOutput)
{
Writer.WriteLine();
_testCreatedOutput = false;
}
}
#endregion
#region TestOutput
public void TestOutput(TestOutput output)
{
if (_displayBeforeOutput && output.TestName != null)
WriteLabelLine(output.TestName);
WriteOutput(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text);
}
#endregion
#region WaitForUser
public void WaitForUser(string message)
{
// Ignore if we don't have a TextReader
if (_reader != null)
{
Writer.WriteLine(ColorStyle.Label, message);
_reader.ReadLine();
}
}
#endregion
#region Test Result Reports
#region DisplaySummaryReport
public void DisplaySummaryReport(ResultSummary summary)
{
var status = summary.ResultState.Status;
var overallResult = status.ToString();
if (overallResult == "Skipped")
overallResult = "Warning";
ColorStyle overallStyle = status == TestStatus.Passed
? ColorStyle.Pass
: status == TestStatus.Failed
? ColorStyle.Failure
: status == TestStatus.Skipped
? ColorStyle.Warning
: ColorStyle.Output;
if (_testCreatedOutput)
Writer.WriteLine();
WriteSectionHeader("Test Run Summary");
Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle);
WriteSummaryCount(" Test Count: ", summary.TestCount);
WriteSummaryCount(", Passed: ", summary.PassCount);
WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure);
WriteSummaryCount(", Warnings: ", summary.WarningCount, ColorStyle.Warning);
WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount);
WriteSummaryCount(", Skipped: ", summary.TotalSkipCount);
Writer.WriteLine();
if (summary.FailedCount > 0)
{
WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure);
WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error);
WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error);
Writer.WriteLine();
}
if (summary.TotalSkipCount > 0)
{
WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning);
WriteSummaryCount(", Explicit: ", summary.ExplicitCount);
WriteSummaryCount(", Other: ", summary.SkipCount);
Writer.WriteLine();
}
Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u"));
Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u"));
Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration));
Writer.WriteLine();
}
private void WriteSummaryCount(string label, int count)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture));
}
private void WriteSummaryCount(string label, int count, ColorStyle color)
{
Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value);
}
#endregion
#region DisplayErrorsAndFailuresReport
public void DisplayErrorsFailuresAndWarningsReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Errors, Failures and Warnings");
DisplayErrorsFailuresAndWarnings(result);
Writer.WriteLine();
if (_options.StopOnError)
{
Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error");
Writer.WriteLine();
}
}
#endregion
#region DisplayNotRunReport
public void DisplayNotRunReport(ITestResult result)
{
_reportIndex = 0;
WriteSectionHeader("Tests Not Run");
DisplayNotRunResults(result);
Writer.WriteLine();
}
#endregion
#region DisplayFullReport
#if FULL // Not currently used, but may be reactivated
/// <summary>
/// Prints a full report of all results
/// </summary>
public void DisplayFullReport(ITestResult result)
{
WriteLine(ColorStyle.SectionHeader, "All Test Results -");
_writer.WriteLine();
DisplayAllResults(result, " ");
_writer.WriteLine();
}
#endif
#endregion
#endregion
#region DisplayWarning
public void DisplayWarning(string text)
{
Writer.WriteLine(ColorStyle.Warning, text);
}
#endregion
#region DisplayError
public void DisplayError(string text)
{
Writer.WriteLine(ColorStyle.Error, text);
}
#endregion
#region DisplayErrors
public void DisplayErrors(IList<string> messages)
{
foreach (string message in messages)
DisplayError(message);
}
#endregion
#endregion
#region Helper Methods
private void DisplayErrorsFailuresAndWarnings(ITestResult result)
{
bool display =
result.ResultState.Status == TestStatus.Failed ||
result.ResultState.Status == TestStatus.Warning;
if (result.Test.IsSuite)
{
if (display)
{
var suite = result.Test as TestSuite;
var site = result.ResultState.Site;
if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown)
DisplayTestResult(result);
if (site == FailureSite.SetUp) return;
}
foreach (ITestResult childResult in result.Children)
DisplayErrorsFailuresAndWarnings(childResult);
}
else if (display)
DisplayTestResult(result);
}
private void DisplayNotRunResults(ITestResult result)
{
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
DisplayNotRunResults(childResult);
else if (result.ResultState.Status == TestStatus.Skipped)
DisplayTestResult(result);
}
private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' };
private int _reportIndex;
private void DisplayTestResult(ITestResult result)
{
ResultState resultState = result.ResultState;
string fullName = result.FullName;
string message = result.Message;
string stackTrace = result.StackTrace;
string reportID = (++_reportIndex).ToString();
int numAsserts = result.AssertionResults.Count;
#if NETSTANDARD1_3 && !NETSTANDARD1_6
ColorStyle style = GetColorStyle(resultState);
string status = GetResultStatus(resultState);
DisplayTestResult(style, reportID, status, fullName, message, stackTrace);
#else
if (numAsserts > 0)
{
int assertionCounter = 0;
string assertID = reportID;
foreach (var assertion in result.AssertionResults)
{
if (numAsserts > 1)
assertID = string.Format("{0}-{1}", reportID, ++assertionCounter);
ColorStyle style = GetColorStyle(resultState);
string status = assertion.Status.ToString();
DisplayTestResult(style, assertID, status, fullName, assertion.Message, assertion.StackTrace);
}
}
else
{
ColorStyle style = GetColorStyle(resultState);
string status = GetResultStatus(resultState);
DisplayTestResult(style, reportID, status, fullName, message, stackTrace);
}
#endif
}
private void DisplayTestResult(ColorStyle style, string prefix, string status, string fullName, string message, string stackTrace)
{
Writer.WriteLine();
Writer.WriteLine(
style, string.Format("{0}) {1} : {2}", prefix, status, fullName));
if (!string.IsNullOrEmpty(message))
Writer.WriteLine(style, message.TrimEnd(TRIM_CHARS));
if (!string.IsNullOrEmpty(stackTrace))
Writer.WriteLine(style, stackTrace.TrimEnd(TRIM_CHARS));
}
private static ColorStyle GetColorStyle(ResultState resultState)
{
ColorStyle style = ColorStyle.Output;
switch (resultState.Status)
{
case TestStatus.Failed:
style = ColorStyle.Failure;
break;
case TestStatus.Warning:
style = ColorStyle.Warning;
break;
case TestStatus.Skipped:
style = resultState.Label == "Ignored" ? ColorStyle.Warning : ColorStyle.Output;
break;
case TestStatus.Passed:
style = ColorStyle.Pass;
break;
}
return style;
}
private static string GetResultStatus(ResultState resultState)
{
string status = resultState.Label;
if (string.IsNullOrEmpty(status))
status = resultState.Status.ToString();
if (status == "Failed" || status == "Error")
{
var site = resultState.Site.ToString();
if (site == "SetUp" || site == "TearDown")
status = site + " " + status;
}
return status;
}
#if FULL
private void DisplayAllResults(ITestResult result, string indent)
{
string status = null;
ColorStyle style = ColorStyle.Output;
switch (result.ResultState.Status)
{
case TestStatus.Failed:
status = "FAIL";
style = ColorStyle.Failure;
break;
case TestStatus.Skipped:
if (result.ResultState.Label == "Ignored")
{
status = "IGN ";
style = ColorStyle.Warning;
}
else
{
status = "SKIP";
style = ColorStyle.Output;
}
break;
case TestStatus.Inconclusive:
status = "INC ";
style = ColorStyle.Output;
break;
case TestStatus.Passed:
status = "OK ";
style = ColorStyle.Pass;
break;
}
WriteLine(style, status + indent + result.Name);
if (result.HasChildren)
foreach (ITestResult childResult in result.Children)
PrintAllResults(childResult, indent + " ");
}
#endif
private void WriteHeader(string text)
{
Writer.WriteLine(ColorStyle.Header, text);
}
private void WriteSubHeader(string text)
{
Writer.WriteLine(ColorStyle.SubHeader, text);
}
private void WriteSectionHeader(string text)
{
Writer.WriteLine(ColorStyle.SectionHeader, text);
}
private void WriteHelpLine(string text)
{
Writer.WriteLine(ColorStyle.Help, text);
}
private string _currentLabel;
private void WriteLabelLine(string label)
{
if (label != _currentLabel)
{
WriteNewLineIfNeeded();
Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label);
_testCreatedOutput = true;
_currentLabel = label;
}
}
private void WriteLabelLineAfterTest(string label, ResultState resultState)
{
WriteNewLineIfNeeded();
string status = string.IsNullOrEmpty(resultState.Label)
? resultState.Status.ToString()
: resultState.Label;
Writer.Write(GetColorForResultStatus(status), status);
Writer.WriteLine(ColorStyle.SectionHeader, " => " + label);
_currentLabel = label;
}
private void WriteNewLineIfNeeded()
{
if (_needsNewLine)
{
Writer.WriteLine();
_needsNewLine = false;
}
}
private void WriteOutput(string text)
{
WriteOutput(ColorStyle.Output, text);
}
private void WriteOutput(ColorStyle color, string text)
{
Writer.Write(color, text);
_testCreatedOutput = true;
_needsNewLine = !text.EndsWith("\n");
}
private static ColorStyle GetColorForResultStatus(string status)
{
switch (status)
{
case "Passed":
return ColorStyle.Pass;
case "Failed":
return ColorStyle.Failure;
case "Error":
case "Invalid":
case "Cancelled":
return ColorStyle.Error;
case "Warning":
case "Ignored":
return ColorStyle.Warning;
default:
return ColorStyle.Output;
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
public class SfbClient
{
public ServerIO io, io2;
JobEntry je;
string pid, pincode;
public string server_version;
System.Globalization.NumberFormatInfo ENU = new System.Globalization.CultureInfo("en-US",false).NumberFormat;
public SfbClient(JobEntry je)
{
this.je = je;
}
public bool ServerVersionIsAtLeast(string version)
{
string[] current = server_version.Split(new char[] { '.' });
string[] needed = version.Split(new char[] { '.' });
if (int.Parse(current[0]) > int.Parse(needed[0]))
return true;
else if (int.Parse(current[0]) == int.Parse(needed[0]) && int.Parse(current[1]) >= int.Parse(needed[1]))
return true;
else return false;
}
public string Connect(string host, int port, FileType ftype)
{
lock (this)
{
string image;
io = new ServerIO();
lock (io)
{
if (io.Connect(host, port) && (image = io.ReadLine()) != null)
{
if (image.Substring(0, 1) == "-")
{
Disconnect();
return image.Substring(5);
}
else
{
string[] s = image.Substring(5).Split();
pid = s[0];
pincode = s[1];
}
}
else return "Connection to the primary server failed.\r\n\r\nHost " + host + "\r\nPort " + port.ToString();
io.WriteLine("VERSION 0.3");
image = io.ReadLine();
if (image.Substring(0, 1) == "+")
{
server_version = image.Substring(5);
io.WriteLine("HOST");
image = io.ReadLine();
if (image.Substring(0, 1) == "+")
{
je.WriteToLog("connected to " + image.Substring(5));
je.SubItems[(int)Display.where].Text = image.Substring(5);
} // else ignore the error
je.WriteToLog("server version " + server_version);
}
else
{
Disconnect();
return image.Substring(5);
}
io.WriteLine(string.Format("CLIENT {0} {1}", Application.ProductName, Houston.HoustonVersion.ToString()));
image = io.ReadLine();
io.WriteLine("USER " + Environment.UserName);
image = io.ReadLine();
if (!SupportedFileType(ftype))
{
Disconnect();
return "The required program is not installed on this server";
}
}
io2 = new ServerIO();
if (io2.Connect(host, port) && (image = io2.ReadLine()) != null)
{
if (image.Substring(0, 1) == "-")
{
Disconnect();
return image.Substring(5);
} //else ignore pid/pin
}
else return "Connection to secondary server failed.\r\n\r\nHost " + host + "\r\nPort " + port.ToString();
io2.WriteLine("VERSION -0.3");
image = io2.ReadLine();
if (image.Substring(0, 1) == "+")
{
}
else
{
Disconnect();
return image.Substring(5);
}
io2.WriteLine("PID " + pid);
io2.ReadLine();
io2.WriteLine("PIN " + pincode);
io2.ReadLine();
return null;
}
}
public bool SupportedFileType(FileType ft)
{
string image;
lock (io)
{
if (ft == FileType.sfbox) io.WriteLine("SUPPORTS sfbox");
else if (ft == FileType.mcrenko) io.WriteLine("SUPPORTS mcrenko");
else if (ft == FileType.mccompile) io.WriteLine("SUPPORTS mccompile");
else if (ft == FileType.ctb) io.WriteLine("SUPPORTS ctb");
else io.WriteLine("SUPPORTS fakeprogram to generate an error");
image = io.ReadLine();
if (image.Substring(0, 1) == "+")
{
return image.Substring(5) == "YES";
}
else return false;
}
}
ArrayList CopyInputFile(string from, string to)
{
string line;
ArrayList inpfiles = new ArrayList();
StreamReader SR = new StreamReader(from, System.Text.Encoding.ASCII);
StreamWriter SW = new StreamWriter(to, false, System.Text.Encoding.ASCII);
string odname = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(new FileInfo(from).DirectoryName);
while ((line = SR.ReadLine()) != null)
{
string[] parts;
parts = line.Split(':');
if (line.StartsWith("//"))
{ //Comment line.
if (parts.Length == 2 && parts[0].Trim() == "//houston" && parts[1].Trim() == "recompile")
{
}
SW.WriteLine(line);
continue;
}
if (parts.Length == 4 && (parts[2].Trim() == "template" || parts[2].Trim() == "initial_guess_input_file"))
{
FileInfo fi = new FileInfo(parts[3].Trim());
if (fi.Exists)
{
SW.WriteLine(parts[0].Trim() + " : " + parts[1].Trim() + " : " + parts[2].Trim() + " : " + fi.Name);
inpfiles.Add(fi);
}
else SW.WriteLine(line);
}
else if (parts.Length == 4 && parts[2].Trim().EndsWith("_range") && parts[3].Trim().StartsWith("<") )
{
FileInfo fi = new FileInfo(parts[3].Trim().Substring(1).Trim());
if (fi.Exists)
{
SW.WriteLine(parts[0].Trim() + " : " + parts[1].Trim() + " : " + parts[2].Trim() + " : <" + fi.Name);
inpfiles.Add(fi);
}
else SW.WriteLine(line);
}
else SW.WriteLine(line);
}
SR.Close(); SW.Close();
Directory.SetCurrentDirectory(odname);
return inpfiles;
}
public string SendFile(FileInfo fi)
{
io.WriteLine("PUT" + " " + fi.Length.ToString() + " " + fi.Name + "");
io.ReadLine(); //Eat the OK
io.SendBinary(fi.FullName);
return fi.Name;
}
public string SendInputFile(string inpfile)
{
ArrayList moreInputFiles;
string tmpfile = Path.GetTempFileName();
FileInfo tmpfileinfo = new FileInfo(tmpfile);
moreInputFiles = CopyInputFile(inpfile, tmpfile);
lock (io)
{
io.locker++;
io.WriteLine("PUT " + tmpfileinfo.Length.ToString());
io.ReadLine(); //Eat the OK
io.SendBinary(tmpfile);
tmpfileinfo.Delete();
if (je.filetype == FileType.sfbox)
{
foreach (FileInfo fi in moreInputFiles) SendFile(fi);
}
io.locker--;
}
return new FileInfo(inpfile).Name;
}
public void Run(FileType what, string fname, JobEntry je, ref string errortext)
{
string image;
lock (io)
{
io.locker++;
switch (what)
{
case FileType.sfbox:
io.WriteLine("RUN " + fname);
break;
case FileType.mcrenko:
io.WriteLine("RUNMC " + fname);
break;
case FileType.mccompile:
io.WriteLine("RUNMCCOMPILE " + fname);
break;
case FileType.ctb:
io.WriteLine("RUNCTB " + fname);
break;
}
image = io.ReadLine();
if (image.Substring(0, 1) == "+")
{
//je.timer.Change(500,2000);
image = io.ReadLine();
while (true)
{
if (image.Length >= 13 && image.Substring(0, 13) == "+OK Finished") break;
else if (image.Length == 12 && image.Substring(0, 12) == "+OK Stopped")
je.SetStatus(Status.waiting);
else if (image.Length == 14 && image.Substring(0, 14) == "+OK Continued")
je.SetStatus(Status.resumed);
else {
//throw new DivideByZeroException("Invalid Division");
try {
je._theTabs.BeginInvoke(je.asyncReadCallback, new Object[] { image + "\r\n" });
}
catch(Exception e) {
errortext = e.Message;
break;
}
}
image = io.ReadLine();
}
//je.timer.Change(0,0);
}
else if (image.Length > 5) errortext = image.Substring(5);
else errortext = "Unknown error whilst running. \r\nUnknown RUN command?";
}
}
public void Download(string dname)
{
string reply;
ArrayList la = new ArrayList();
lock (io2)
{
io2.locker++;
io2.WriteLine("LIST");
reply = io2.ReadLine();
while (reply.Substring(4, 1) == "-")
{
la.Add(reply.Substring(5));
reply = io2.ReadLine();
}
string odname = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(dname);
foreach (string fname in la)
{
string fsize;
io2.WriteLine("GET " + fname);
fsize = io2.ReadLine().Substring(5);
je.WriteToLog("downloading \"" + fname + "\" (" + fsize + " bytes)");
io2.GetBinary(fname, Convert.ToInt64(fsize,ENU));
}
Directory.SetCurrentDirectory(odname);
io2.locker--;
}
}
public void GetStatus()
{
string reply;
lock (io2)
{
io2.locker++;
io2.WriteLine("STAT");
reply = io2.ReadLine();
if (reply.Substring(0, 1) == "+")
{
while (reply.Substring(4, 1) == "-")
{
if (reply.Substring(5, 3) == "CPU")
je.CPU = Convert.ToSingle(reply.Substring(9),ENU);
else if (reply.Substring(5, 3) == "MEM")
je.MEM = Convert.ToInt32(reply.Substring(9),ENU);
reply = io2.ReadLine();
}
}
io2.locker--;
}
}
public void GetFinalStatus()
{
string reply;
lock (io2)
{
io2.locker++;
lock (io)
{
io.locker++;
io.WriteLine("STAT");
reply = io.ReadLine();
if (reply.Substring(0, 1) == "+")
{
while (reply.Substring(4, 1) == "-")
{
if (reply.Substring(5, 3) == "CPU")
je.CPU = Convert.ToSingle(reply.Substring(9),ENU);
else if (reply.Substring(5, 3) == "MEM")
{
if (reply.Substring(9) != "0")
je.MEM = Convert.ToInt32(reply.Substring(9),ENU);
}
reply = io.ReadLine();
}
}
io.locker--;
}
io2.locker--;
}
}
public void Kill()
{
lock (io2)
{
io2.locker++;
io2.WriteLine("STOP");
io2.ReadLine();
io2.locker--;
}
}
public ArrayList GetNews()
{
ArrayList al = new ArrayList();
io.WriteLine("NEWS");
string reply = io.ReadLine();
if (reply.Substring(0, 1) == "+")
{
while (reply.Substring(4, 1) == "-")
{
string msg = reply.Substring(5);
//Check if the msg starts with a [id] tag
if (msg.StartsWith("[") && msg.IndexOf(']') != -1) al.Add(msg);
reply = io.ReadLine();
}
}
return al;
}
public void Disconnect()
{
// First close the sec. server
if (io2 != null)
{
lock (io2)
{
io2.locker++;
io2.WriteLine("QUIT");
io2.ReadLine(); //Eat the OK
io2.Disconnect();
io2.locker--;
}
}
//Then the primary
lock (io)
{
io.locker++;
io.WriteLine("QUIT");
io.ReadLine(); //Eat the OK
io.Disconnect();
io.locker--;
}
}
}
public class ServerIO
{
public int locker = 0;
TcpClient srv;
public StreamReader sr;
StreamWriter sw;
public bool Connect(string host, int port)
{
try
{
NetworkStream stream;
srv = new TcpClient(host, port);
stream = srv.GetStream();
sr = new StreamReader(stream, System.Text.Encoding.Default);
sw = new StreamWriter(stream);
sw.AutoFlush = true;
return true;
}
catch (SocketException)
{
return false;
}
}
public void Disconnect()
{
srv.Close();
}
public void SendBinary(string ifname)
{
char[] buf;
long nleft; int nread;
FileInfo rfile = new FileInfo(ifname);
StreamReader sr = new StreamReader(rfile.OpenRead(), Encoding.ASCII);
nleft = rfile.Length;
while (nleft > 0)
{
buf = new char[4 * 1024];
nread = sr.Read(buf, 0, buf.Length);
sw.Write(buf, 0, nread);
nleft -= nread;
}
sr.Close();
}
public void GetBinary(string path, long nleft)
{
char[] buf; int nread;
FileInfo wfile = new FileInfo(path);
StreamWriter sw = new StreamWriter(wfile.Create(), System.Text.Encoding.Default);
while (nleft > 0)
{
buf = new char[4 * 1024];
nread = sr.Read(buf, 0, buf.Length);
sw.Write(buf, 0, nread);
nleft -= nread;
}
sw.Close();
}
public string ReadLine()
{
return sr.ReadLine();
}
public void WriteLine(string str)
{
sw.WriteLine(str);
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.PXA27x.Drivers
{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.Runtime;
/// <summary>
/// I2C device driver for the PXA271 I2C hardware.
/// </summary>
public abstract class I2C
{
#region Constructor/Destructor
/// <summary>
/// The current transaction in progress.
/// </summary>
private I2CBus_Transaction m_currentTransaction;
/// <summary>
/// The current sub transaction of the <see cref="m_currentTransaction"/>
/// in progress.
/// </summary>
private I2CBus_TransactionUnit m_currentTransactionUnit;
private const byte c_DirectionWrite = 0x00;
private const byte c_DirectionRead = 0x01;
/// <summary>
/// The serial data line (SDA) of the I2C port.
/// </summary>
private GPIO.Port m_sdaPort;
/// <summary>
/// The serial clock line (SCL) of the I2C port.
/// </summary>
private GPIO.Port m_sclPort;
/// <summary>
/// Initialized the I2C driver.
/// </summary>
/// <remarks>
/// This function configures the slave mode address
/// of the I2C device to 0x01, i.e., clients are not
/// able to talk to devices configured for this address.
/// </remarks>
public void Initialize()
{
//no active action
m_currentTransaction = null;
m_currentTransactionUnit = null;
//configure SCL
m_sclPort = new GPIO.Port(PXA27x.I2C.PIN_I2C_SCL, false);
GPIO.Instance.EnableAsInputAlternateFunction(m_sclPort, 1);
//configure SDA
m_sdaPort = new GPIO.Port(PXA27x.I2C.PIN_I2C_SDA, false);
GPIO.Instance.EnableAsInputAlternateFunction(m_sdaPort, 1);
//configure the priority of the interrupt source in the
//InterruptController Hardware
//note: this is not the driver used to register
// the interrupt handler with!
PXA27x.InterruptController.Instance.SetPriority(PXA27x.InterruptController.IRQ_INDEX_I2C, 0);
//enable and register interrupt for the I2C controller
m_i2cInterruptHandler = InterruptController.Handler.Create(PXA27x.InterruptController.IRQ_INDEX_I2C,
InterruptPriority.Normal,
InterruptSettings.RisingEdge /*| InterruptSettings.Fast*/,
new InterruptController.Callback(this.ProcessI2CInterrupt));
InterruptController.Instance.RegisterAndEnable(m_i2cInterruptHandler);
//enable clock to I2C unit
//note: no access to the I2C registers
// before setting this bit
ClockManager.Instance.CKEN.EnI2C = true;
//setup our slave address - only used for slave mode
PXA27x.I2C.Instance.ISAR = 0x1; //our default address
}
#endregion
#region Public API
/// <summary>
/// Executes a transaction on the I2C bus.
/// </summary>
/// <param name="transaction">The action to execute on
/// the I2C bus.</param>
public void StartTransactionAsMaster(I2CBus_Transaction transaction)
{
if (null == transaction)
throw new ArgumentNullException("transaction");
//reset the state of this transaction
transaction.ResetTransaction();
//setup current action and action unit
//fail if there is a transaction going on at the moment
if (null != Interlocked.CompareExchange<I2CBus_Transaction>(ref this.m_currentTransaction, transaction, null))
throw new InvalidOperationException("m_currentTransaction != null");
//get the first transaction unit
m_currentTransactionUnit = transaction.Pop();
//setup default control field for new transfer
PXA27x.I2C.ICR_Bitfield control = new PXA27x.I2C.ICR_Bitfield
{
//configure interrupts
DRFIE = true, //enable Data Buffer Register (IDBR) receive interrupt
ITEIE = true, //enable IDBR transit empty interrupt
BEIE = true, //enable Bus error interrupt
GCD = true, //disable General call
//setup unit as master
IUE = true, //enable I2C unit
SCLE = true, //enable driving the SCL line
//send first byte indication
START = true, //send start condition
TB = true, //Transfer Byte
};
//setup I2C address
uint address = (uint)(0xFE & (transaction.Address << 1));
//setup the direction bit
address |= m_currentTransactionUnit.IsReadTransaction() ? I2C.c_DirectionRead : I2C.c_DirectionWrite;
//the peer address is the first byte to send
PXA27x.I2C.Instance.IDBR = address;
//Use high bit rate if requested
control.FM = (transaction.ClockRate >= 400);
//Initiate the send operation
PXA27x.I2C.Instance.ICR = control;
}
#endregion
#region Private API
/// <summary>
/// The handler for all interrupts generated by the I2C device.
/// </summary>
private InterruptController.Handler m_i2cInterruptHandler;
/// <summary>
/// Ends any active transaction started as
/// a I2C master device.
/// </summary>
public void StopTransactionAsMaster()
{
//unset all flags that depend on the transaction flow
PXA27x.I2C.Instance.ICR.MA = true; //signal master abort command
m_currentTransaction = null;
m_currentTransactionUnit = null;
}
/// <summary>
/// Processes interrupts generated by the I2C
/// device.
/// </summary>
/// <param name="handler">The handler that was registered with the
/// interrupt controller for the interrupt.</param>
private void ProcessI2CInterrupt(InterruptController.Handler handler)
{
//read control and status
PXA27x.I2C.ISR_Bitfield status = PXA27x.I2C.Instance.ISR;
if (status.ITE) //If Transmit Buffer Empty interrupt
{
OnTransmitBufferEmpty();
}
else if (status.IRF) //If Receive Buffer Full interrupt
{
OnReceiveBufferFull();
}
else if (status.BED || status.ALD) //If there was a bus error or arbitration lost indication
{
//save the data in case we call "StopTransactionAsMaster" later on
//which will clear the variable
I2CBus_Transaction transaction = m_currentTransaction;
//Shut down I2C interrupts, stop driving bus
PXA27x.I2C.Instance.ICR.IUE = false;
StopTransactionAsMaster();
//Problem talking to slave - we're done
transaction.Signal(I2CBus_Transaction.CompletionStatus.Aborted);
}
}
/// <summary>
/// Called from the interrupt handler when the data register
/// is full and data needs to be saved locally for later processing.
/// </summary>
private void OnReceiveBufferFull()
{
PXA27x.I2C i2c = PXA27x.I2C.Instance;
//save the data in case we call "StopTransactionAsMaster" later on
//which will clear the variables
I2CBus_Transaction transaction = m_currentTransaction;
I2CBus_TransactionUnit transactionUnit = m_currentTransactionUnit;
//clear interrupt flag
i2c.ISR.IRF = true;
//Read receive buffer data
if (!transactionUnit.IsTransferComplete)
{
byte data = (byte)i2c.IDBR;
transactionUnit.Push(data);
}
//If last byte was just received
if (transactionUnit.IsTransferComplete)
{
//Tidy up the control register
i2c.ICR.STOP = i2c.ICR.ACKNAK = false;
//Finish up the transaction
if (!transaction.IsProcessingLastUnit)
{
//If more to transaction
StartTransactionAsMaster(transaction /*, true */);
}
else
{
StopTransactionAsMaster();
//signal the succesfull complection
transaction.Signal(I2CBus_Transaction.CompletionStatus.Completed);
//Shut down I2C master
i2c.ICR.IUE = false;
}
}
else if (transactionUnit.IsLastByte) //If exactly 1 byte left to receive
{
PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR;
//Initiate next byte read from slave
ctrl.START = false;
ctrl.STOP = ctrl.ALDIE = ctrl.ACKNAK = ctrl.TB = true;
i2c.ICR = ctrl;
}
else //If more than one byte left to receive
{
PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR;
//Initiate next byte read from slave
ctrl.START = ctrl.STOP = ctrl.ACKNAK = false;
ctrl.ALDIE = ctrl.TB = true;
i2c.ICR = ctrl;
}
}
/// <summary>
/// Called from the interrupt handler when the data register
/// is empty and new data needs to be send to the client device.
/// </summary>
private void OnTransmitBufferEmpty()
{
//save status and configuration
PXA27x.I2C i2c = PXA27x.I2C.Instance;
PXA27x.I2C.ISR_Bitfield status = i2c.ISR;
PXA27x.I2C.ICR_Bitfield ctrl = i2c.ICR;
//save the data in case we call "StopTransactionAsMaster" later on
//which will clear the variables
I2CBus_Transaction transaction = m_currentTransaction;
I2CBus_TransactionUnit transactionUnit = m_currentTransactionUnit;
//clear transmit empty indication flag
//(writing "true" will clear the flag)
i2c.ISR.ITE = true;// PXA27x.I2C.I2C.ISR__ITE;
//If arbitration loss detected, clear that, too
//(writing "true" will clear the flag)
if (status.ALD)
{
i2c.ISR.ALD = true;// = PXA27x.I2C.I2C.ISR__ALD;
}
//If we just finished sending an address in Read mode
if (status.RWM)
{
//If we are expecting only one byte
if (transactionUnit.IsLastByte)
{
//Must send stop and NAK after receiving last byte
ctrl.START = false;
//Initiate read from slave
ctrl.STOP = ctrl.ALDIE = ctrl.ACKNAK = ctrl.TB = true;
}
else //If we are expecting more than one byte
{
//Do not send a stop and ACK the next received byte
ctrl.START = ctrl.STOP = ctrl.ACKNAK = false;
//Initiate read from slave
ctrl.ALDIE = ctrl.TB = true;
}
//Initiate the read operation
i2c.ICR = ctrl;
}
else //If we have just finished sending address or data in Write mode
{
//if the data transfer is complete
if (transactionUnit.IsTransferComplete)
{
//Clear the stop bit
i2c.ICR.STOP = false;
if (transaction.IsProcessingLastUnit)
{
StopTransactionAsMaster();
//signal the succesfull complection
transaction.Signal(I2CBus_Transaction.CompletionStatus.Completed);
//Shut down I2C port master
i2c.ICR.IUE = false;
}
else
{
StartTransactionAsMaster(transaction /*, true */ );
}
}
else if (status.BED) //if there has been a bus error detected
{
//Clear the bus error
i2c.ISR.BED = true;
//and abort the transaction
StopTransactionAsMaster();
//signal the abortion
transaction.Signal(I2CBus_Transaction.CompletionStatus.Aborted);
//Shut down I2C master
i2c.ICR.IUE = false;
}
else //in the middle of the send operation
{
//If sending the last byte we must signal
//the stop condition after the byte was sent
if (transactionUnit.IsLastByte)
{
ctrl.START = false;
ctrl.STOP = true;
}
else
{
ctrl.START = false;
ctrl.STOP = false;
}
//Set up start/stop and arbitration loss detect
//after the operation has started
ctrl.ALDIE = true;
i2c.ICR = ctrl;
//Set up next byte to transmit
//Get data ready to send and put it
//into the send register
i2c.IDBR = transactionUnit.Pop();
//Initiate the transmission
i2c.ICR.TB = true;
}
}
}
#endregion
#region Singleton API
#if TESTMODE_DESKTOP
private static I2C s_instance;
/// <summary>
/// Retrieves the I2C driver singleton.
/// </summary>
public static I2C Instance
{
get
{
if (null != s_instance) return s_instance;
s_instance = new I2C();
s_instance.Initialize();
return s_instance;
}
}
#else
/// <summary>
/// Retrieves the I2C driver singleton.
/// </summary>
extern public static I2C Instance
{
[MethodImpl(MethodImplOptions.InternalCall)]
[SingletonFactory]
get;
}
#endif
#endregion
}
/// <summary>
/// Base class for an I2C Transaction.
/// </summary>
public class I2CBus_TransactionUnit
{
#region Constructor/Destructor
/// <summary>
/// Initializes an I2C transaction
/// </summary>
/// <param name="isReadTransaction">True, if the data is read from the device. False if
/// data it to be written to the device.</param>
/// <param name="buffer">The buffer to fill from (when reading) the device
/// or transfer to (when writing) the device.</param>
protected I2CBus_TransactionUnit(bool isReadTransaction, byte[] buffer)
{
if (null == buffer)
throw new ArgumentNullException("buffer");
this.Buffer = buffer;
this.m_isReadTransactionUnit = isReadTransaction;
//this.m_queueIndex = 0;
}
#endregion
#region Public API
/// <summary>
/// The current index into the buffer
/// used for Push/Pop operations.
/// </summary>
private int m_queueIndex;
/// <summary>
/// reset the internal state of this transaction
/// </summary>
internal void ResetTransactionUnit()
{
this.m_queueIndex = 0;
}
/// <summary>
/// The buffer to fill from (when reading) the device
/// or transfer to (when writing) the device.
/// </summary>
public readonly byte[] Buffer;
#endregion
#region Internal API
/// <summary>
/// Indicates the direction of the transaction
/// </summary>
private bool m_isReadTransactionUnit;
/// <summary>
/// Indicates the direction of the transaction
/// </summary>
/// <returns>
/// If true, the transaction is a read transaction, i.e.,
/// data is read from the device and written to the buffer.
/// If false, this is a write transaction, i.e.,
/// data is read from the buffer and written to the device.
/// </returns>
internal bool IsReadTransaction()
{
return m_isReadTransactionUnit;
}
/// <summary>
/// Returns the next byte to send to the device
/// and adjusts the internal pointer to the next byte.
/// </summary>
/// <remarks>
/// note: An exception will be raised if the transaction
/// is not a write transaction.
/// </remarks>
/// <returns>The next byte to send to the device.</returns>
internal byte Pop()
{
if (m_isReadTransactionUnit)
throw new ArgumentOutOfRangeException();
byte ret = this.Buffer[m_queueIndex];
m_queueIndex++;
return ret;
}
/// <summary>
/// Pushes the data read from the device to the internal
/// buffer and adjusts the internal pointer to the next byte.
/// </summary>
/// <remarks>
/// note: An exception will be raised if the transaction
/// is not a read transaction.
/// </remarks>
/// <param name="val">The data read from the device to be
/// pushed to the buffer.</param>
internal void Push(byte val)
{
if (!m_isReadTransactionUnit)
throw new ArgumentOutOfRangeException("val");
this.Buffer[m_queueIndex] = val;
m_queueIndex++;
}
/// <summary>
/// Indicates if the transaction is complete,
/// i.e. all data has been sent/received.
/// </summary>
internal bool IsTransferComplete
{
get
{
return m_queueIndex == this.Buffer.Length;
}
}
/// <summary>
/// Indicates if the last byte of the transaction
/// is to be processed.
/// </summary>
/// <remarks>
/// note: the last byte is special in that the I2C
/// bus requires special signalling for the
/// last byte.
/// </remarks>
internal bool IsLastByte
{
get
{
return m_queueIndex == this.Buffer.Length - 1;
}
}
#endregion
}
/// <summary>
/// Represents a comlex I2C transaction consisting
/// of several <see cref="I2C_HAL_TransactionUnit"/> elements.
/// </summary>
public class I2CBus_Transaction : IDisposable
{
#region Constructor/Destructor
/// <summary>
/// Initializes a complex transaction from a set of user transactions for
/// a given peer address and clock rate.
/// </summary>
/// <param name="address">The address of the peer to talk to.</param>
/// <param name="clockRate">The clock rate (either 100 or 400khz) to use as transmission speed.</param>
/// <param name="units">The sequence of user transaction to run against the given peer.</param>
public I2CBus_Transaction(ushort address, int clockRate, I2CBus_TransactionUnit[] units)
{
m_completed = new ManualResetEvent(false);
m_status = CompletionStatus.Aborted;
m_address = address;
m_clockRate = clockRate;
m_transactionUnits = units;
//m_bytesTransacted = 0;
//m_current = 0;
}
#endregion
#region Public API
/// <summary>
/// Waits for the transaction to complete for a specified amount of time.
/// </summary>
/// <param name="milliseconds">The maximum time to wait for the transaction to complete.</param>
/// <returns>True, if the transaction is complete, false, if the transaction is still
/// running.
/// note: having a transaction completed does not means that it was successfull.
/// Look at <see cref="BytesTransacted"/> to see how many bytes have been successfully
/// transacted.</returns>
/// <seealso cref="BytesTransacted"/>
public bool WaitForCompletion(int milliseconds)
{
return m_completed.WaitOne(milliseconds, false);
}
/// <summary>
/// The number of bytes successfully sent/received.
/// </summary>
public int BytesTransacted
{
get
{
return m_bytesTransacted;
}
internal set
{
m_bytesTransacted = value;
}
}
/// <summary>
/// The address of the peer.
/// </summary>
public ushort Address
{
get
{
return m_address;
}
}
/// <summary>
/// The clockrate at which to talk to the client.
/// </summary>
public int ClockRate
{
get
{
return m_clockRate;
}
}
/// <summary>
/// If true, this is the last user transaction.
/// </summary>
public bool IsProcessingLastUnit
{
get
{
return (null == m_transactionUnits || m_current >= m_transactionUnits.Length);
}
}
/// <summary>
/// The completion status of this transaction.
/// </summary>
public CompletionStatus TransactionState
{
get { return m_status; }
}
#endregion
/// <summary>
/// resets the state of this transaction
/// </summary>
internal void ResetTransaction() {
m_completed.Reset();
m_status = CompletionStatus.Aborted;
m_bytesTransacted = 0;
m_current = 0;
foreach (I2CBus_TransactionUnit unit in m_transactionUnits)
{
unit.ResetTransactionUnit();
}
}
#region Internal API
private ManualResetEvent m_completed;
private I2CBus_TransactionUnit[] m_transactionUnits;
private int m_bytesTransacted;
private ushort m_address;
private int m_clockRate;
private CompletionStatus m_status;
private int m_current;
/// <summary>
/// Pops the next user transaction from the transaction queue
/// and adjusts the internal pointer to the next transaction.
/// </summary>
/// <returns>The next user transaction to execute.</returns>
internal I2CBus_TransactionUnit Pop()
{
if (m_current > 0)
BytesTransacted += m_transactionUnits[m_current - 1].Buffer.Length;
return m_transactionUnits[m_current++];
}
/// <summary>
/// Signal handler called by the I2C state machine to signal the end of the transactions.
/// </summary>
/// <param name="status">The result status of the user transactions.</param>
internal void Signal(CompletionStatus status)
{
if (status == CompletionStatus.Completed)
{
m_bytesTransacted = 0;
for (int i = 0; i < m_transactionUnits.Length; i++)
{
m_bytesTransacted += m_transactionUnits[i].Buffer.Length;
}
}
m_status = status;
m_completed.Set();
}
#endregion
#region Nested data types
/// <summary>
/// The completion status of the entire
/// transaction.
/// </summary>
public enum CompletionStatus
{
/// <summary>
/// The transaction was aborted at
/// some point. Some of the user transactions
/// have possibly been completed, some possibly not.
/// </summary>
Aborted,
/// <summary>
/// All user transaction that were part of the combined
/// transaction completed successfully.
/// </summary>
Completed
};
#endregion
#region IDisposable Members
/// <summary>
/// Disposes all resources held by the Transaction
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes all resources held by the Transaction
/// </summary>
/// <param name="fDisposing">True, if called through Dispose(). False otherwise.</param>
protected virtual void Dispose(bool fDisposing)
{
if (m_completed != null)
m_completed.Close();
m_completed = null;
}
#endregion
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations.Infrastructure;
using MVC6BearerToken.DAL;
namespace MVC6BearerTokenMigrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
public override void BuildModel(ModelBuilder builder)
{
builder
.Annotation("ProductVersion", "7.0.0-beta6-13815")
.Annotation("SqlServer:ValueGenerationStrategy", "IdentityColumn");
builder.Entity("MVC6BearerToken.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Email")
.Annotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.Annotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.Annotation("MaxLength", 256);
b.Key("Id");
b.Index("NormalizedEmail")
.Annotation("Relational:Name", "EmailIndex");
b.Index("NormalizedUserName")
.Annotation("Relational:Name", "UserNameIndex");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("MVC6BearerToken.Models.Client", b =>
{
b.Property<string>("Id");
b.Property<bool>("Active");
b.Property<string>("AllowedOrigin")
.Annotation("MaxLength", 100);
b.Property<int>("ApplicationType");
b.Property<string>("Name")
.Required()
.Annotation("MaxLength", 100);
b.Property<int>("RefreshTokenLifeTime");
b.Property<string>("Secret")
.Required();
b.Key("Id");
});
builder.Entity("MVC6BearerToken.Models.RefreshToken", b =>
{
b.Property<string>("Id");
b.Property<string>("ClientId")
.Required()
.Annotation("MaxLength", 50);
b.Property<DateTime>("ExpiresUtc");
b.Property<DateTime>("IssuedUtc");
b.Property<string>("Subject")
.Required()
.Annotation("MaxLength", 50);
b.Key("Id");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken();
b.Property<string>("Name")
.Annotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.Annotation("MaxLength", 256);
b.Key("Id");
b.Index("NormalizedName")
.Annotation("Relational:Name", "RoleNameIndex");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId");
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId");
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("MVC6BearerToken.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the ModifyCluster operation.
/// Modifies the settings for a cluster. For example, you can add another security or
/// parameter group, update the preferred maintenance window, or change the master user
/// password. Resetting a cluster password or modifying the security groups associated
/// with a cluster do not need a reboot. However, modifying a parameter group requires
/// a reboot for parameters to take effect. For more information about managing clusters,
/// go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html">Amazon
/// Redshift Clusters</a> in the <i>Amazon Redshift Cluster Management Guide</i> .
///
///
/// <para>
/// You can also change node type and the number of nodes to scale up or down the cluster.
/// When resizing a cluster, you must specify both the number of nodes and the node type
/// even if one of the parameters does not change.
/// </para>
/// </summary>
public partial class ModifyClusterRequest : AmazonRedshiftRequest
{
private bool? _allowVersionUpgrade;
private int? _automatedSnapshotRetentionPeriod;
private string _clusterIdentifier;
private string _clusterParameterGroupName;
private List<string> _clusterSecurityGroups = new List<string>();
private string _clusterType;
private string _clusterVersion;
private string _hsmClientCertificateIdentifier;
private string _hsmConfigurationIdentifier;
private string _masterUserPassword;
private string _newClusterIdentifier;
private string _nodeType;
private int? _numberOfNodes;
private string _preferredMaintenanceWindow;
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Gets and sets the property AllowVersionUpgrade.
/// <para>
/// If <code>true</code>, major version upgrades will be applied automatically to the
/// cluster during the maintenance window.
/// </para>
///
/// <para>
/// Default: <code>false</code>
/// </para>
/// </summary>
public bool AllowVersionUpgrade
{
get { return this._allowVersionUpgrade.GetValueOrDefault(); }
set { this._allowVersionUpgrade = value; }
}
// Check to see if AllowVersionUpgrade property is set
internal bool IsSetAllowVersionUpgrade()
{
return this._allowVersionUpgrade.HasValue;
}
/// <summary>
/// Gets and sets the property AutomatedSnapshotRetentionPeriod.
/// <para>
/// The number of days that automated snapshots are retained. If the value is 0, automated
/// snapshots are disabled. Even if automated snapshots are disabled, you can still create
/// manual snapshots when you want with <a>CreateClusterSnapshot</a>.
/// </para>
///
/// <para>
/// If you decrease the automated snapshot retention period from its current value, existing
/// automated snapshots that fall outside of the new retention period will be immediately
/// deleted.
/// </para>
///
/// <para>
/// Default: Uses existing setting.
/// </para>
///
/// <para>
/// Constraints: Must be a value from 0 to 35.
/// </para>
/// </summary>
public int AutomatedSnapshotRetentionPeriod
{
get { return this._automatedSnapshotRetentionPeriod.GetValueOrDefault(); }
set { this._automatedSnapshotRetentionPeriod = value; }
}
// Check to see if AutomatedSnapshotRetentionPeriod property is set
internal bool IsSetAutomatedSnapshotRetentionPeriod()
{
return this._automatedSnapshotRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property ClusterIdentifier.
/// <para>
/// The unique identifier of the cluster to be modified.
/// </para>
///
/// <para>
/// Example: <code>examplecluster</code>
/// </para>
/// </summary>
public string ClusterIdentifier
{
get { return this._clusterIdentifier; }
set { this._clusterIdentifier = value; }
}
// Check to see if ClusterIdentifier property is set
internal bool IsSetClusterIdentifier()
{
return this._clusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property ClusterParameterGroupName.
/// <para>
/// The name of the cluster parameter group to apply to this cluster. This change is
/// applied only after the cluster is rebooted. To reboot a cluster use <a>RebootCluster</a>.
///
/// </para>
///
/// <para>
/// Default: Uses existing setting.
/// </para>
///
/// <para>
/// Constraints: The cluster parameter group must be in the same parameter group family
/// that matches the cluster version.
/// </para>
/// </summary>
public string ClusterParameterGroupName
{
get { return this._clusterParameterGroupName; }
set { this._clusterParameterGroupName = value; }
}
// Check to see if ClusterParameterGroupName property is set
internal bool IsSetClusterParameterGroupName()
{
return this._clusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property ClusterSecurityGroups.
/// <para>
/// A list of cluster security groups to be authorized on this cluster. This change is
/// asynchronously applied as soon as possible.
/// </para>
///
/// <para>
/// Security groups currently associated with the cluster, and not in the list of groups
/// to apply, will be revoked from the cluster.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be 1 to 255 alphanumeric characters or hyphens</li> <li>First character
/// must be a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li>
/// </ul>
/// </summary>
public List<string> ClusterSecurityGroups
{
get { return this._clusterSecurityGroups; }
set { this._clusterSecurityGroups = value; }
}
// Check to see if ClusterSecurityGroups property is set
internal bool IsSetClusterSecurityGroups()
{
return this._clusterSecurityGroups != null && this._clusterSecurityGroups.Count > 0;
}
/// <summary>
/// Gets and sets the property ClusterType.
/// <para>
/// The new cluster type.
/// </para>
///
/// <para>
/// When you submit your cluster resize request, your existing cluster goes into a read-only
/// mode. After Amazon Redshift provisions a new cluster based on your resize requirements,
/// there will be outage for a period while the old cluster is deleted and your connection
/// is switched to the new cluster. You can use <a>DescribeResize</a> to track the progress
/// of the resize request.
/// </para>
///
/// <para>
/// Valid Values: <code> multi-node | single-node </code>
/// </para>
/// </summary>
public string ClusterType
{
get { return this._clusterType; }
set { this._clusterType = value; }
}
// Check to see if ClusterType property is set
internal bool IsSetClusterType()
{
return this._clusterType != null;
}
/// <summary>
/// Gets and sets the property ClusterVersion.
/// <para>
/// The new version number of the Amazon Redshift engine to upgrade to.
/// </para>
///
/// <para>
/// For major version upgrades, if a non-default cluster parameter group is currently
/// in use, a new cluster parameter group in the cluster parameter group family for the
/// new version must be specified. The new cluster parameter group can be the default
/// for that cluster parameter group family. For more information about parameters and
/// parameter groups, go to <a href="http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-parameter-groups.html">Amazon
/// Redshift Parameter Groups</a> in the <i>Amazon Redshift Cluster Management Guide</i>.
///
/// </para>
///
/// <para>
/// Example: <code>1.0</code>
/// </para>
/// </summary>
public string ClusterVersion
{
get { return this._clusterVersion; }
set { this._clusterVersion = value; }
}
// Check to see if ClusterVersion property is set
internal bool IsSetClusterVersion()
{
return this._clusterVersion != null;
}
/// <summary>
/// Gets and sets the property HsmClientCertificateIdentifier.
/// <para>
/// Specifies the name of the HSM client certificate the Amazon Redshift cluster uses
/// to retrieve the data encryption keys stored in an HSM.
/// </para>
/// </summary>
public string HsmClientCertificateIdentifier
{
get { return this._hsmClientCertificateIdentifier; }
set { this._hsmClientCertificateIdentifier = value; }
}
// Check to see if HsmClientCertificateIdentifier property is set
internal bool IsSetHsmClientCertificateIdentifier()
{
return this._hsmClientCertificateIdentifier != null;
}
/// <summary>
/// Gets and sets the property HsmConfigurationIdentifier.
/// <para>
/// Specifies the name of the HSM configuration that contains the information the Amazon
/// Redshift cluster can use to retrieve and store keys in an HSM.
/// </para>
/// </summary>
public string HsmConfigurationIdentifier
{
get { return this._hsmConfigurationIdentifier; }
set { this._hsmConfigurationIdentifier = value; }
}
// Check to see if HsmConfigurationIdentifier property is set
internal bool IsSetHsmConfigurationIdentifier()
{
return this._hsmConfigurationIdentifier != null;
}
/// <summary>
/// Gets and sets the property MasterUserPassword.
/// <para>
/// The new password for the cluster master user. This change is asynchronously applied
/// as soon as possible. Between the time of the request and the completion of the request,
/// the <code>MasterUserPassword</code> element exists in the <code>PendingModifiedValues</code>
/// element of the operation response. <note> Operations never return the password, so
/// this operation provides a way to regain access to the master user account for a cluster
/// if the password is lost. </note>
/// </para>
///
/// <para>
/// Default: Uses existing setting.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be between 8 and 64 characters in length.</li> <li>Must contain at
/// least one uppercase letter.</li> <li>Must contain at least one lowercase letter.</li>
/// <li>Must contain one number.</li> <li>Can be any printable ASCII character (ASCII
/// code 33 to 126) except ' (single quote), " (double quote), \, /, @, or space.</li>
/// </ul>
/// </summary>
public string MasterUserPassword
{
get { return this._masterUserPassword; }
set { this._masterUserPassword = value; }
}
// Check to see if MasterUserPassword property is set
internal bool IsSetMasterUserPassword()
{
return this._masterUserPassword != null;
}
/// <summary>
/// Gets and sets the property NewClusterIdentifier.
/// <para>
/// The new identifier for the cluster.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens.</li> <li>Alphabetic
/// characters must be lowercase.</li> <li>First character must be a letter.</li> <li>Cannot
/// end with a hyphen or contain two consecutive hyphens.</li> <li>Must be unique for
/// all clusters within an AWS account.</li> </ul>
/// <para>
/// Example: <code>examplecluster</code>
/// </para>
/// </summary>
public string NewClusterIdentifier
{
get { return this._newClusterIdentifier; }
set { this._newClusterIdentifier = value; }
}
// Check to see if NewClusterIdentifier property is set
internal bool IsSetNewClusterIdentifier()
{
return this._newClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property NodeType.
/// <para>
/// The new node type of the cluster. If you specify a new node type, you must also specify
/// the number of nodes parameter.
/// </para>
///
/// <para>
/// When you submit your request to resize a cluster, Amazon Redshift sets access permissions
/// for the cluster to read-only. After Amazon Redshift provisions a new cluster according
/// to your resize requirements, there will be a temporary outage while the old cluster
/// is deleted and your connection is switched to the new cluster. When the new connection
/// is complete, the original access permissions for the cluster are restored. You can
/// use <a>DescribeResize</a> to track the progress of the resize request.
/// </para>
///
/// <para>
/// Valid Values: <code> ds1.xlarge</code> | <code>ds1.8xlarge</code> | <code> ds2.xlarge</code>
/// | <code>ds2.8xlarge</code> | <code>dc1.large</code> | <code>dc1.8xlarge</code>.
/// </para>
/// </summary>
public string NodeType
{
get { return this._nodeType; }
set { this._nodeType = value; }
}
// Check to see if NodeType property is set
internal bool IsSetNodeType()
{
return this._nodeType != null;
}
/// <summary>
/// Gets and sets the property NumberOfNodes.
/// <para>
/// The new number of nodes of the cluster. If you specify a new number of nodes, you
/// must also specify the node type parameter.
/// </para>
///
/// <para>
/// When you submit your request to resize a cluster, Amazon Redshift sets access permissions
/// for the cluster to read-only. After Amazon Redshift provisions a new cluster according
/// to your resize requirements, there will be a temporary outage while the old cluster
/// is deleted and your connection is switched to the new cluster. When the new connection
/// is complete, the original access permissions for the cluster are restored. You can
/// use <a>DescribeResize</a> to track the progress of the resize request.
/// </para>
///
/// <para>
/// Valid Values: Integer greater than <code>0</code>.
/// </para>
/// </summary>
public int NumberOfNodes
{
get { return this._numberOfNodes.GetValueOrDefault(); }
set { this._numberOfNodes = value; }
}
// Check to see if NumberOfNodes property is set
internal bool IsSetNumberOfNodes()
{
return this._numberOfNodes.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// The weekly time range (in UTC) during which system maintenance can occur, if necessary.
/// If system maintenance is necessary during the window, it may result in an outage.
///
/// </para>
///
/// <para>
/// This maintenance window change is made immediately. If the new maintenance window
/// indicates the current time, there must be at least 120 minutes between the current
/// time and end of the window in order to ensure that pending changes are applied.
/// </para>
///
/// <para>
/// Default: Uses existing setting.
/// </para>
///
/// <para>
/// Format: ddd:hh24:mi-ddd:hh24:mi, for example <code>wed:07:30-wed:08:00</code>.
/// </para>
///
/// <para>
/// Valid Days: Mon | Tue | Wed | Thu | Fri | Sat | Sun
/// </para>
///
/// <para>
/// Constraints: Must be at least 30 minutes.
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A list of virtual private cloud (VPC) security groups to be associated with the cluster.
///
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace DirectShowLib
{
#region Declarations
#if ALLOW_UNTESTED_INTERFACES
/// <summary>
/// From VMRPresentationFlags
/// </summary>
[Flags]
public enum VMRPresentationFlags
{
None = 0,
SyncPoint = 0x00000001,
Preroll = 0x00000002,
Discontinuity = 0x00000004,
TimeValid = 0x00000008,
SrcDstRectsValid = 0x00000010
}
/// <summary>
/// From VMRSurfaceAllocationFlags
/// </summary>
[Flags]
public enum VMRSurfaceAllocationFlags
{
None = 0,
PixelFormatValid = 0x01,
ThreeDTarget = 0x02,
AllowSysMem = 0x04,
ForceSysMem = 0x08,
DirectedFlip = 0x10,
DXVATarget = 0x20
}
/// <summary>
/// From VMRPRESENTATIONINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRPresentationInfo
{
public VMRPresentationFlags dwFlags;
public IntPtr lpSurf; //LPDIRECTDRAWSURFACE7
public long rtStart;
public long rtEnd;
public Size szAspectRatio;
public DsRect rcSrc;
public DsRect rcDst;
public int dwTypeSpecificFlags;
public int dwInterlaceFlags;
}
/// <summary>
/// From VMRALLOCATIONINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRAllocationInfo
{
public VMRSurfaceAllocationFlags dwFlags;
// public BitmapInfoHeader lpHdr;
// public DDPixelFormat lpPixFmt;
public IntPtr lpHdr;
public IntPtr lpPixFmt;
public Size szAspectRatio;
public int dwMinBuffers;
public int dwMaxBuffers;
public int dwInterlaceFlags;
public Size szNativeSize;
}
#endif
/// <summary>
/// From VMRDeinterlaceTech
/// </summary>
[Flags]
public enum VMRDeinterlaceTech
{
Unknown = 0x0000,
BOBLineReplicate = 0x0001,
BOBVerticalStretch = 0x0002,
MedianFiltering = 0x0004,
EdgeFiltering = 0x0010,
FieldAdaptive = 0x0020,
PixelAdaptive = 0x0040,
MotionVectorSteered = 0x0080
}
/// <summary>
/// From VMRBITMAP_* defines
/// </summary>
[Flags]
public enum VMRBitmap
{
None = 0,
Disable = 0x00000001,
Hdc = 0x00000002,
EntireDDS = 0x00000004,
SRCColorKey = 0x00000008,
SRCRect = 0x00000010
}
/// <summary>
/// From VMRDeinterlacePrefs
/// </summary>
[Flags]
public enum VMRDeinterlacePrefs
{
None = 0,
NextBest = 0x01,
BOB = 0x02,
Weave = 0x04,
Mask = 0x07
}
/// <summary>
/// From VMRMixerPrefs
/// </summary>
[Flags]
public enum VMRMixerPrefs
{
None = 0,
NoDecimation = 0x00000001,
DecimateOutput = 0x00000002,
ARAdjustXorY = 0x00000004,
DecimationReserved = 0x00000008,
DecimateMask = 0x0000000F,
BiLinearFiltering = 0x00000010,
PointFiltering = 0x00000020,
FilteringMask = 0x000000F0,
RenderTargetRGB = 0x00000100,
RenderTargetYUV = 0x00001000,
RenderTargetYUV420 = 0x00000200,
RenderTargetYUV422 = 0x00000400,
RenderTargetYUV444 = 0x00000800,
RenderTargetReserved = 0x0000E000,
RenderTargetMask = 0x0000FF00,
DynamicSwitchToBOB = 0x00010000,
DynamicDecimateBy2 = 0x00020000,
DynamicReserved = 0x000C0000,
DynamicMask = 0x000F0000
}
/// <summary>
/// From VMRRenderPrefs
/// </summary>
[Flags]
public enum VMRRenderPrefs
{
RestrictToInitialMonitor = 0x00000000,
ForceOffscreen = 0x00000001,
ForceOverlays = 0x00000002,
AllowOverlays = 0x00000000,
AllowOffscreen = 0x00000000,
DoNotRenderColorKeyAndBorder = 0x00000008,
Reserved = 0x00000010,
PreferAGPMemWhenMixing = 0x00000020,
Mask = 0x0000003f,
}
/// <summary>
/// From VMRMode
/// </summary>
[Flags]
public enum VMRMode
{
None = 0,
Windowed = 0x00000001,
Windowless = 0x00000002,
Renderless = 0x00000004,
}
/// <summary>
/// From VMR_ASPECT_RATIO_MODE
/// </summary>
public enum VMRAspectRatioMode
{
None,
LetterBox
}
/// <summary>
/// From VMRALPHABITMAP
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRAlphaBitmap
{
public VMRBitmap dwFlags;
public IntPtr hdc; // HDC
public IntPtr pDDS; //LPDIRECTDRAWSURFACE7
public DsRect rSrc;
public NormalizedRect rDest;
public float fAlpha;
public int clrSrcKey;
}
/// <summary>
/// From VMRDeinterlaceCaps
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRDeinterlaceCaps
{
public int dwSize;
public int dwNumPreviousOutputFrames;
public int dwNumForwardRefSamples;
public int dwNumBackwardRefSamples;
public VMRDeinterlaceTech DeinterlaceTechnology;
}
/// <summary>
/// From VMRFrequency
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRFrequency
{
public int dwNumerator;
public int dwDenominator;
}
/// <summary>
/// From VMRVideoDesc
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack=1)]
public struct VMRVideoDesc
{
public int dwSize;
public int dwSampleWidth;
public int dwSampleHeight;
[MarshalAs(UnmanagedType.Bool)] public bool SingleFieldPerSample;
public int dwFourCC;
public VMRFrequency InputSampleFreq;
public VMRFrequency OutputFrameFreq;
}
/// <summary>
/// From VMRVIDEOSTREAMINFO
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRVideoStreamInfo
{
public IntPtr pddsVideoSurface;
public int dwWidth;
public int dwHeight;
public int dwStrmID;
public float fAlpha;
public DDColorKey ddClrKey;
public NormalizedRect rNormal;
}
/// <summary>
/// From DDCOLORKEY
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct DDColorKey
{
public int dw1;
public int dw2;
}
/// <summary>
/// From VMRMONITORINFO
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
public struct VMRMonitorInfo
{
public VMRGuid guid;
public DsRect rcMonitor;
public IntPtr hMon; // HMONITOR
public int dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string szDevice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=256)] public string szDescription;
public long liDriverVersion;
public int dwVendorId;
public int dwDeviceId;
public int dwSubSysId;
public int dwRevision;
}
/// <summary>
/// From VMRGUID
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct VMRGuid
{
public IntPtr pGUID; // GUID *
public Guid GUID;
}
#endregion
#region Interfaces
#if ALLOW_UNTESTED_INTERFACES
[ComImport,
Guid("CE704FE7-E71E-41fb-BAA2-C4403E1182F5"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRImagePresenter
{
[PreserveSig]
int StartPresenting([In] IntPtr dwUserID);
[PreserveSig]
int StopPresenting([In] IntPtr dwUserID);
[PreserveSig]
int PresentImage(
[In] IntPtr dwUserID,
[In] ref VMRPresentationInfo lpPresInfo
);
}
[ComImport,
Guid("31ce832e-4484-458b-8cca-f4d7e3db0b52"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRSurfaceAllocator
{
[PreserveSig]
int AllocateSurface(
[In] IntPtr dwUserID,
[In] ref VMRAllocationInfo lpAllocInfo,
[Out] out int lpdwActualBuffers,
[In, Out] ref IntPtr lplpSurface // LPDIRECTDRAWSURFACE7
);
[PreserveSig]
int FreeSurface([In] IntPtr dwID);
[PreserveSig]
int PrepareSurface(
[In] IntPtr dwUserID,
[In] IntPtr lplpSurface, // LPDIRECTDRAWSURFACE7
[In] int dwSurfaceFlags
);
[PreserveSig]
int AdviseNotify([In] IVMRSurfaceAllocatorNotify lpIVMRSurfAllocNotify);
}
[ComImport,
Guid("aada05a8-5a4e-4729-af0b-cea27aed51e2"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRSurfaceAllocatorNotify
{
[PreserveSig]
int AdviseSurfaceAllocator(
[In] IntPtr dwUserID,
[In] IVMRSurfaceAllocator lpIVRMSurfaceAllocator
);
[PreserveSig]
int SetDDrawDevice(
[In] IntPtr lpDDrawDevice, // LPDIRECTDRAW7
[In] IntPtr hMonitor // HMONITOR
);
[PreserveSig]
int ChangeDDrawDevice(
[In] IntPtr lpDDrawDevice, // LPDIRECTDRAW7
[In] IntPtr hMonitor // HMONITOR
);
[PreserveSig]
int RestoreDDrawSurfaces();
[PreserveSig]
int NotifyEvent(
[In] int EventCode,
[In] IntPtr Param1,
[In] IntPtr Param2
);
[PreserveSig]
int SetBorderColor([In] int clrBorder);
}
[ComImport,
Guid("a9849bbe-9ec8-4263-b764-62730f0d15d0"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRSurface
{
[PreserveSig]
int IsSurfaceLocked();
[PreserveSig]
int LockSurface([Out] out IntPtr lpSurface); // BYTE**
[PreserveSig]
int UnlockSurface();
[PreserveSig]
int GetSurface([Out, MarshalAs(UnmanagedType.Interface)] out object lplpSurface);
}
[ComImport,
Guid("e6f7ce40-4673-44f1-8f77-5499d68cb4ea"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRImagePresenterExclModeConfig : IVMRImagePresenterConfig
{
#region IVMRImagePresenterConfig Methods
[PreserveSig]
new int SetRenderingPrefs([In] VMRRenderPrefs dwRenderFlags);
[PreserveSig]
new int GetRenderingPrefs([Out] out VMRRenderPrefs dwRenderFlags);
#endregion
[PreserveSig]
int SetXlcModeDDObjAndPrimarySurface(
[In] IntPtr lpDDObj,
[In] IntPtr lpPrimarySurf
);
[PreserveSig]
int GetXlcModeDDObjAndPrimarySurface(
[Out] out IntPtr lpDDObj,
[Out] out IntPtr lpPrimarySurf
);
}
#endif
[ComImport,
Guid("9e5530c5-7034-48b4-bb46-0b8a6efc8e36"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRFilterConfig
{
[PreserveSig]
int SetImageCompositor([In] IVMRImageCompositor lpVMRImgCompositor);
[PreserveSig]
int SetNumberOfStreams([In] int dwMaxStreams);
[PreserveSig]
int GetNumberOfStreams([Out] out int pdwMaxStreams);
[PreserveSig]
int SetRenderingPrefs([In] VMRRenderPrefs dwRenderFlags);
[PreserveSig]
int GetRenderingPrefs([Out] out VMRRenderPrefs pdwRenderFlags);
[PreserveSig]
int SetRenderingMode([In] VMRMode Mode);
[PreserveSig]
int GetRenderingMode([Out] out VMRMode Mode);
}
[ComImport,
Guid("0eb1088c-4dcd-46f0-878f-39dae86a51b7"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRWindowlessControl
{
[PreserveSig]
int GetNativeVideoSize(
[Out] out int lpWidth,
[Out] out int lpHeight,
[Out] out int lpARWidth,
[Out] out int lpARHeight
);
[PreserveSig]
int GetMinIdealVideoSize(
[Out] out int lpWidth,
[Out] out int lpHeight
);
[PreserveSig]
int GetMaxIdealVideoSize(
[Out] out int lpWidth,
[Out] out int lpHeight
);
[PreserveSig]
int SetVideoPosition(
[In] DsRect lpSRCRect,
[In] DsRect lpDSTRect
);
[PreserveSig]
int GetVideoPosition(
[Out] DsRect lpSRCRect,
[Out] DsRect lpDSTRect
);
[PreserveSig]
int GetAspectRatioMode([Out] out VMRAspectRatioMode lpAspectRatioMode);
[PreserveSig]
int SetAspectRatioMode([In] VMRAspectRatioMode AspectRatioMode);
[PreserveSig]
int SetVideoClippingWindow([In] IntPtr hwnd); // HWND
[PreserveSig]
int RepaintVideo(
[In] IntPtr hwnd, // HWND
[In] IntPtr hdc // HDC
);
[PreserveSig]
int DisplayModeChanged();
/// <summary>
/// the caller is responsible for free the returned memory by calling CoTaskMemFree.
/// </summary>
[PreserveSig]
int GetCurrentImage([Out] out IntPtr lpDib); // BYTE**
[PreserveSig]
int SetBorderColor([In] int Clr);
[PreserveSig]
int GetBorderColor([Out] out int lpClr);
[PreserveSig]
int SetColorKey([In] int Clr);
[PreserveSig]
int GetColorKey([Out] out int lpClr);
}
[ComImport,
Guid("ede80b5c-bad6-4623-b537-65586c9f8dfd"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRAspectRatioControl
{
[PreserveSig]
int GetAspectRatioMode([Out] out VMRAspectRatioMode lpdwARMode);
[PreserveSig]
int SetAspectRatioMode([In] VMRAspectRatioMode lpdwARMode);
}
[ComImport,
Guid("bb057577-0db8-4e6a-87a7-1a8c9a505a0f"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRDeinterlaceControl
{
[PreserveSig]
int GetNumberOfDeinterlaceModes(
[In] ref VMRVideoDesc lpVideoDescription,
[In, Out] ref int lpdwNumDeinterlaceModes,
[Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct)] Guid[] lpDeinterlaceModes
);
[PreserveSig]
int GetDeinterlaceModeCaps(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid lpDeinterlaceMode,
[In] ref VMRVideoDesc lpVideoDescription,
[In, Out] ref VMRDeinterlaceCaps lpDeinterlaceCaps
);
[PreserveSig]
int GetDeinterlaceMode(
[In] int dwStreamID,
[Out] out Guid lpDeinterlaceMode
);
[PreserveSig]
int SetDeinterlaceMode(
[In] int dwStreamID,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid lpDeinterlaceMode
);
[PreserveSig]
int GetDeinterlacePrefs([Out] out VMRDeinterlacePrefs lpdwDeinterlacePrefs);
[PreserveSig]
int SetDeinterlacePrefs([In] VMRDeinterlacePrefs lpdwDeinterlacePrefs);
[PreserveSig]
int GetActualDeinterlaceMode(
[In] int dwStreamID,
[Out] out Guid lpDeinterlaceMode
);
}
[ComImport,
Guid("7a4fb5af-479f-4074-bb40-ce6722e43c82"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRImageCompositor
{
[PreserveSig]
int InitCompositionTarget(
[In] IntPtr pD3DDevice,
[In] IntPtr pddsRenderTarget
);
[PreserveSig]
int TermCompositionTarget(
[In] IntPtr pD3DDevice,
[In] IntPtr pddsRenderTarget
);
[PreserveSig]
int SetStreamMediaType(
[In] int dwStrmID,
[In] AMMediaType pmt,
[In, MarshalAs(UnmanagedType.Bool)] bool fTexture
);
[PreserveSig]
int CompositeImage(
[In] IntPtr pD3DDevice,
[In] IntPtr pddsRenderTarget,
[In] AMMediaType pmtRenderTarget,
[In] long rtStart,
[In] long rtEnd,
[In] int dwClrBkGnd,
[In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct, SizeParamIndex=7)] VMRVideoStreamInfo[] pVideoStreamInfo,
[In] int cStreams
);
}
[ComImport,
Guid("9f3a1c85-8555-49ba-935f-be5b5b29d178"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRImagePresenterConfig
{
[PreserveSig]
int SetRenderingPrefs([In] VMRRenderPrefs dwRenderFlags);
[PreserveSig]
int GetRenderingPrefs([Out] out VMRRenderPrefs dwRenderFlags);
}
[ComImport,
Guid("1E673275-0257-40aa-AF20-7C608D4A0428"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRMixerBitmap
{
[PreserveSig]
int SetAlphaBitmap([In] ref VMRAlphaBitmap pBmpParms);
[PreserveSig]
int UpdateAlphaBitmapParameters([In] ref VMRAlphaBitmap pBmpParms);
[PreserveSig]
int GetAlphaBitmapParameters([Out] out VMRAlphaBitmap pBmpParms);
}
[ComImport,
Guid("9cf0b1b6-fbaa-4b7f-88cf-cf1f130a0dce"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRMonitorConfig
{
[PreserveSig]
int SetMonitor([In] ref VMRGuid pGUID);
[PreserveSig]
int GetMonitor([Out] out VMRGuid pGUID);
[PreserveSig]
int SetDefaultMonitor([In] ref VMRGuid pGUID);
[PreserveSig]
int GetDefaultMonitor([Out] out VMRGuid pGUID);
[PreserveSig]
int GetAvailableMonitors(
[Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct)] VMRMonitorInfo[] pInfo,
[In] int dwMaxInfoArraySize,
[Out] out int pdwNumDevices
);
}
[ComImport,
Guid("058d1f11-2a54-4bef-bd54-df706626b727"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRVideoStreamControl
{
[PreserveSig]
int SetColorKey([In] ref DDColorKey lpClrKey);
[PreserveSig]
int GetColorKey([Out] out DDColorKey lpClrKey);
[PreserveSig]
int SetStreamActiveState([In, MarshalAs(UnmanagedType.Bool)] bool fActive);
[PreserveSig]
int GetStreamActiveState([Out, MarshalAs(UnmanagedType.Bool)] out bool fActive);
}
[ComImport,
Guid("1c1a17b0-bed0-415d-974b-dc6696131599"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVMRMixerControl
{
[PreserveSig]
int SetAlpha(
[In] int dwStreamID,
[In] float Alpha
);
[PreserveSig]
int GetAlpha(
[In] int dwStreamID,
[Out] out float Alpha
);
[PreserveSig]
int SetZOrder(
[In] int dwStreamID,
[In] int dwZ
);
[PreserveSig]
int GetZOrder(
[In] int dwStreamID,
[Out] out int dwZ
);
[PreserveSig]
int SetOutputRect(
[In] int dwStreamID,
[In] ref NormalizedRect pRect
);
[PreserveSig]
int GetOutputRect(
[In] int dwStreamID,
[Out] out NormalizedRect pRect
);
[PreserveSig]
int SetBackgroundClr([In] int ClrBkg);
[PreserveSig]
int GetBackgroundClr([Out] out int ClrBkg);
[PreserveSig]
int SetMixingPrefs([In] VMRMixerPrefs dwMixerPrefs);
[PreserveSig]
int GetMixingPrefs([Out] out VMRMixerPrefs dwMixerPrefs);
}
[ComImport,
Guid("aac18c18-e186-46d2-825d-a1f8dc8e395a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVPManager
{
[PreserveSig]
int SetVideoPortIndex([In] int dwVideoPortIndex);
[PreserveSig]
int GetVideoPortIndex([Out] out int dwVideoPortIndex);
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using DotNetMVC.Areas.HelpPage.ModelDescriptions;
using DotNetMVC.Areas.HelpPage.Models;
namespace DotNetMVC.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);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ReportWebSite.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using LamarCodeGeneration;
using Marten.Events;
using Marten.Events.Querying;
using Marten.Exceptions;
using Marten.Internal.Sessions;
using Marten.Internal.Storage;
using Marten.Linq;
using Marten.Linq.Parsing;
using Marten.Linq.QueryHandlers;
using Marten.Schema.Arguments;
using Marten.Storage;
using Marten.Util;
using Remotion.Linq.Clauses;
#nullable enable
namespace Marten.Services.BatchQuerying
{
public class BatchedQuery: IBatchedQuery, IBatchEvents
{
private static readonly MartenQueryParser QueryParser = new MartenQueryParser();
private readonly IList<IBatchQueryItem> _items = new List<IBatchQueryItem>();
private readonly QuerySession _parent;
private readonly IManagedConnection _runner;
public BatchedQuery(IManagedConnection runner, QuerySession parent)
{
_runner = runner;
_parent = parent;
}
public IBatchEvents Events => this;
public Task<T> Load<T>(string id) where T : class
{
return load<T, string>(id);
}
public Task<T> Load<T>(int id) where T : class
{
return load<T, int>(id);
}
public Task<T> Load<T>(long id) where T : class
{
return load<T, long>(id);
}
public Task<T> Load<T>(Guid id) where T : class
{
return load<T, Guid>(id);
}
public IBatchLoadByKeys<TDoc> LoadMany<TDoc>() where TDoc : class
{
return new BatchLoadByKeys<TDoc>(this);
}
public Task<IReadOnlyList<T>> Query<T>(string sql, params object[] parameters) where T : class
{
return AddItem(new UserSuppliedQueryHandler<T>(_parent, sql, parameters));
}
public IBatchedQueryable<T> Query<T>() where T : class
{
return new BatchedQueryable<T>(this, _parent.Query<T>());
}
public async Task Execute(CancellationToken token = default)
{
if (!_items.Any())
return;
var command = _parent.BuildCommand(_items.Select(x => x.Handler));
using (var reader = await _runner.ExecuteReaderAsync(command, token))
{
await _items[0].ReadAsync(reader, _parent, token);
var others = _items.Skip(1).ToArray();
foreach (var item in others)
{
var hasNext = await reader.NextResultAsync(token);
if (!hasNext)
throw new InvalidOperationException("There is no next result to read over.");
await item.ReadAsync(reader, _parent, token);
}
}
}
public void ExecuteSynchronously()
{
if (!_items.Any())
return;
var command = _parent.BuildCommand(_items.Select(x => x.Handler));
using (var reader = _runner.ExecuteReader(command))
{
_items[0].Read(reader, _parent);
foreach (var item in _items.Skip(1))
{
var hasNext = reader.NextResult();
if (!hasNext)
throw new InvalidOperationException("There is no next result to read over.");
item.Read(reader, _parent);
}
}
}
public Task<TResult> Query<TDoc, TResult>(ICompiledQuery<TDoc, TResult> query)
{
var source = _parent.Options.GetCompiledQuerySourceFor(query, _parent);
var handler = (IQueryHandler<TResult>)source.Build(query, _parent);
return AddItem(handler);
}
public Task<IEvent> Load(Guid id)
{
var handler = new SingleEventQueryHandler(id, _parent.Tenant.EventStorage());
return AddItem(handler);
}
public Task<StreamState> FetchStreamState(Guid streamId)
{
var handler = _parent.Tenant.EventStorage()
.QueryForStream(StreamAction.ForReference(streamId, _parent.Tenant));
return AddItem(handler);
}
public Task<IReadOnlyList<IEvent>> FetchStream(Guid streamId, long version = 0, DateTime? timestamp = null)
{
var selector = _parent.Tenant.EventStorage();
var statement = new EventStatement(selector)
{
StreamId = streamId, Version = version, Timestamp = timestamp, TenantId = _parent.Tenant.TenantId
};
IQueryHandler<IReadOnlyList<IEvent>> handler = new ListQueryHandler<IEvent>(statement, selector);
return AddItem(handler);
}
public Task<T> AddItem<T>(IQueryHandler<T> handler)
{
var item = new BatchQueryItem<T>(handler);
_items.Add(item);
return item.Result;
}
private Task<T> load<T, TId>(TId id) where T : class where TId : notnull
{
var storage = _parent.StorageFor<T>();
if (storage is IDocumentStorage<T, TId> s)
{
var handler = new LoadByIdHandler<T, TId>(s, id);
return AddItem(handler);
}
var idType = storage.IdType;
throw new DocumentIdTypeMismatchException(storage, typeof(TId));
}
private Task<TResult> addItem<TDoc, TResult>(IQueryable<TDoc> queryable, ResultOperatorBase op)
{
var handler = queryable.As<MartenLinqQueryable<TDoc>>().BuildHandler<TResult>(op);
return AddItem(handler);
}
public Task<bool> Any<TDoc>(IMartenQueryable<TDoc> queryable)
{
return addItem<TDoc, bool>(queryable, LinqConstants.AnyOperator);
}
public Task<long> Count<TDoc>(IMartenQueryable<TDoc> queryable)
{
return addItem<TDoc, long>(queryable, LinqConstants.LongCountOperator);
}
internal Task<IReadOnlyList<T>> Query<T>(IMartenQueryable<T> queryable)
{
var handler = queryable.As<MartenLinqQueryable<T>>().BuildHandler<IReadOnlyList<T>>();
return AddItem(handler);
}
public Task<T> First<T>(IMartenQueryable<T> queryable)
{
return addItem<T, T>(queryable, LinqConstants.FirstOperator);
}
public Task<T?> FirstOrDefault<T>(IMartenQueryable<T> queryable)
{
return addItem<T, T?>(queryable, LinqConstants.FirstOrDefaultOperator);
}
public Task<T> Single<T>(IMartenQueryable<T> queryable)
{
return addItem<T, T>(queryable, LinqConstants.SingleOperator);
}
public Task<T?> SingleOrDefault<T>(IMartenQueryable<T> queryable)
{
return addItem<T, T?>(queryable, LinqConstants.SingleOrDefaultOperator);
}
public Task<TResult> Min<TResult>(IQueryable<TResult> queryable)
{
return addItem<TResult, TResult>(queryable, LinqConstants.MinOperator);
}
public Task<TResult> Max<TResult>(IQueryable<TResult> queryable)
{
return addItem<TResult, TResult>(queryable, LinqConstants.MaxOperator);
}
public Task<TResult> Sum<TResult>(IQueryable<TResult> queryable)
{
return addItem<TResult, TResult>(queryable, LinqConstants.SumOperator);
}
public Task<double> Average<T>(IQueryable<T> queryable)
{
return addItem<T, double>(queryable, LinqConstants.AverageOperator);
}
public class BatchLoadByKeys<TDoc>: IBatchLoadByKeys<TDoc> where TDoc : class
{
private readonly BatchedQuery _parent;
public BatchLoadByKeys(BatchedQuery parent)
{
_parent = parent;
}
public Task<IReadOnlyList<TDoc>> ById<TKey>(params TKey[] keys)
{
return load(keys);
}
public Task<IReadOnlyList<TDoc>> ByIdList<TKey>(IEnumerable<TKey> keys)
{
return load(keys.ToArray());
}
private Task<IReadOnlyList<TDoc>> load<TKey>(TKey[] keys)
{
var storage = _parent._parent.StorageFor<TDoc>();
return _parent.AddItem(new LoadByIdArrayHandler<TDoc, TKey>(storage, keys));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure
{
public class DynamicPageEndpointMatcherPolicyTest
{
public DynamicPageEndpointMatcherPolicyTest()
{
var actions = new ActionDescriptor[]
{
new PageActionDescriptor()
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["page"] = "/Index",
},
DisplayName = "/Index",
},
new PageActionDescriptor()
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["page"] = "/About",
},
DisplayName = "/About"
},
};
PageEndpoints = new[]
{
new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[0]), "Test1"),
new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[1]), "Test2"),
};
DynamicEndpoint = new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(new object[]
{
new DynamicPageRouteValueTransformerMetadata(typeof(CustomTransformer), State),
new PageEndpointDataSourceIdMetadata(1),
}),
"dynamic");
DataSource = new DefaultEndpointDataSource(PageEndpoints);
SelectorCache = new TestDynamicPageEndpointSelectorCache(DataSource);
var services = new ServiceCollection();
services.AddRouting();
services.AddTransient<CustomTransformer>(s =>
{
var transformer = new CustomTransformer();
transformer.Transform = (c, values, state) => Transform(c, values, state);
transformer.Filter = (c, values, state, endpoints) => Filter(c, values, state, endpoints);
return transformer;
});
Services = services.BuildServiceProvider();
Comparer = Services.GetRequiredService<EndpointMetadataComparer>();
LoadedEndpoints = new[]
{
new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "Test1"),
new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "Test2"),
new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "ReplacedLoaded")
};
var loader = new Mock<PageLoader>();
loader
.Setup(l => l.LoadAsync(It.IsAny<PageActionDescriptor>(), It.IsAny<EndpointMetadataCollection>()))
.Returns((PageActionDescriptor descriptor, EndpointMetadataCollection endpoint) => Task.FromResult(new CompiledPageActionDescriptor
{
Endpoint = descriptor.DisplayName switch
{
"/Index" => LoadedEndpoints[0],
"/About" => LoadedEndpoints[1],
"/ReplacedEndpoint" => LoadedEndpoints[2],
_ => throw new InvalidOperationException($"Invalid endpoint '{descriptor.DisplayName}'.")
}
}));
Loader = loader.Object;
}
private EndpointMetadataComparer Comparer { get; }
private DefaultEndpointDataSource DataSource { get; }
private Endpoint[] PageEndpoints { get; }
private Endpoint DynamicEndpoint { get; }
private Endpoint [] LoadedEndpoints { get; }
private PageLoader Loader { get; }
private DynamicPageEndpointSelectorCache SelectorCache { get; }
private object State { get; }
private IServiceProvider Services { get; }
private Func<HttpContext, RouteValueDictionary, object, ValueTask<RouteValueDictionary>> Transform { get; set; }
private Func<HttpContext, RouteValueDictionary, object, IReadOnlyList<Endpoint>, ValueTask<IReadOnlyList<Endpoint>>> Filter { get; set; } = (_, __, ___, e) => new ValueTask<IReadOnlyList<Endpoint>>(e);
[Fact]
public async Task ApplyAsync_NoMatch()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
candidates.SetValidity(0, false);
Transform = (c, values, state) =>
{
throw new InvalidOperationException();
};
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_HasMatchNoEndpointFound()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary());
};
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Null(candidates[0].Endpoint);
Assert.Null(candidates[0].Values);
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_HasMatchFindsEndpoint_WithoutRouteValues()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
}));
};
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Same(LoadedEndpoints[0], candidates[0].Endpoint);
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("page", kvp.Key);
Assert.Equal("/Index", kvp.Value);
});
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_HasMatchFindsEndpoint_WithRouteValues()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { new RouteValueDictionary(new { slug = "test", }), };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
state
}));
};
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Same(LoadedEndpoints[0], candidates[0].Endpoint);
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("page", kvp.Key);
Assert.Equal("/Index", kvp.Value);
},
kvp =>
{
Assert.Equal("slug", kvp.Key);
Assert.Equal("test", kvp.Value);
},
kvp =>
{
Assert.Equal("state", kvp.Key);
Assert.Same(State, kvp.Value);
});
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_Throws_ForTransformersWithInvalidLifetime()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { new RouteValueDictionary(new { slug = "test", }), };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
state
}));
};
var httpContext = new DefaultHttpContext()
{
RequestServices = new ServiceCollection().AddScoped(sp => new CustomTransformer() { State = "Invalid" }).BuildServiceProvider()
};
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => policy.ApplyAsync(httpContext, candidates));
}
[Fact]
public async Task ApplyAsync_CanDiscardFoundEndpoints()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { new RouteValueDictionary(new { slug = "test", }), };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
state
}));
};
Filter = (c, values, state, endpoints) =>
{
return new ValueTask<IReadOnlyList<Endpoint>>(Array.Empty<Endpoint>());
};
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_CanReplaceFoundEndpoints()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { new RouteValueDictionary(new { slug = "test", }), };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
state
}));
};
Filter = (c, values, state, endpoints) => new ValueTask<IReadOnlyList<Endpoint>>(new[]
{
new Endpoint((ctx) => Task.CompletedTask, new EndpointMetadataCollection(new PageActionDescriptor()
{
DisplayName = "/ReplacedEndpoint",
}), "ReplacedEndpoint")
});
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Equal(1, candidates.Count);
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("page", kvp.Key);
Assert.Equal("/Index", kvp.Value);
},
kvp =>
{
Assert.Equal("slug", kvp.Key);
Assert.Equal("test", kvp.Value);
},
kvp =>
{
Assert.Equal("state", kvp.Key);
Assert.Same(State, kvp.Value);
});
Assert.Equal("ReplacedLoaded", candidates[0].Endpoint.DisplayName);
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_CanExpandTheListOfFoundEndpoints()
{
// Arrange
var policy = new DynamicPageEndpointMatcherPolicy(SelectorCache, Loader, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { new RouteValueDictionary(new { slug = "test", }), };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary(new
{
page = "/Index",
state
}));
};
Filter = (c, values, state, endpoints) => new ValueTask<IReadOnlyList<Endpoint>>(new[]
{
PageEndpoints[0], PageEndpoints[1]
});
var httpContext = new DefaultHttpContext()
{
RequestServices = Services,
};
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Equal(2, candidates.Count);
Assert.True(candidates.IsValidCandidate(0));
Assert.True(candidates.IsValidCandidate(1));
Assert.Same(LoadedEndpoints[0], candidates[0].Endpoint);
Assert.Same(LoadedEndpoints[1], candidates[1].Endpoint);
}
private class TestDynamicPageEndpointSelectorCache : DynamicPageEndpointSelectorCache
{
public TestDynamicPageEndpointSelectorCache(EndpointDataSource dataSource)
{
AddDataSource(dataSource, 1);
}
}
private class CustomTransformer : DynamicRouteValueTransformer
{
public Func<HttpContext, RouteValueDictionary, object, ValueTask<RouteValueDictionary>> Transform { get; set; }
public Func<HttpContext, RouteValueDictionary, object, IReadOnlyList<Endpoint>, ValueTask<IReadOnlyList<Endpoint>>> Filter { get; set; }
public override ValueTask<IReadOnlyList<Endpoint>> FilterAsync(HttpContext httpContext, RouteValueDictionary values, IReadOnlyList<Endpoint> endpoints)
{
return Filter(httpContext, values, State, endpoints);
}
public override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
return Transform(httpContext, values, State);
}
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Text.Utf8;
namespace System.Text
{
public static partial class PrimitiveFormatter
{
static readonly string[] s_dayNames = { "Sun, ", "Mon, ", "Tue, ", "Wed, ", "Thu, ", "Fri, ", "Sat, " };
static readonly string[] s_monthNames = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
static readonly byte[][] s_dayNamesUtf8 = {
new Utf8String("Sun, ").Bytes.ToArray(),
new Utf8String("Mon, ").Bytes.ToArray(),
new Utf8String("Tue, ").Bytes.ToArray(),
new Utf8String("Wed, ").Bytes.ToArray(),
new Utf8String("Thu, ").Bytes.ToArray(),
new Utf8String("Fri, ").Bytes.ToArray(),
new Utf8String("Sat, ").Bytes.ToArray(),
};
static readonly byte[][] s_monthNamesUtf8 = {
new Utf8String("Jan").Bytes.ToArray(),
new Utf8String("Feb").Bytes.ToArray(),
new Utf8String("Mar").Bytes.ToArray(),
new Utf8String("Apr").Bytes.ToArray(),
new Utf8String("May").Bytes.ToArray(),
new Utf8String("Jun").Bytes.ToArray(),
new Utf8String("Jul").Bytes.ToArray(),
new Utf8String("Aug").Bytes.ToArray(),
new Utf8String("Sep").Bytes.ToArray(),
new Utf8String("Oct").Bytes.ToArray(),
new Utf8String("Nov").Bytes.ToArray(),
new Utf8String("Dec").Bytes.ToArray(),
};
static readonly byte[] s_gmtUtf8Bytes = new Utf8String(" GMT").Bytes.ToArray();
static readonly TextFormat D2 = new TextFormat('D', 2);
static readonly TextFormat D4 = new TextFormat('D', 4);
static readonly TextFormat D7 = new TextFormat('D', 7);
static readonly TextFormat G = new TextFormat('G');
static readonly TextFormat t = new TextFormat('t');
const int FractionalTimeScale = 10000000;
public static bool TryFormat(this DateTimeOffset value, Span<byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
{
if (format.IsDefault)
{
format.Symbol = 'G';
}
Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');
switch (format.Symbol)
{
case 'R':
if (encoding.IsInvariantUtf16) // TODO: there are many checks like this one in the code. They need to also verify that the UTF8 branch is invariant.
{
return TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, out bytesWritten, EncodingData.InvariantUtf16);
}
else
{
return TryFormatDateTimeRfc1123(value.UtcDateTime, buffer, out bytesWritten, EncodingData.InvariantUtf8);
}
case 'O':
if (encoding.IsInvariantUtf16)
{
return TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, out bytesWritten, EncodingData.InvariantUtf16);
}
else
{
return TryFormatDateTimeFormatO(value.UtcDateTime, false, buffer, out bytesWritten, EncodingData.InvariantUtf8);
}
case 'G':
return TryFormatDateTimeFormatG(value.DateTime, buffer, out bytesWritten, encoding);
default:
throw new NotImplementedException();
}
}
public static bool TryFormat(this DateTime value, Span<byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
{
if (format.IsDefault)
{
format.Symbol = 'G';
}
Precondition.Require(format.Symbol == 'R' || format.Symbol == 'O' || format.Symbol == 'G');
switch (format.Symbol)
{
case 'R':
var utc = value.ToUniversalTime();
if (encoding.IsInvariantUtf16)
{
return TryFormatDateTimeRfc1123(utc, buffer, out bytesWritten, EncodingData.InvariantUtf16);
}
else
{
return TryFormatDateTimeRfc1123(utc, buffer, out bytesWritten, EncodingData.InvariantUtf8);
}
case 'O':
if (encoding.IsInvariantUtf16)
{
return TryFormatDateTimeFormatO(value, true, buffer, out bytesWritten, EncodingData.InvariantUtf16);
}
else
{
return TryFormatDateTimeFormatO(value, true, buffer, out bytesWritten, EncodingData.InvariantUtf8);
}
case 'G':
return TryFormatDateTimeFormatG(value, buffer, out bytesWritten, encoding);
default:
throw new NotImplementedException();
}
}
static bool TryFormatDateTimeFormatG(DateTime value, Span<byte> buffer, out int bytesWritten, EncodingData encoding)
{
// for now it only works for invariant culture
if(!encoding.IsInvariantUtf16 && !encoding.IsInvariantUtf8)
{
throw new NotImplementedException();
}
bytesWritten = 0;
if (!TryWriteInt32(value.Month, buffer, ref bytesWritten, G, encoding)) { return false; }
if (!TryWriteChar('/', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Day, buffer, ref bytesWritten, G, encoding)) { return false; }
if (!TryWriteChar('/', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Year, buffer, ref bytesWritten, G, encoding)) { return false; }
if (!TryWriteChar(' ', buffer, ref bytesWritten, encoding)) { return false; }
var hour = value.Hour;
if(hour == 0)
{
hour = 12;
}
if(hour > 12)
{
hour = hour - 12;
}
if (!TryWriteInt32(hour, buffer, ref bytesWritten, G, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Minute, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Second, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(' ', buffer, ref bytesWritten, encoding)) { return false; }
if(value.Hour > 11)
{
TryWriteString("PM", buffer, ref bytesWritten, encoding);
}
else
{
TryWriteString("AM", buffer, ref bytesWritten, encoding);
}
return true;
}
static bool TryFormatDateTimeFormatO(DateTimeOffset value, bool isDateTime, Span<byte> buffer, out int bytesWritten, EncodingData encoding)
{
bytesWritten = 0;
if (!TryWriteInt32(value.Year, buffer, ref bytesWritten, D4, encoding)) { return false; }
if (!TryWriteChar('-', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Month, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar('-', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Day, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar('T', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Hour, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Minute, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Second, buffer, ref bytesWritten, D2, encoding)) { return false; }
// add optional fractional second only if needed...
var rounded = new DateTimeOffset(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, TimeSpan.Zero);
var delta = value - rounded;
if (delta.Ticks != 0)
{
if (!TryWriteChar('.', buffer, ref bytesWritten, encoding)) { return false; }
var timeFrac = delta.Ticks * FractionalTimeScale / System.TimeSpan.TicksPerSecond;
if (!TryWriteInt64(timeFrac, buffer, ref bytesWritten, D7, encoding)) { return false; }
}
if (isDateTime)
{
if (!TryWriteChar('Z', buffer, ref bytesWritten, encoding)) { return false; }
}
else
{
if (!TryWriteChar('+', buffer, ref bytesWritten, encoding)) { return false; }
int bytes;
if (!value.Offset.TryFormat(buffer.Slice(bytesWritten), out bytes, t, encoding)) { return false; }
bytesWritten += bytes;
}
return true;
}
static bool TryFormatDateTimeRfc1123(DateTime value, Span<byte> buffer, out int bytesWritten, EncodingData encoding)
{
if (encoding.IsInvariantUtf8)
{
bytesWritten = 0;
if (buffer.Length < 29) {
return false;
}
s_dayNamesUtf8[(int)value.DayOfWeek].CopyTo(buffer);
TryFormat(value.Day, buffer.Slice(5), out bytesWritten, D2, encoding);
buffer[7] = (byte)' ';
var monthBytes = s_monthNamesUtf8[value.Month - 1];
monthBytes.CopyTo(buffer.Slice(8));
buffer[11] = (byte)' ';
TryFormat(value.Year, buffer.Slice(12), out bytesWritten, D4, encoding);
buffer[16] = (byte)' ';
TryFormat(value.Hour, buffer.Slice(17), out bytesWritten, D2, encoding);
buffer[19] = (byte)':';
TryFormat(value.Minute, buffer.Slice(20), out bytesWritten, D2, encoding);
buffer[22] = (byte)':';
TryFormat(value.Second, buffer.Slice(23), out bytesWritten, D2, encoding);
s_gmtUtf8Bytes.CopyTo(buffer.Slice(25));
bytesWritten = 29;
return true;
}
bytesWritten = 0;
if (!TryWriteString(s_dayNames[(int)value.DayOfWeek], buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Day, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(' ', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteString(s_monthNames[value.Month - 1], buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteChar(' ', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Year, buffer, ref bytesWritten, D4, encoding)) { return false; }
if (!TryWriteChar(' ', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Hour, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Minute, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(value.Second, buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteString(" GMT", buffer, ref bytesWritten, encoding)) { return false; }
return true;
}
public static bool TryFormat(this TimeSpan value, Span<byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
{
if (format.IsDefault)
{
format.Symbol = 'c';
}
Precondition.Require(format.Symbol == 'G' || format.Symbol == 't' || format.Symbol == 'c' || format.Symbol == 'g');
if (format.Symbol != 't')
{
return TryFormatTimeSpanG(value, buffer, out bytesWritten, format, encoding);
}
// else it's format 't' (short time used to print time offsets)
return TryFormatTimeSpanT(value, buffer, out bytesWritten, encoding);
}
private static bool TryFormatTimeSpanG(TimeSpan value, Span<byte> buffer, out int bytesWritten, TextFormat format = default(TextFormat), EncodingData encoding = default(EncodingData))
{
bytesWritten = 0;
if (value.Ticks < 0)
{
if (!TryWriteChar('-', buffer, ref bytesWritten, encoding)) { return false; }
}
bool daysWritten = false;
if (value.Days != 0 || format.Symbol == 'G')
{
if (!TryWriteInt32(Abs(value.Days), buffer, ref bytesWritten, default(TextFormat), encoding)) { return false; }
daysWritten = true;
if (format.Symbol == 'c')
{
if (!TryWriteChar('.', buffer, ref bytesWritten, encoding)) { return false; }
}
else
{
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
}
}
var hourFormat = default(TextFormat);
if ((daysWritten || format.Symbol == 'c') && format.Symbol != 'g')
{
hourFormat = D2;
}
if (!TryWriteInt32(Abs(value.Hours), buffer, ref bytesWritten, hourFormat, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(Abs(value.Minutes), buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(Abs(value.Seconds), buffer, ref bytesWritten, D2, encoding)) { return false; }
long remainingTicks;
if (value.Ticks != long.MinValue)
{
remainingTicks = Abs(value.Ticks) % TimeSpan.TicksPerSecond;
}
else
{
remainingTicks = long.MaxValue % TimeSpan.TicksPerSecond;
remainingTicks = (remainingTicks + 1) % TimeSpan.TicksPerSecond;
}
var ticksFormat = D7;
if (remainingTicks != 0)
{
if (!TryWriteChar('.', buffer, ref bytesWritten, encoding)) { return false; }
var fraction = remainingTicks * FractionalTimeScale / TimeSpan.TicksPerSecond;
if (!TryWriteInt64(fraction, buffer, ref bytesWritten, ticksFormat, encoding)) { return false; }
}
return true;
}
private static bool TryFormatTimeSpanT(TimeSpan value, Span<byte> buffer, out int bytesWritten, EncodingData encoding)
{
bytesWritten = 0;
if (value.Ticks < 0)
{
if (!TryWriteChar('-', buffer, ref bytesWritten, encoding)) { return false; }
}
if (!TryWriteInt32(Abs((int)value.TotalHours), buffer, ref bytesWritten, D2, encoding)) { return false; }
if (!TryWriteChar(':', buffer, ref bytesWritten, encoding)) { return false; }
if (!TryWriteInt32(Abs(value.Minutes), buffer, ref bytesWritten, D2, encoding)) { return false; }
return true;
}
// Math.Abs is in System.Runtime.Extensions. I don't want to add a dependency just for Abs.
// Also, this is not a general purpose Abs. It works only for days, months, etc.
static int Abs(int value)
{
if (value < 0) value = -value;
return value;
}
static long Abs(long value)
{
if (value < 0) value = -value;
return value;
}
}
}
| |
using System;
namespace Lucene.Net.Index
{
/*
* 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 IBits = Lucene.Net.Util.IBits;
using BytesRef = Lucene.Net.Util.BytesRef;
/// <summary>
/// This class contains utility methods and constants for <see cref="DocValues"/>
/// </summary>
public sealed class DocValues
{
/* no instantiation */
private DocValues()
{
}
/// <summary>
/// An empty <see cref="BinaryDocValues"/> which returns <see cref="BytesRef.EMPTY_BYTES"/> for every document
/// </summary>
public static readonly BinaryDocValues EMPTY_BINARY = new BinaryDocValuesAnonymousInnerClassHelper();
private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues
{
public BinaryDocValuesAnonymousInnerClassHelper()
{
}
public override void Get(int docID, BytesRef result)
{
result.Bytes = BytesRef.EMPTY_BYTES;
result.Offset = 0;
result.Length = 0;
}
}
/// <summary>
/// An empty <see cref="NumericDocValues"/> which returns zero for every document
/// </summary>
public static readonly NumericDocValues EMPTY_NUMERIC = new NumericDocValuesAnonymousInnerClassHelper();
private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
{
public NumericDocValuesAnonymousInnerClassHelper()
{
}
public override long Get(int docID)
{
return 0;
}
}
/// <summary>
/// An empty <see cref="SortedDocValues"/> which returns <see cref="BytesRef.EMPTY_BYTES"/> for every document
/// </summary>
public static readonly SortedDocValues EMPTY_SORTED = new SortedDocValuesAnonymousInnerClassHelper();
private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
{
public SortedDocValuesAnonymousInnerClassHelper()
{
}
public override int GetOrd(int docID)
{
return -1;
}
public override void LookupOrd(int ord, BytesRef result)
{
result.Bytes = BytesRef.EMPTY_BYTES;
result.Offset = 0;
result.Length = 0;
}
public override int ValueCount => 0;
}
/// <summary>
/// An empty <see cref="SortedDocValues"/> which returns <see cref="SortedSetDocValues.NO_MORE_ORDS"/> for every document
/// </summary>
public static readonly SortedSetDocValues EMPTY_SORTED_SET = new RandomAccessOrdsAnonymousInnerClassHelper();
private class RandomAccessOrdsAnonymousInnerClassHelper : RandomAccessOrds
{
public RandomAccessOrdsAnonymousInnerClassHelper()
{
}
public override long NextOrd()
{
return NO_MORE_ORDS;
}
public override void SetDocument(int docID)
{
}
public override void LookupOrd(long ord, BytesRef result)
{
throw new IndexOutOfRangeException();
}
public override long ValueCount => 0;
public override long OrdAt(int index)
{
throw new IndexOutOfRangeException();
}
public override int Cardinality()
{
return 0;
}
}
/// <summary>
/// Returns a multi-valued view over the provided <see cref="SortedDocValues"/>
/// </summary>
public static SortedSetDocValues Singleton(SortedDocValues dv)
{
return new SingletonSortedSetDocValues(dv);
}
/// <summary>
/// Returns a single-valued view of the <see cref="SortedSetDocValues"/>, if it was previously
/// wrapped with <see cref="Singleton"/>, or <c>null</c>.
/// </summary>
public static SortedDocValues UnwrapSingleton(SortedSetDocValues dv)
{
if (dv is SingletonSortedSetDocValues)
{
return ((SingletonSortedSetDocValues)dv).SortedDocValues;
}
else
{
return null;
}
}
/// <summary>
/// Returns a <see cref="IBits"/> representing all documents from <paramref name="dv"/> that have a value.
/// </summary>
public static IBits DocsWithValue(SortedDocValues dv, int maxDoc)
{
return new BitsAnonymousInnerClassHelper(dv, maxDoc);
}
private class BitsAnonymousInnerClassHelper : IBits
{
private Lucene.Net.Index.SortedDocValues dv;
private int maxDoc;
public BitsAnonymousInnerClassHelper(Lucene.Net.Index.SortedDocValues dv, int maxDoc)
{
this.dv = dv;
this.maxDoc = maxDoc;
}
public virtual bool Get(int index)
{
return dv.GetOrd(index) >= 0;
}
public virtual int Length => maxDoc;
}
/// <summary>
/// Returns a <see cref="IBits"/> representing all documents from <paramref name="dv"/> that have a value.
/// </summary>
public static IBits DocsWithValue(SortedSetDocValues dv, int maxDoc)
{
return new BitsAnonymousInnerClassHelper2(dv, maxDoc);
}
private class BitsAnonymousInnerClassHelper2 : IBits
{
private Lucene.Net.Index.SortedSetDocValues dv;
private int maxDoc;
public BitsAnonymousInnerClassHelper2(Lucene.Net.Index.SortedSetDocValues dv, int maxDoc)
{
this.dv = dv;
this.maxDoc = maxDoc;
}
public virtual bool Get(int index)
{
dv.SetDocument(index);
return dv.NextOrd() != SortedSetDocValues.NO_MORE_ORDS;
}
public virtual int Length => maxDoc;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.UseThrowExpression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.UseThrowExpression;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression
{
public partial class UseThrowExpressionTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace)
{
return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>(
new CSharpUseThrowExpressionDiagnosticAnalyzer(),
new UseThrowExpressionCodeFixProvider());
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithoutBraces()
{
await TestAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestOnIf()
{
await TestAsync(
@"using System;
class C
{
void M(string s)
{
[|if|] (s == null)
throw new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithBraces()
{
await TestAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnAssign()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
_s = [|s|];
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task OnlyInCSharp7AndHigher()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s)) };
_s = s;
}
}", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task WithIntermediaryStatements()
{
await TestAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryWrite()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s = ""something"";
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task NotWithIntermediaryMemberAccess()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
[|throw|] new ArgumentNullException(nameof(s));
};
s.ToString();
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNullCheckOnLeft()
{
await TestAsync(
@"using System;
class C
{
void M(string s)
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M(string s)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestWithLocal()
{
await TestAsync(
@"using System;
class C
{
void M()
{
string s = null;
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}",
@"using System;
class C
{
void M()
{
string s = null;
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestNotOnField()
{
await TestMissingAsync(
@"using System;
class C
{
string s;
void M()
{
if (null == s)
[|throw|] new ArgumentNullException(nameof(s));
_s = s;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task TestAssignBeforeCheck()
{
await TestMissingAsync(
@"using System;
class C
{
void M(string s)
{
_s = s;
if (s == null)
[|throw|] new ArgumentNullException(nameof(s));
}
}");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace NurseReporting.Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.CodeTools;
using System.IO;
using System.Xml.Linq;
using System.Diagnostics.Contracts;
namespace Microsoft.Contracts.VisualStudio
{
[Guid("6962FC39-92C8-4e9b-9E3E-4A52D08D1D83")]
public partial class PropertyPane : UserControl, Microsoft.VisualStudio.CodeTools.IPropertyPane
{
private readonly ProjectProperty[] properties;
public PropertyPane()
{
InitializeComponent();
var version = typeof(PropertyPane).Assembly.GetName().Version;
VersionLabel.Text = version.ToString();
properties = new ProjectProperty[]{
new CheckBoxProperty("CodeContractsEnableRuntimeChecking", EnableRuntimeCheckingBox, false),
new CheckBoxProperty("CodeContractsRuntimeOnlyPublicSurface", OnlyPublicSurfaceContractsBox, false),
new NegatedCheckBoxProperty("CodeContractsRuntimeThrowOnFailure", AssertOnFailureBox, false),
new CheckBoxProperty("CodeContractsRuntimeCallSiteRequires", CallSiteRequiresBox, false),
new CheckBoxProperty("CodeContractsRuntimeSkipQuantifiers", SkipQuantifiersBox, false),
new CheckBoxProperty("CodeContractsRunCodeAnalysis", EnableStaticCheckingBox, false),
new CheckBoxProperty("CodeContractsNonNullObligations", ImplicitNonNullObligationsBox, true),
new CheckBoxProperty("CodeContractsBoundsObligations", ImplicitArrayBoundObligationsBox, true),
new CheckBoxProperty("CodeContractsArithmeticObligations", ImplicitArithmeticObligationsBox, true),
new CheckBoxProperty("CodeContractsEnumObligations", ImplicitEnumWritesBox, true),
#if INCLUDE_UNSAFE_ANALYSIS
// new CheckBoxProperty("CodeContractsPointerObligations", this.ImplicitPointerUseObligationsBox, false),
#endif
new CheckBoxProperty("CodeContractsRedundantAssumptions", redundantAssumptionsCheckBox, true),
new CheckBoxProperty("CodeContractsAssertsToContractsCheckBox", AssertsToContractsCheckBox, true),
new CheckBoxProperty("CodeContractsRedundantTests", RedundantTestsCheckBox, true),
new CheckBoxProperty("CodeContractsMissingPublicRequiresAsWarnings", missingPublicRequiresAsWarningsCheckBox, true),
new CheckBoxProperty("CodeContractsMissingPublicEnsuresAsWarnings", checkMissingPublicEnsures, false),
new CheckBoxProperty("CodeContractsInferRequires", InferRequiresCheckBox, true),
new CheckBoxProperty("CodeContractsInferEnsures", InferEnsuresCheckBox, false),
new CheckBoxProperty("CodeContractsInferEnsuresAutoProperties", InferEnsuresAutoPropertiesCheckBox, true),
new CheckBoxProperty("CodeContractsInferObjectInvariants", InferObjectInvariantsCheckBox, false),
new CheckBoxProperty("CodeContractsSuggestAssumptions", SuggestAssumptionsCheckBox, false),
new CheckBoxProperty("CodeContractsSuggestAssumptionsForCallees", SuggestCalleeAssumptionsCheckBox, false),
new CheckBoxProperty("CodeContractsSuggestRequires", SuggestRequiresCheckBox, false),
//new CheckBoxProperty("CodeContractsSuggestEnsures", this.SuggestEnsuresCheckBox, false),
new CheckBoxProperty("CodeContractsNecessaryEnsures", NecessaryEnsuresCheckBox, true),
new CheckBoxProperty("CodeContractsSuggestObjectInvariants", SuggestObjectInvariantsCheckBox, false),
new CheckBoxProperty("CodeContractsSuggestReadonly", SuggestReadonlyCheckBox, true),
new CheckBoxProperty("CodeContractsRunInBackground", RunInBackgroundBox, true),
new CheckBoxProperty("CodeContractsShowSquigglies", ShowSquiggliesBox, true),
new CheckBoxProperty("CodeContractsUseBaseLine", BaseLineBox, false),
new CheckBoxProperty("CodeContractsEmitXMLDocs", EmitContractDocumentationCheckBox, false),
new TextBoxProperty("CodeContractsCustomRewriterAssembly", CustomRewriterMethodsAssemblyTextBox, ""),
new TextBoxProperty("CodeContractsCustomRewriterClass", CustomRewriterMethodsClassTextBox, ""),
new TextBoxProperty("CodeContractsLibPaths", LibPathTextBox, ""),
new TextBoxProperty("CodeContractsExtraRewriteOptions", ExtraRuntimeCheckingOptionsBox, ""),
new TextBoxProperty("CodeContractsExtraAnalysisOptions", ExtraCodeAnalysisOptionsBox, ""),
new TextBoxProperty("CodeContractsSQLServerOption", SQLServerTextBox, ""),
new TextBoxProperty("CodeContractsBaseLineFile", BaseLineTextBox, ""),
new CheckBoxProperty("CodeContractsCacheAnalysisResults", CacheResultsCheckBox, true),
new CheckBoxProperty("CodeContractsSkipAnalysisIfCannotConnectToCache", skipAnalysisIfCannotConnectToCache, false),
new CheckBoxProperty("CodeContractsFailBuildOnWarnings", FailBuildOnWarningsCheckBox, false),
new CheckBoxProperty("CodeContractsBeingOptimisticOnExternal", BeingOptmisticOnExternalCheckBox, true)
};
}
#region Changed properties
private Microsoft.VisualStudio.CodeTools.IPropertyPaneHost host; // = null;
private void PropertiesChanged()
{
if (host != null)
{
host.PropertiesChanged();
}
}
private void EnableDisableRuntimeDependentUI()
{
// Enable/Disable dependent options
CustomRewriterMethodsAssemblyLabel.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
CustomRewriterMethodsClassLabel.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
CustomRewriterMethodsAssemblyTextBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
CustomRewriterMethodsClassTextBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
RuntimeCheckingLevelDropDown.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
OnlyPublicSurfaceContractsBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
AssertOnFailureBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
CallSiteRequiresBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
SkipQuantifiersBox.Enabled = IsChecked(EnableRuntimeCheckingBox.CheckState);
}
private void EnableDisableStaticDependentUI()
{
#if EXCLUDE_STATIC_ANALYSIS
EnableStaticCheckingBox.Visible = false;
RunInBackgroundBox.Visible = false;
ShowSquiggliesBox.Visible = false;
this.ImplicitPointerUseObligationsBox.Visible = false;
ImplicitArrayBoundObligationsBox.Visible = false;
ImplicitArithmeticObligationsBox.Visible = false;
redundantAssumptionsCheckBox.Visible = false;
ImplicitNonNullObligationsBox.Visible = false;
BaseLineBox.Visible = false;
BaseLineTextBox.Visible = false;
WarningLevelTrackBar.Visible = false;
WarningLevelLabel.Visible = false;
StaticCheckingGroup.Text = "Static Checking (not included in this version of CodeContracts. Download the Premium edition.)";
#else
// Enable/Disable dependent options
bool enabled = IsChecked(EnableStaticCheckingBox.CheckState);
RunInBackgroundBox.Enabled = enabled;
ShowSquiggliesBox.Enabled = enabled;
#if INCLUDE_UNSAFE_ANALYSIS
// this.ImplicitPointerUseObligationsBox.Enabled = enabled;
// this.ImplicitPointerUseObligationsBox.Visible = true;
#else
// this.ImplicitPointerUseObligationsBox.Visible = false;
#endif
ImplicitArrayBoundObligationsBox.Enabled = enabled;
ImplicitArithmeticObligationsBox.Enabled = enabled;
redundantAssumptionsCheckBox.Enabled = enabled;
ImplicitNonNullObligationsBox.Enabled = enabled;
ImplicitEnumWritesBox.Enabled = enabled;
BaseLineBox.Enabled = enabled;
BaseLineTextBox.Enabled = enabled && IsChecked(BaseLineBox.CheckState);
CacheResultsCheckBox.Enabled = enabled;
FailBuildOnWarningsCheckBox.Enabled = enabled;
WarningLevelTrackBar.Enabled = enabled;
InferEnsuresCheckBox.Enabled = enabled;
InferEnsuresAutoPropertiesCheckBox.Enabled = enabled;
InferRequiresCheckBox.Enabled = enabled;
InferObjectInvariantsCheckBox.Enabled = enabled;
SuggestAssumptionsCheckBox.Enabled = enabled;
//this.SuggestEnsuresCheckBox.Enabled = enabled;
SuggestRequiresCheckBox.Enabled = enabled;
SuggestObjectInvariantsCheckBox.Enabled = enabled;
SuggestReadonlyCheckBox.Enabled = enabled;
// The labels for the warning level
WarningLevelLabel.Enabled = enabled;
WarningLowLabel.Enabled = enabled;
WarningFullLabel.Enabled = enabled;
SQLServerTextBox.Enabled = enabled;
SQLServerLabel.Enabled = enabled;
missingPublicRequiresAsWarningsCheckBox.Enabled = enabled;
checkMissingPublicEnsures.Enabled = enabled;
BeingOptmisticOnExternalCheckBox.Enabled = enabled;
SuggestCalleeAssumptionsCheckBox.Enabled = enabled;
AssertsToContractsCheckBox.Enabled = enabled;
NecessaryEnsuresCheckBox.Enabled = enabled;
RedundantTestsCheckBox.Enabled = enabled;
#endif
}
private void EnableDisableContractReferenceDependentUI()
{
// Enable/Disable dependent options
bool enabled = String.Compare(ContractReferenceAssemblySelection.SelectedItem as string, "build", true) == 0;
EmitContractDocumentationCheckBox.Enabled = enabled;
}
private void EnableDisableBaseLineUI()
{
// Enable/Disable dependent options
BaseLineTextBox.Enabled = IsChecked(BaseLineBox.CheckState);
BaseLineUpdateButton.Enabled = IsChecked(BaseLineBox.CheckState);
// add default
if (BaseLineTextBox.Enabled && (BaseLineTextBox.Text == null || BaseLineTextBox.Text == ""))
{
BaseLineTextBox.Text = @"..\..\baseline.xml";
}
}
private void EnableDisableBackgroundDependentUI()
{
// Enable/Disable dependent options
FailBuildOnWarningsCheckBox.Enabled = IsUnChecked(RunInBackgroundBox.CheckState) && IsChecked(EnableStaticCheckingBox.CheckState);
}
private void EnableDisableCacheDependendUI()
{
SQLServerTextBox.Enabled = IsChecked(CacheResultsCheckBox.CheckState) && IsChecked(EnableStaticCheckingBox.CheckState);
SQLServerLabel.Enabled = IsChecked(CacheResultsCheckBox.CheckState) && IsChecked(EnableStaticCheckingBox.CheckState);
}
public void SetHost(Microsoft.VisualStudio.CodeTools.IPropertyPaneHost h)
{
host = h;
}
#endregion
#region Attributes
public string Title
{
get { return "Code Contracts"; }
}
public int HelpContext
{
get { return 0; }
}
public string HelpFile
{
get { return ""; }
}
#endregion
#region IPropertyPane Members
[Pure]
private CheckState CheckStateOfBool(bool checkedBool)
{
if (checkedBool) { return CheckState.Checked; }
return CheckState.Unchecked;
}
[Pure]
private bool IsChecked(CheckState checkState)
{
return checkState == CheckState.Checked;
}
[Pure]
private bool IsUnChecked(CheckState checkState)
{
return checkState == CheckState.Unchecked;
}
private const string BuildContractReferenceAssemblyName = "CodeContractsBuildReferenceAssembly";
private const string RuntimeCheckingLevelName = "CodeContractsRuntimeCheckingLevel";
private const string ContractReferenceAssemblyName = "CodeContractsReferenceAssembly";
private const string AssemblyModeName = "CodeContractsAssemblyMode";
private const string WarningLevelName = "CodeContractsAnalysisWarningLevel";
private const string PrecisionLevelName = "CodeContractsAnalysisPrecisionLevel";
/// <summary>
/// Load project file properties and represent them in the UI.
/// IMPORTANT:
/// The defaults must match what the build script expect as defaults!!! This way, not representing a
/// property in the project file is equivalent to it having the default.
/// </summary>
/// <param name="configNames"></param>
/// <param name="storage"></param>
public void LoadProperties(string[] configNames, IPropertyStorage storage)
{
bool propertiesChangedOnLoad = false;
SetGlobalComboBoxState(storage, AssemblyModeDropDown, AssemblyModeName, "0");
foreach (var prop in properties)
{
Contract.Assume(prop != null);
prop.Load(configNames, storage);
}
EnableDisableRuntimeDependentUI();
var runtimeCheckingLevel = SetComboBoxState(configNames, storage, RuntimeCheckingLevelDropDown, RuntimeCheckingLevelName, "Full");
if (runtimeCheckingLevel == "RequiresAlways")
{
// fixup backwards compatible string
RuntimeCheckingLevelDropDown.SelectedItem = "ReleaseRequires";
propertiesChangedOnLoad = true;
}
EnableDisableStaticDependentUI();
EnableDisableBaseLineUI();
EnableDisableBackgroundDependentUI();
EnableDisableCacheDependendUI();
bool anyFound, indeterminate;
string contractReferenceAssemblySelection = storage.GetProperties(false, configNames, ContractReferenceAssemblyName, "(none)", out anyFound, out indeterminate);
if (!indeterminate)
{
if (!anyFound)
{
bool anyFound2, indeterminate2;
// check for legacy
var legacyBuildContractReferenceAssembly = storage.GetProperties(false, configNames, BuildContractReferenceAssemblyName, false, out anyFound2, out indeterminate2);
if (anyFound2 && !indeterminate2)
{
if (legacyBuildContractReferenceAssembly)
{
// TODO remove property
contractReferenceAssemblySelection = "Build";
// make sure properties are changed!!!
propertiesChangedOnLoad = true;
}
else
{
contractReferenceAssemblySelection = "DoNotBuild";
propertiesChangedOnLoad = true;
}
}
}
ContractReferenceAssemblySelection.SelectedItem = contractReferenceAssemblySelection;
}
else
{
ContractReferenceAssemblySelection.SelectedItem = null;
}
// Load the track bar properties
LoadTrackBarProperties(WarningLevelTrackBar, WarningLevelName, configNames, storage);
EnableDisableContractReferenceDependentUI();
if (propertiesChangedOnLoad)
{
this.PropertiesChanged();
SaveProperties(configNames, storage);
}
}
static private void LoadTrackBarProperties(TrackBar trackBar, string name, string[] configNames, IPropertyStorage storage)
{
bool anyFound, indeterminate;
var selection = storage.GetProperties(false, configNames, name, "out", out anyFound, out indeterminate);
int value;
if (!indeterminate && Int32.TryParse(selection, out value)
&& value >= trackBar.Minimum && value <= trackBar.Maximum)
{
trackBar.Value = value;
}
else
{
trackBar.Value = 0; // default: low
}
}
private string SetGlobalComboBoxState(IPropertyStorage storage, ComboBox box, string propertyName, string defaultValue)
{
string result = storage.GetProperty(false, "", propertyName, defaultValue) as string;
int index = 0;
if (result != null)
{
if (!Int32.TryParse(result, out index))
{
index = 0;
}
}
box.SelectedIndex = index;
return result;
}
private string SetComboBoxState(string[] configNames, IPropertyStorage storage, ComboBox box, string propertyName, string defaultValue)
{
string result = storage.GetProperties(false, configNames, propertyName, defaultValue) as string;
box.SelectedItem = result;
return result;
}
public void SaveProperties(string[] configNames, IPropertyStorage storage)
{
Contract.Assume(storage != null);
foreach (var prop in properties)
{
Contract.Assume(prop != null);
prop.Save(configNames, storage);
}
if (AssemblyModeDropDown.SelectedItem != null)
{
storage.SetProperty(false, "", AssemblyModeName, AssemblyModeDropDown.SelectedIndex.ToString());
}
if (RuntimeCheckingLevelDropDown.SelectedItem != null)
{
storage.SetProperties(false, configNames, RuntimeCheckingLevelName, RuntimeCheckingLevelDropDown.SelectedItem.ToString());
}
if (ContractReferenceAssemblySelection.SelectedItem != null)
{
storage.SetProperties(false, configNames, ContractReferenceAssemblyName, ContractReferenceAssemblySelection.SelectedItem.ToString());
}
storage.SetProperties(false, configNames, WarningLevelName, WarningLevelTrackBar.Value.ToString());
}
#endregion
#region Event handlers
private void EnableContractCheckingBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
EnableDisableRuntimeDependentUI();
}
private void EnableStaticCheckingBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
EnableDisableStaticDependentUI();
}
private void LibPathTextBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void PlatformTextBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void CustomRewriterMethodsAssemblyTextBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void CustomRewriterMethodsClassTextBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ImplicitNonNullObligationsBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ImplicitArrayBoundObligationsBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ImplicitPointerUseObligationsBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ExtraCodeAnalysisOptionsBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void BaseLineTextBox_TextChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void BaseLineBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
EnableDisableBaseLineUI();
}
private void runtimeCheckingLevel_SelectedIndexChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void RunInBackgroundBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
EnableDisableBackgroundDependentUI();
}
private void SquiggliesBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ImplicitArithmeticObligationsBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void ImplicitEnumWritesBox_CheckedChanged(object sender, EventArgs e)
{
PropertiesChanged();
}
private void OnlyPublicSurfaceContractsBox_CheckedChanged_1(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void AssertOnFailureBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void CallSiteRequiresBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SkipQuantifiersBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void updateBaselineButton_Click(object sender, EventArgs e)
{
try
{
var baselineName = BaseLineBox.Text;
if (!File.Exists(baselineName)) return;
var diffName = baselineName + ".new";
if (!File.Exists(diffName)) return;
Contract.Assert(!string.IsNullOrEmpty(baselineName));
Contract.Assert(!string.IsNullOrEmpty(diffName));
XElement baseline = XElement.Load(baselineName);
XElement diffs = XElement.Load(diffName);
foreach (var elem in diffs.Elements())
{
baseline.Add(elem);
}
baseline.Save(baselineName);
diffs.RemoveAll();
diffs.Save(diffName);
}
catch { }
}
private void EmitContractDocumentationCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void redundantAssumptionsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void ContractReferenceAssemblySelection_SelectedIndexChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
EnableDisableContractReferenceDependentUI();
}
private void AssemblyModeDropDown_SelectedIndexChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void CacheResultsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
EnableDisableCacheDependendUI();
}
private void WarningLevel_SelectedIndexChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void WarningLevelTrackBar_Scroll(object sender, EventArgs e)
{
this.PropertiesChanged();
WarningLevelToolTip.SetToolTip(WarningLevelTrackBar, WarningLevelToString(WarningLevelTrackBar.Value));
}
#endregion
#region ToolTipHelpers
static private string WarningLevelToString(int value)
{
switch (value)
{
case 0:
return "most relevant warnings";
case 1:
return "relevant warnings";
case 2:
return "more warnings";
case 3:
return "all warnings";
default:
return value.ToString();
}
}
static private string PrecisionLevelToString(int value)
{
switch (value)
{
case 0:
return "fast analysis";
case 1:
return "more precise";
case 2:
return "full power analysis";
default:
return value.ToString();
}
}
#endregion
private void InferRequires_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void InferEnsuresCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SuggestRequiresCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SuggestEnsuresCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void DisjunctivePreconditionsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void InferObjectInvariantsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SuggestObjectInvariantsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SuggestAssumptions_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void docLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://research.microsoft.com/en-us/projects/contracts/userdoc.pdf");
}
private void PropertyPane_Load(object sender, EventArgs e)
{
}
private void SQLServerTextBox_TextChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void FailBuildOnWarningsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void missingPublicRequiresAsWarningsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void help_Link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads");
}
private void VersionLabel_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("http://research.microsoft.com/en-us/projects/contracts/releasenotes.aspx");
}
private void BeingOptmisticOnExternalCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void RedundantTestsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void AssertsToContractsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void NecessaryEnsuresCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void linkUnderstandingTheStaticChecker_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("http://research.microsoft.com/en-us/projects/contracts/cccheck.pdf");
}
private void checkMissingPublicEnsures_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void skipAnalysisIfCannotConnectToCache_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void SuggestCalleeAssumptionsCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
private void InferEnsuresAutoPropertiesCheckBox_CheckedChanged(object sender, EventArgs e)
{
this.PropertiesChanged();
}
}
}
| |
//-----------------------------------------------------------------------------
// Filename: Crypto.cs
//
// Description: Encrypts and decrypts data.
//
// History:
// 16 Jul 2005 Aaron Clauson Created.
// 10 Sep 2009 Aaron Clauson Updated to use RNGCryptoServiceProvider in place of Random.
//
// License:
// Aaron Clauson
//-----------------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Security.Cryptography;
using log4net;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Sys
{
public class Crypto
{
public const int DEFAULT_RANDOM_LENGTH = 10; // Number of digits to return for default random numbers.
public const int AES_KEY_SIZE = 32;
public const int AES_IV_SIZE = 16;
private const string CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static ILog logger = AppState.logger;
private static Random _rng = new Random();
private static RNGCryptoServiceProvider m_randomProvider = new RNGCryptoServiceProvider();
#if !SILVERLIGHT
public static string RSAEncrypt(string xmlKey, string plainText)
{
return Convert.ToBase64String(RSAEncryptRaw(xmlKey, plainText));
}
public static byte[] RSAEncryptRaw(string xmlKey, string plainText)
{
try
{
RSACryptoServiceProvider key = GetRSAProvider(xmlKey);
return key.Encrypt(Encoding.ASCII.GetBytes(plainText), true);
}
catch (Exception excp)
{
logger.Error("Exception RSAEncrypt. " + excp.Message);
throw excp;
}
}
public static string RSADecrypt(string xmlKey, string cypherText)
{
return Encoding.ASCII.GetString(RSADecryptRaw(xmlKey, Convert.FromBase64String((cypherText))));
}
public static byte[] RSADecryptRaw(string xmlKey, byte[] cypher)
{
try
{
RSACryptoServiceProvider key = GetRSAProvider(xmlKey);
return key.Decrypt(cypher, true);
}
catch (Exception excp)
{
logger.Error("Exception RSADecrypt. " + excp.Message);
throw excp;
}
}
public static RSACryptoServiceProvider GetRSAProvider(string xmlKey)
{
CspParameters cspParam = new CspParameters();
cspParam.Flags = CspProviderFlags.UseMachineKeyStore;
RSACryptoServiceProvider key = new RSACryptoServiceProvider(cspParam);
key.FromXmlString(xmlKey);
return key;
}
#endif
public static string SymmetricEncrypt(string key, string iv, string plainText)
{
if (plainText.IsNullOrBlank())
{
throw new ApplicationException("The plain text string cannot be empty in SymmetricEncrypt.");
}
return SymmetricEncrypt(key, iv, Encoding.UTF8.GetBytes(plainText));
}
public static string SymmetricEncrypt(string key, string iv, byte[] plainTextBytes)
{
if (key.IsNullOrBlank())
{
throw new ApplicationException("The key string cannot be empty in SymmetricEncrypt.");
}
else if (iv.IsNullOrBlank())
{
throw new ApplicationException("The initialisation vector cannot be empty in SymmetricEncrypt.");
}
else if (plainTextBytes == null)
{
throw new ApplicationException("The plain text string cannot be empty in SymmetricEncrypt.");
}
AesManaged aes = new AesManaged();
ICryptoTransform encryptor = aes.CreateEncryptor(GetFixedLengthByteArray(key, AES_KEY_SIZE), GetFixedLengthByteArray(iv, AES_IV_SIZE));
MemoryStream resultStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.Close();
return Convert.ToBase64String(resultStream.ToArray());
}
public static string SymmetricDecrypt(string key, string iv, string cipherText)
{
if (cipherText.IsNullOrBlank())
{
throw new ApplicationException("The cipher text string cannot be empty in SymmetricDecrypt.");
}
return SymmetricDecrypt(key, iv, Convert.FromBase64String(cipherText));
}
public static string SymmetricDecrypt(string key, string iv, byte[] cipherBytes)
{
if (key.IsNullOrBlank())
{
throw new ApplicationException("The key string cannot be empty in SymmetricDecrypt.");
}
else if (iv.IsNullOrBlank())
{
throw new ApplicationException("The initialisation vector cannot be empty in SymmetricDecrypt.");
}
else if (cipherBytes == null)
{
throw new ApplicationException("The cipher byte array cannot be empty in SymmetricDecrypt.");
}
AesManaged aes = new AesManaged();
ICryptoTransform encryptor = aes.CreateDecryptor(GetFixedLengthByteArray(key, AES_KEY_SIZE), GetFixedLengthByteArray(iv, AES_IV_SIZE));
MemoryStream cipherStream = new MemoryStream(cipherBytes);
CryptoStream cryptoStream = new CryptoStream(cipherStream, encryptor, CryptoStreamMode.Read);
StreamReader cryptoStreamReader = new StreamReader(cryptoStream);
return cryptoStreamReader.ReadToEnd();
}
private static byte[] GetFixedLengthByteArray(string value, int length)
{
if (value.Length < length)
{
while (value.Length < length)
{
value += 0x00;
}
}
else if (value.Length > length)
{
value = value.Substring(0, length);
}
return Encoding.UTF8.GetBytes(value);
}
public static string GetRandomString(int length)
{
char[] buffer = new char[length];
for (int i = 0; i < length; i++)
{
buffer[i] = CHARS[_rng.Next(CHARS.Length)];
}
return new string(buffer);
}
public static string GetRandomString()
{
return GetRandomString(DEFAULT_RANDOM_LENGTH);
}
/// <summary>
/// Returns a 10 digit random number.
/// </summary>
/// <returns></returns>
public static int GetRandomInt()
{
return GetRandomInt(DEFAULT_RANDOM_LENGTH);
}
/// <summary>
/// Returns a random number of a specified length.
/// </summary>
public static int GetRandomInt(int length)
{
int randomStart = 1000000000;
int randomEnd = Int32.MaxValue;
if (length > 0 && length < DEFAULT_RANDOM_LENGTH)
{
randomStart = Convert.ToInt32(Math.Pow(10, length - 1));
randomEnd = Convert.ToInt32(Math.Pow(10, length) - 1);
}
return GetRandomInt(randomStart, randomEnd);
}
public static Int32 GetRandomInt(Int32 minValue, Int32 maxValue)
{
if (minValue > maxValue)
{
throw new ArgumentOutOfRangeException("minValue");
}
else if (minValue == maxValue)
{
return minValue;
}
Int64 diff = maxValue - minValue + 1;
int attempts = 0;
while (attempts < 10)
{
byte[] uint32Buffer = new byte[4];
m_randomProvider.GetBytes(uint32Buffer);
UInt32 rand = BitConverter.ToUInt32(uint32Buffer, 0);
Int64 max = (1 + (Int64)UInt32.MaxValue);
Int64 remainder = max % diff;
if (rand <= max - remainder)
{
return (Int32)(minValue + (rand % diff));
}
attempts++;
}
throw new ApplicationException("GetRandomInt did not return an appropriate random number within 10 attempts.");
}
public static UInt16 GetRandomUInt16()
{
byte[] uint16Buffer = new byte[2];
m_randomProvider.GetBytes(uint16Buffer);
return BitConverter.ToUInt16(uint16Buffer, 0);
}
public static UInt32 GetRandomUInt()
{
byte[] uint32Buffer = new byte[4];
m_randomProvider.GetBytes(uint32Buffer);
return BitConverter.ToUInt32(uint32Buffer, 0);
}
//public static string GetRandomString(int length)
//{
// string randomStr = GetRandomInt(length).ToString();
// return (randomStr.Length > length) ? randomStr.Substring(0, length) : randomStr;
//}
public static byte[] createRandomSalt(int length)
{
byte[] randBytes = new byte[length];
m_randomProvider.GetBytes(randBytes);
return randBytes;
}
/// <summary>
/// This vesion reads the whole file in at once. This is not great since it can consume
/// a lot of memory if the file is large. However a buffered approach generates
/// diferrent hashes across different platforms.
/// </summary>
/// <param name="filepath"></param>
/// <returns></returns>
public static string GetHash(string filepath)
{
// Check and then attempt to open the plaintext stream.
FileStream fileStream = GetFileStream(filepath);
// Encrypt the file using its hash as the key.
SHA1 shaM = new SHA1Managed();
// Buffer to read in plain text blocks.
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
fileStream.Close();
byte[] overallHash = shaM.ComputeHash(fileBuffer);
return Convert.ToBase64String(overallHash);
}
/// <summary>
/// Used by methods wishing to perform a hash operation on a file. This method
/// will perform a number of checks and if happy return a read only file stream.
/// </summary>
/// <param name="filepath">The path to the input file for the hash operation.</param>
/// <returns>A read only file stream for the file or throws an exception if there is a problem.</returns>
private static FileStream GetFileStream(string filepath)
{
// Check that the file exists.
if (!File.Exists(filepath))
{
logger.Error("Cannot open a non-existent file for a hash operation, " + filepath + ".");
throw new IOException("Cannot open a non-existent file for a hash operation, " + filepath + ".");
}
// Open the file.
FileStream inputStream = File.OpenRead(filepath);
if (inputStream.Length == 0)
{
inputStream.Close();
logger.Error("Cannot perform a hash operation on an empty file, " + filepath + ".");
throw new IOException("Cannot perform a hash operation on an empty file, " + filepath + ".");
}
return inputStream;
}
/// <summary>
/// Gets an "X2" string representation of a random number.
/// </summary>
/// <param name="byteLength">The byte length of the random number string to obtain.</param>
/// <returns>A string representation of the random number. It will be twice the length of byteLength.</returns>
public static string GetRandomByteString(int byteLength)
{
byte[] myKey = new byte[byteLength];
m_randomProvider.GetBytes(myKey);
string sessionID = null;
myKey.ToList().ForEach(b => sessionID += b.ToString("x2"));
return sessionID;
}
public static byte[] GetSHAHash(params string[] values)
{
SHA1 sha = new SHA1Managed();
string plainText = null;
foreach (string value in values)
{
plainText += value;
}
return sha.ComputeHash(Encoding.UTF8.GetBytes(plainText));
}
public static string GetSHAHashAsString(params string[] values)
{
return Convert.ToBase64String(GetSHAHash(values));
}
/// <summary>
/// Returns the hash with each byte as an X2 string. This is useful for situations where
/// the hash needs to only contain safe ASCII characters.
/// </summary>
/// <param name="values">The list of string to concantenate and hash.</param>
/// <returns>A string with "safe" (0-9 and A-F) characters representing the hash.</returns>
public static string GetSHAHashAsHex(params string[] values)
{
byte[] hash = GetSHAHash(values);
string hashStr = null;
hash.ToList().ForEach(b => hashStr += b.ToString("x2"));
return hashStr;
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class CryptoUnitTest {
[TestFixtureSetUp]
public void Init() {
}
[TestFixtureTearDown]
public void Dispose() {
}
[Test]
public void SampleTest() {
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
int initRandomNumber = Crypto.GetRandomInt();
Console.WriteLine("Random int = " + initRandomNumber + ".");
Console.WriteLine("-----------------------------------------");
}
[Test]
public void CallRandomNumberWebServiceUnitTest() {
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
Console.WriteLine("Random number = " + GetRandomInt());
Console.WriteLine("-----------------------------------------");
}
[Test]
public void GetRandomNumberTest() {
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
Console.WriteLine("Random number = " + GetRandomInt());
Console.WriteLine("-----------------------------------------");
}
[Test]
public void GetOneHundredRandomNumbersTest() {
Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name);
for (int index = 0; index < 100; index++) {
Console.WriteLine("Random number = " + GetRandomInt());
}
Console.WriteLine("-----------------------------------------");
}
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PygmentSharp.Core.Styles
{
/// <summary>
/// Represents formatting and color style
/// </summary>
public sealed class StyleData : IEquatable<StyleData>
{
/// <summary>
/// Gets the text color
/// </summary>
public string Color { get; }
/// <summary>
/// Gets a value indicating if the text is bold
/// </summary>
public bool Bold { get; }
/// <summary>
/// Gets a value indicating if the text is italic
/// </summary>
public bool Italic { get; }
/// <summary>
/// Gets a value indicating if the text is underliend
/// </summary>
public bool Underline { get; }
/// <summary>
/// gets the background color
/// </summary>
public string BackgroundColor { get; }
/// <summary>
/// gets the border color
/// </summary>
public string BorderColor { get; }
/// <summary>
/// gets a value indicating if the font should come from the Roman family
/// </summary>
public bool Roman { get; }
/// <summary>
/// gets a value indicating if the font should be sans-serif
/// </summary>
public bool Sans { get; }
/// <summary>
/// gets a value indicating if the font should be monospaced
/// </summary>
public bool Mono { get; }
/// <summary>
/// Initializea a new instance of the <see cref="StyleData"/> class
/// </summary>
/// <param name="color">text color</param>
/// <param name="bold">text bolded?</param>
/// <param name="italic">text italics?</param>
/// <param name="underline">text udnerliend?</param>
/// <param name="bgColor">background color</param>
/// <param name="borderColor">border color</param>
/// <param name="roman">font roman?</param>
/// <param name="sans">font sans-serif?</param>
/// <param name="mono">font monospaced?</param>
public StyleData(string color = null,
bool bold = false,
bool italic = false,
bool underline = false,
string bgColor = null,
string borderColor = null,
bool roman = false,
bool sans = false,
bool mono = false)
{
Color = color;
Bold = bold;
Italic = italic;
Underline = underline;
BackgroundColor = bgColor;
BorderColor = borderColor;
Roman = roman;
Sans = sans;
Mono = mono;
}
/// <summary>
/// Parses a <see cref="StyleData"/> instance from a string
/// </summary>
/// <param name="text">the string to parse</param>
/// <returns></returns>
public static StyleData Parse(string text) => Parse(text, new StyleData());
/// <summary>
/// Parses a <see cref="StyleData"/> instance from a string, merging with a default. Unset properties in the parse string will
/// be copied from the base style
/// </summary>
/// <param name="text">The string to parse</param>
/// <param name="merged">The base style to merge with</param>
/// <returns></returns>
public static StyleData Parse(string text, StyleData merged)
{
string color = merged.Color, bgColor = merged.BackgroundColor, borderColor = merged.BorderColor;
bool bold = merged.Bold, italic = merged.Italic, underline = merged.Underline, roman = merged.Roman, sans = merged.Sans, mono = merged.Mono;
foreach (var styledef in text.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries))
{
if (styledef == "noinherit")
{
// noop
}
else if (styledef == "bold")
bold = true;
else if (styledef == "nobold")
bold = false;
else if (styledef == "italic")
italic = true;
else if (styledef == "noitalic")
italic = false;
else if (styledef == "underline")
underline = true;
else if (styledef.StartsWith("bg:", StringComparison.Ordinal))
bgColor = ColorFormat(styledef.Substring(3));
else if (styledef.StartsWith("border:", StringComparison.Ordinal))
borderColor = ColorFormat(styledef.Substring(7));
else if (styledef == "roman")
roman = true;
else if (styledef == "sans")
sans = true;
else if (styledef == "mono")
mono = true;
else
color = ColorFormat(styledef);
}
return new StyleData(color, bold, italic, underline, bgColor, borderColor, roman, sans, mono);
}
/// <summary>Returns a string that represents the current object. Basically CSS style</summary>
/// <returns>A string that represents the current object.</returns>
/// <filterpriority>2</filterpriority>
public override string ToString()
{
var color = string.IsNullOrEmpty(Color) ? null : $"color:#{Color};";
var fontWeight = Bold ? "font-weight:bold;" : null;
var fontStyle = Italic ? "font-style:italic;" : null;
var textDecoration = Underline ? "text-decoration:underline;" : null;
var borderColor = string.IsNullOrEmpty(BorderColor) ? null : $"border-color:#{BorderColor};";
var backgroundColor = string.IsNullOrEmpty(BackgroundColor) ? null : $"background-color:#{BackgroundColor};";
var fontFamily = new StringBuilder();
if (Roman || Sans || Mono)
{
fontFamily.Append("font-family:");
if (Roman) fontFamily.Append(" roman");
if (Sans) fontFamily.Append(" sans");
if (Mono) fontFamily.Append(" mono");
fontFamily.Append(";");
}
return string.Concat(color, backgroundColor, borderColor, fontFamily, fontWeight, fontStyle, textDecoration);
}
private static string ColorFormat(string color)
{
if (color.StartsWith("#", StringComparison.InvariantCulture))
{
var colorPart = color.Substring(1);
if (colorPart.Length == 6)
return colorPart;
if (colorPart.Length == 3)
{
var r = colorPart[0];
var g = colorPart[1];
var b = colorPart[2];
return string.Concat(r, r, g, g, b, b);
}
}
else if (color == "")
return "";
throw new FormatException($"Could not understand color '{color}'.");
}
#region R# Equality
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(StyleData other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return string.Equals(Color, other.Color) && Bold == other.Bold && Italic == other.Italic && Underline == other.Underline && string.Equals(BackgroundColor, other.BackgroundColor) && string.Equals(BorderColor, other.BorderColor) && Roman == other.Roman && Sans == other.Sans && Mono == other.Mono;
}
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <returns>true if the specified object is equal to the current object; otherwise, false.</returns>
/// <param name="obj">The object to compare with the current object. </param>
/// <filterpriority>2</filterpriority>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((StyleData) obj);
}
/// <summary>Serves as the default hash function. </summary>
/// <returns>A hash code for the current object.</returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode()
{
unchecked
{
var hashCode = (Color != null ? Color.GetHashCode() : 0);
hashCode = (hashCode*397) ^ Bold.GetHashCode();
hashCode = (hashCode*397) ^ Italic.GetHashCode();
hashCode = (hashCode*397) ^ Underline.GetHashCode();
hashCode = (hashCode*397) ^ (BackgroundColor != null ? BackgroundColor.GetHashCode() : 0);
hashCode = (hashCode*397) ^ (BorderColor != null ? BorderColor.GetHashCode() : 0);
hashCode = (hashCode*397) ^ Roman.GetHashCode();
hashCode = (hashCode*397) ^ Sans.GetHashCode();
hashCode = (hashCode*397) ^ Mono.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Compares two StyleDatas for equality
/// </summary>
/// <param name="left">The LHS styledata</param>
/// <param name="right">The RHS styledata</param>
/// <returns></returns>
public static bool operator ==(StyleData left, StyleData right)
{
return Equals(left, right);
}
/// <summary>
/// Compares two StyleDatas for inequality
/// </summary>
/// <param name="left">The LHS styledata</param>
/// <param name="right">The RHS styledata</param>
/// <returns></returns>
public static bool operator !=(StyleData left, StyleData right)
{
return !Equals(left, right);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
using Mono.Addins;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.Servers;
[assembly:AddinRoot("Robust", OpenSim.VersionInfo.VersionNumber)]
namespace OpenSim.Server.Base
{
[TypeExtensionPoint(Path="/Robust/Connector", Name="RobustConnector")]
public interface IRobustConnector
{
string ConfigName
{
get;
}
bool Enabled
{
get;
}
string PluginPath
{
get;
set;
}
uint Configure(IConfigSource config);
void Initialize(IHttpServer server);
void Unload();
}
public class PluginLoader
{
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public AddinRegistry Registry
{
get;
private set;
}
public IConfigSource Config
{
get;
private set;
}
public PluginLoader(IConfigSource config, string registryPath)
{
Config = config;
Registry = new AddinRegistry(registryPath, ".");
//suppress_console_output_(true);
AddinManager.Initialize(registryPath);
//suppress_console_output_(false);
AddinManager.Registry.Update();
CommandManager commandmanager = new CommandManager(Registry);
AddinManager.AddExtensionNodeHandler("/Robust/Connector", OnExtensionChanged);
}
private static TextWriter prev_console_;
// Temporarily masking the errors reported on start
// This is caused by a non-managed dll in the ./bin dir
// when the registry is initialized. The dll belongs to
// libomv, which has a hard-coded path to "." for pinvoke
// to load the openjpeg dll
//
// Will look for a way to fix, but for now this keeps the
// confusion to a minimum. this was copied from our region
// plugin loader, we have been doing this in there for a long time.
//
public void suppress_console_output_(bool save)
{
if (save)
{
prev_console_ = System.Console.Out;
System.Console.SetOut(new StreamWriter(Stream.Null));
}
else
{
if (prev_console_ != null)
System.Console.SetOut(prev_console_);
}
}
private void OnExtensionChanged(object s, ExtensionNodeEventArgs args)
{
IRobustConnector connector = (IRobustConnector)args.ExtensionObject;
Addin a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
if(a == null)
{
Registry.Rebuild(null);
a = Registry.GetAddin(args.ExtensionNode.Addin.Id);
}
switch(args.Change)
{
case ExtensionChange.Add:
if (a.AddinFile.Contains(Registry.DefaultAddinsFolder))
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from registry", a.Name);
connector.PluginPath = System.IO.Path.Combine(Registry.DefaultAddinsFolder,a.Name.Replace(',', '.')); }
else
{
m_log.InfoFormat("[SERVER UTILS]: Adding {0} from ./bin", a.Name);
connector.PluginPath = a.AddinFile;
}
LoadPlugin(connector);
break;
case ExtensionChange.Remove:
m_log.InfoFormat("[SERVER UTILS]: Removing {0}", a.Name);
UnloadPlugin(connector);
break;
}
}
private void LoadPlugin(IRobustConnector connector)
{
IHttpServer server = null;
uint port = connector.Configure(Config);
if(connector.Enabled)
{
server = GetServer(connector, port);
connector.Initialize(server);
}
else
{
m_log.InfoFormat("[SERVER UTILS]: {0} Disabled.", connector.ConfigName);
}
}
private void UnloadPlugin(IRobustConnector connector)
{
m_log.InfoFormat("[SERVER UTILS]: Unloading {0}", connector.ConfigName);
connector.Unload();
}
private IHttpServer GetServer(IRobustConnector connector, uint port)
{
IHttpServer server;
if(port != 0)
server = MainServer.GetHttpServer(port);
else
server = MainServer.Instance;
return server;
}
}
public static class ServerUtils
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static byte[] SerializeResult(XmlSerializer xs, object data)
{
using (MemoryStream ms = new MemoryStream())
using (XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8))
{
xw.Formatting = Formatting.Indented;
xs.Serialize(xw, data);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
byte[] ret = ms.GetBuffer();
Array.Resize(ref ret, (int)ms.Length);
return ret;
}
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T> (string dllName, Object[] args) where T:class
{
// This is good to debug configuration problems
//if (dllName == string.Empty)
// Util.PrintCallStack();
string className = String.Empty;
// The path for a dynamic plugin will contain ":" on Windows
string[] parts = dllName.Split (new char[] {':'});
if (parts [0].Length > 1)
{
dllName = parts [0];
if (parts.Length > 1)
className = parts[1];
}
else
{
// This is Windows - we must replace the ":" in the path
dllName = String.Format ("{0}:{1}", parts [0], parts [1]);
if (parts.Length > 2)
className = parts[2];
}
return LoadPlugin<T>(dllName, className, args);
}
/// <summary>
/// Load a plugin from a dll with the given class or interface
/// </summary>
/// <param name="dllName"></param>
/// <param name="className"></param>
/// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
/// <returns></returns>
public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
{
string interfaceName = typeof(T).ToString();
try
{
Assembly pluginAssembly = Assembly.LoadFrom(dllName);
foreach (Type pluginType in pluginAssembly.GetTypes())
{
if (pluginType.IsPublic)
{
if (className != String.Empty
&& pluginType.ToString() != pluginType.Namespace + "." + className)
continue;
Type typeInterface = pluginType.GetInterface(interfaceName, true);
if (typeInterface != null)
{
T plug = null;
try
{
plug = (T)Activator.CreateInstance(pluginType,
args);
}
catch (Exception e)
{
if (!(e is System.MissingMethodException))
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin {0} from {1}. Exception: {2}",
interfaceName,
dllName,
e.InnerException == null ? e.Message : e.InnerException.Message),
e);
}
m_log.ErrorFormat("[SERVER UTILS]: Error loading plugin {0}: {1} args.Length {2}", dllName, e.Message, args.Length);
return null;
}
return plug;
}
}
}
return null;
}
catch (ReflectionTypeLoadException rtle)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}:\n{1}", dllName,
String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
rtle);
return null;
}
catch (Exception e)
{
m_log.Error(string.Format("[SERVER UTILS]: Error loading plugin from {0}", dllName), e);
return null;
}
}
public static Dictionary<string, object> ParseQueryString(string query)
{
Dictionary<string, object> result = new Dictionary<string, object>();
string[] terms = query.Split(new char[] {'&'});
if (terms.Length == 0)
return result;
foreach (string t in terms)
{
string[] elems = t.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
if (name.EndsWith("[]"))
{
string cleanName = name.Substring(0, name.Length - 2);
if (result.ContainsKey(cleanName))
{
if (!(result[cleanName] is List<string>))
continue;
List<string> l = (List<string>)result[cleanName];
l.Add(value);
}
else
{
List<string> newList = new List<string>();
newList.Add(value);
result[cleanName] = newList;
}
}
else
{
if (!result.ContainsKey(name))
result[name] = value;
}
}
return result;
}
public static string BuildQueryString(Dictionary<string, object> data)
{
string qstring = String.Empty;
string part;
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value is List<string>)
{
List<string> l = (List<String>)kvp.Value;
foreach (string s in l)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"[]=" + System.Web.HttpUtility.UrlEncode(s);
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
else
{
if (kvp.Value.ToString() != String.Empty)
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
"=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
}
else
{
part = System.Web.HttpUtility.UrlEncode(kvp.Key);
}
if (qstring != String.Empty)
qstring += "&";
qstring += part;
}
}
return qstring;
}
public static string BuildXmlResponse(Dictionary<string, object> data)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
BuildXmlData(rootElement, data);
return doc.InnerXml;
}
private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
{
foreach (KeyValuePair<string, object> kvp in data)
{
if (kvp.Value == null)
continue;
XmlElement elem = parent.OwnerDocument.CreateElement("",
XmlConvert.EncodeLocalName(kvp.Key), "");
if (kvp.Value is Dictionary<string, object>)
{
XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
"type", "");
type.Value = "List";
elem.Attributes.Append(type);
BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
}
else
{
elem.AppendChild(parent.OwnerDocument.CreateTextNode(
kvp.Value.ToString()));
}
parent.AppendChild(elem);
}
}
public static Dictionary<string, object> ParseXmlResponse(string data)
{
//m_log.DebugFormat("[XXX]: received xml string: {0}", data);
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(data);
XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
if (rootL.Count != 1)
return ret;
XmlNode rootNode = rootL[0];
ret = ParseElement(rootNode);
return ret;
}
private static Dictionary<string, object> ParseElement(XmlNode element)
{
Dictionary<string, object> ret = new Dictionary<string, object>();
XmlNodeList partL = element.ChildNodes;
foreach (XmlNode part in partL)
{
XmlNode type = part.Attributes.GetNamedItem("type");
if (type == null || type.Value != "List")
{
ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
}
else
{
ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
}
}
return ret;
}
public static IConfig GetConfig(string configFile, string configName)
{
IConfig config;
if (File.Exists(configFile))
{
IConfigSource configsource = new IniConfigSource(configFile);
config = configsource.Configs[configName];
}
else
config = null;
return config;
}
public static IConfigSource LoadInitialConfig(string url)
{
IConfigSource source = new XmlConfigSource();
m_log.InfoFormat("[SERVER UTILS]: {0} is a http:// URI, fetching ...", url);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(url);
IConfigSource cs = new XmlConfigSource(r);
source.Merge(cs);
}
catch (Exception e)
{
m_log.FatalFormat("[SERVER UTILS]: Exception reading config from URI {0}\n" + e.ToString(), url);
Environment.Exit(1);
}
return source;
}
}
}
| |
//
// assembly: System_test
// namespace: MonoTests.System.Text.RegularExpressions
// file: RegexTest.cs
//
// Authors:
// Juraj Skripsky ([email protected])
//
// (c) 2003 Juraj Skripsky
using System;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace MonoTests.System.Text.RegularExpressions {
[TestFixture]
public class RegexTest : Assertion {
[Test]
public void Simple () {
char[] c = { (char)32, (char)8212, (char)32 };
string s = new String(c);
Assertion.AssertEquals ("char", true, Regex.IsMatch(s, s));
}
[Test]
public void Unescape () {
string inString = @"\a\b\t\r\v\f\n\e\02400\x231\cC\ufffff\*";
char [] c = { (char)7, (char)8, (char)9, (char)13,
(char)11, (char)12, (char)10, (char)27, (char) 20,
(char)48, (char)48, (char)35, (char)49,
(char)3, (char)65535, (char)102, (char)42
};
string expectedString = new String(c);
string outString = Regex.Unescape(inString);
Assertion.AssertEquals("unescape", outString, expectedString);
}
[Test]
public void Match1 ()
{
Regex email = new Regex ("(?<user>[^@]+)@(?<domain>.+)");
Match m;
m = email.Match ("[email protected]");
Assert ("#m01", m.Success);
AssertEquals ("#m02", "mono", m.Groups ["user"].Value);
AssertEquals ("#m03", "go-mono.com", m.Groups ["domain"].Value);
m = email.Match ("[email protected]");
Assert ("#m04", m.Success);
AssertEquals ("#m05", "mono.bugs", m.Groups ["user"].Value);
AssertEquals ("#m06", "go-mono.com", m.Groups ["domain"].Value);
}
[Test]
public void Matches1 ()
{
Regex words = new Regex ("(?<word>\\w+)");
MatchCollection mc = words.Matches ("the fat cat ate the rat");
AssertEquals ("#m01", 6, mc.Count);
AssertEquals ("#m02", "the", mc [0].Value);
AssertEquals ("#m03", "fat", mc [1].Value);
AssertEquals ("#m04", "cat", mc [2].Value);
AssertEquals ("#m05", "ate", mc [3].Value);
AssertEquals ("#m06", "the", mc [4].Value);
AssertEquals ("#m07", "rat", mc [5].Value);
}
[Test]
public void Matches2 ()
{
Regex words = new Regex ("(?<word>\\w+)", RegexOptions.RightToLeft);
MatchCollection mc = words.Matches ("the fat cat ate the rat");
AssertEquals ("#m01", 6, mc.Count);
AssertEquals ("#m02", "the", mc [5].Value);
AssertEquals ("#m03", "fat", mc [4].Value);
AssertEquals ("#m04", "cat", mc [3].Value);
AssertEquals ("#m05", "ate", mc [2].Value);
AssertEquals ("#m06", "the", mc [1].Value);
AssertEquals ("#m07", "rat", mc [0].Value);
}
[Test]
public void Matches3 ()
{
Regex digits = new Regex ("(?<digit>\\d+)");
MatchCollection mc = digits.Matches ("0 1 2 3 4 5 6a7b8c9d10");
AssertEquals ("#m01", 11, mc.Count);
AssertEquals ("#m02", "0", mc [0].Value);
AssertEquals ("#m03", "1", mc [1].Value);
AssertEquals ("#m04", "2", mc [2].Value);
AssertEquals ("#m05", "3", mc [3].Value);
AssertEquals ("#m06", "4", mc [4].Value);
AssertEquals ("#m07", "5", mc [5].Value);
AssertEquals ("#m08", "6", mc [6].Value);
AssertEquals ("#m09", "7", mc [7].Value);
AssertEquals ("#m10", "8", mc [8].Value);
AssertEquals ("#m11", "9", mc [9].Value);
AssertEquals ("#m12", "10", mc [10].Value);
}
[Test]
public void Matches4 ()
{
Regex digits = new Regex ("(?<digit>\\d+)", RegexOptions.RightToLeft);
MatchCollection mc = digits.Matches ("0 1 2 3 4 5 6a7b8c9d10");
AssertEquals ("#m01", 11, mc.Count);
AssertEquals ("#m02", "0", mc [10].Value);
AssertEquals ("#m03", "1", mc [9].Value);
AssertEquals ("#m04", "2", mc [8].Value);
AssertEquals ("#m05", "3", mc [7].Value);
AssertEquals ("#m06", "4", mc [6].Value);
AssertEquals ("#m07", "5", mc [5].Value);
AssertEquals ("#m08", "6", mc [4].Value);
AssertEquals ("#m09", "7", mc [3].Value);
AssertEquals ("#m10", "8", mc [2].Value);
AssertEquals ("#m11", "9", mc [1].Value);
AssertEquals ("#m12", "10", mc [0].Value);
}
[Test]
public void Matches5 ()
{
Regex lines = new Regex ("(?<line>.+)");
MatchCollection mc = lines.Matches (story);
AssertEquals ("#m01", 5, mc.Count);
AssertEquals ("#m02", "Two little dragons lived in the forest", mc [0].Value);
AssertEquals ("#m03", "They spent their days collecting honey suckle,",
mc [1].Value);
AssertEquals ("#m04", "And eating curds and whey", mc [2].Value);
AssertEquals ("#m05", "Until an evil sorcer came along", mc [3].Value);
AssertEquals ("#m06", "And chased my dragon friends away", mc [4].Value);
}
[Test]
public void Matches6 ()
{
Regex lines = new Regex ("(?<line>.+)", RegexOptions.RightToLeft);
MatchCollection mc = lines.Matches (story);
AssertEquals ("#m01", 5, mc.Count);
AssertEquals ("#m02", "Two little dragons lived in the forest", mc [4].Value);
AssertEquals ("#m03", "They spent their days collecting honey suckle,",
mc [3].Value);
AssertEquals ("#m04", "And eating curds and whey", mc [2].Value);
AssertEquals ("#m05", "Until an evil sorcer came along", mc [1].Value);
AssertEquals ("#m06", "And chased my dragon friends away", mc [0].Value);
}
string story = "Two little dragons lived in the forest\n" +
"They spent their days collecting honey suckle,\n" +
"And eating curds and whey\n" +
"Until an evil sorcer came along\n" +
"And chased my dragon friends away";
[Test]
public void Matches7 ()
{
Regex nonwhite = new Regex ("(?<nonwhite>\\S+)");
MatchCollection mc = nonwhite.Matches ("ab 12 cde 456 fghi .,\niou");
AssertEquals ("#m01", 7, mc.Count);
AssertEquals ("#m02", "ab", mc [0].Value);
AssertEquals ("#m03", "12", mc [1].Value);
AssertEquals ("#m04", "cde", mc [2].Value);
AssertEquals ("#m05", "456", mc [3].Value);
AssertEquals ("#m06", "fghi", mc [4].Value);
AssertEquals ("#m07", ".,", mc [5].Value);
AssertEquals ("#m08", "iou", mc [6].Value);
}
[Test]
public void Matches8 ()
{
Regex nonwhite = new Regex ("(?<nonwhite>\\S+)", RegexOptions.RightToLeft);
MatchCollection mc = nonwhite.Matches ("ab 12 cde 456 fghi .,\niou");
AssertEquals ("#m01", 7, mc.Count);
AssertEquals ("#m02", "ab", mc [6].Value);
AssertEquals ("#m03", "12", mc [5].Value);
AssertEquals ("#m04", "cde", mc [4].Value);
AssertEquals ("#m05", "456", mc [3].Value);
AssertEquals ("#m06", "fghi", mc [2].Value);
AssertEquals ("#m07", ".,", mc [1].Value);
AssertEquals ("#m08", "iou", mc [0].Value);
}
[Test]
public void Matches9 ()
{
Regex nondigit = new Regex ("(?<nondigit>\\D+)");
MatchCollection mc = nondigit.Matches ("ab0cd1ef2");
AssertEquals ("#m01", 3, mc.Count);
AssertEquals ("#m02", "ab", mc [0].Value);
AssertEquals ("#m02", "cd", mc [1].Value);
AssertEquals ("#m02", "ef", mc [2].Value);
}
[Test]
public void Matches10 ()
{
Regex nondigit = new Regex ("(?<nondigit>\\D+)", RegexOptions.RightToLeft);
MatchCollection mc = nondigit.Matches ("ab0cd1ef2");
AssertEquals ("#m01", 3, mc.Count);
AssertEquals ("#m02", "ab", mc [2].Value);
AssertEquals ("#m02", "cd", mc [1].Value);
AssertEquals ("#m02", "ef", mc [0].Value);
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Menu Builder Helper Class
//-----------------------------------------------------------------------------
//- @class MenuBuilder
//- @brief Create Dynamic Context and MenuBar Menus
//-
//-
//- Summary : The MenuBuilder script class exists merely as a helper for creating
//- popup menu's for use in torque editors. It is setup as a single
//- object with dynamic fields starting with item[0]..[n] that describe
//- how to create the menu in question. An example is below.
//-
//- isPopup : isPopup is a persistent field on PopupMenu console class which
//- when specified to true will allow you to perform .showPopup(x,y)
//- commands which allow popupmenu's to be used/reused as menubar menus
//- as well as context menus.
//-
//- barPosition : barPosition indicates which index on the menu bar (0 = leftmost)
//- to place this menu if it is attached. Use the attachToMenuBar() command
//- to attach a menu.
//-
//- barName : barName specifies the visible name of a menu item that is attached
//- to the global menubar.
//-
//- canvas : The GuiCanvas object the menu should be attached to. This defaults to
//- the global Canvas object if unspecified.
//-
//- Remarks : If you wish to use a menu as a context popup menu, isPopup must be
//- specified as true at the creation time of the menu.
//-
//- @li @b item[n] (String) TAB (String) TAB (String) : <c>A Menu Item Definition.</c>
//- @code item[0] = "Open File..." TAB "Ctrl O" TAB "Something::OpenFile"; @endcode
//-
//- @li @b isPopup (bool) : <c>If Specified the menu will be considered a popup menu and should be used via .showPopup()</c>
//- @code isPopup = true; @endcode
//-
//-
//- Example : Creating a @b MenuBar Menu
//- @code
//- %%editMenu = new PopupMenu()
//- {
//- barPosition = 3;
//- barName = "View";
//- superClass = "MenuBuilder";
//- item[0] = "Undo" TAB "Ctrl Z" TAB "levelBuilderUndo(1);";
//- item[1] = "Redo" TAB "Ctrl Y" TAB "levelBuilderRedo(1);";
//- item[2] = "-";
//- };
//-
//- %%editMenu.attachToMenuBar( 1, "Edit" );
//-
//- @endcode
//-
//-
//- Example : Creating a @b Context (Popup) Menu
//- @code
//- %%contextMenu = new PopupMenu()
//- {
//- superClass = MenuBuilder;
//- isPopup = true;
//- item[0] = "My Super Cool Item" TAB "Ctrl 2" TAB "echo(\"Clicked Super Cool Item\");";
//- item[1] = "-";
//- };
//-
//- %%contextMenu.showPopup();
//- @endcode
//-
//-
//- Example : Modifying a Menu
//- @code
//- %%editMenu = new PopupMenu()
//- {
//- item[0] = "Foo" TAB "Ctrl F" TAB "echo(\"clicked Foo\")";
//- item[1] = "-";
//- };
//- %%editMenu.addItem( 2, "Bar" TAB "Ctrl B" TAB "echo(\"clicked Bar\")" );
//- %%editMenu.removeItem( 0 );
//- %%editMenu.addItem( 0, "Modified Foo" TAB "Ctrl F" TAB "echo(\"clicked modified Foo\")" );
//- @endcode
//-
//-
//- @see PopupMenu
//-
//-----------------------------------------------------------------------------
// Adds one item to the menu.
// if %item is skipped or "", we will use %item[#], which was set when the menu was created.
// if %item is provided, then we update %item[#].
function MenuBuilder::addItem(%this, %pos, %item) {
if(%item $= "")
%item = %this.item[%pos];
if(%item !$= %this.item[%pos])
%this.item[%pos] = %item;
%name = getField(%item, 0);
%accel = getField(%item, 1);
%cmd = getField(%item, 2);
// We replace the [this] token with our object ID
%cmd = strreplace( %cmd, "[this]", %this );
%this.item[%pos] = setField( %item, 2, %cmd );
if(isObject(%accel)) {
// If %accel is an object, we want to add a sub menu
%this.insertSubmenu(%pos, %name, %accel);
} else {
%this.insertItem(%pos, %name !$= "-" ? %name : "", %accel);
}
}
function MenuBuilder::appendItem(%this, %item) {
%this.addItem(%this.getItemCount(), %item);
}
function MenuBuilder::onAdd(%this) {
if(! isObject(%this.canvas))
%this.canvas = Canvas;
for(%i = 0; %this.item[%i] !$= ""; %i++) {
%this.addItem(%i);
}
}
function MenuBuilder::onRemove(%this) {
if (!$Cfg_UI_Menu_UseNativeMenu && !$InGuiEditor)
return;
if (!isObject(%this)) {
warnLog("Trying to remove a menu which is not a menu:",%this);
return;
}
%this.removeFromMenuBar();
}
//-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///
function MenuBuilder::onSelectItem(%this, %id, %text) {
%cmd = getField(%this.item[%id], 2);
if(%cmd !$= "") {
eval( %cmd );
return true;
}
return false;
}
//- Sets a new name on an existing menu item.
function MenuBuilder::setItemName( %this, %id, %name ) {
%item = %this.item[%id];
%accel = getField(%item, 1);
%this.setItem( %id, %name, %accel );
}
//- Sets a new command on an existing menu item.
function MenuBuilder::setItemCommand( %this, %id, %command ) {
%this.item[%id] = setField( %this.item[%id], 2, %command );
}
//- (SimID this)
//- Wraps the attachToMenuBar call so that it does not require knowledge of
//- barName or barIndex to be removed/attached. This makes the individual
//- MenuBuilder items very easy to add and remove dynamically from a bar.
//-
function MenuBuilder::attachToMenuBar( %this ) {
if( %this.barName $= "" ) {
error("MenuBuilder::attachToMenuBar - Menu property 'barName' not specified.");
return false;
}
if( %this.barPosition < 0 ) {
error("MenuBuilder::attachToMenuBar - Menu " SPC %this.barName SPC "property 'barPosition' is invalid, must be zero or greater.");
return false;
}
Parent::attachToMenuBar( %this, %this.canvas, %this.barPosition, %this.barName );
}
//-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///
// Callbacks from PopupMenu. These callbacks are now passed on to submenus
// in C++, which was previously not the case. Thus, no longer anything to
// do in these. I am keeping the callbacks in case they are needed later.
function MenuBuilder::onAttachToMenuBar(%this, %canvas, %pos, %title) {
}
function MenuBuilder::onRemoveFromMenuBar(%this, %canvas) {
}
//-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///-///
//- Method called to setup default state for the menu. Expected to be overriden
//- on an individual menu basis. See the mission editor for an example.
function MenuBuilder::setupDefaultState(%this) {
for(%i = 0; %this.item[%i] !$= ""; %i++) {
%name = getField(%this.item[%i], 0);
%accel = getField(%this.item[%i], 1);
%cmd = getField(%this.item[%i], 2);
// Pass on to sub menus
if(isObject(%accel))
%accel.setupDefaultState();
}
}
//- Method called to easily enable or disable all items in a menu.
function MenuBuilder::enableAllItems(%this, %enable) {
for(%i = 0; %this.item[%i] !$= ""; %i++) {
%this.enableItem(%i, %enable);
}
}
| |
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using MonoMac.ObjCRuntime;
using MonoMac.Foundation;
using MonoMac.AppKit;
namespace SamplesButtonMadness
{
public partial class TestWindowController : MonoMac.AppKit.NSWindowController
{
#region members
NSPopUpButton codeBasedPopUpDown;
NSPopUpButton codeBasedPopUpRight;
NSButton codeBasedButtonRound;
NSButton codeBasedButtonSquare;
NSSegmentedControl codeBasedSegmentControl;
NSLevelIndicator codeBasedIndicator;
#endregion
#region Constructors
// Called when created from unmanaged code
public TestWindowController (IntPtr handle) : base(handle)
{
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public TestWindowController (NSCoder coder) : base(coder)
{
}
// Call to load from the XIB/NIB file
public TestWindowController () : base("TestWindow")
{
}
#endregion
//strongly typed window accessor
public new TestWindow Window {
get { return (TestWindow)base.Window; }
}
#region implementation
public override void AwakeFromNib ()
{
base.AwakeFromNib ();
#region first two buttons
// add the image menu item back to the first menu item
NSMenuItem menuItem = new NSMenuItem ("", new Selector (""), "");
menuItem.Image = NSImage.ImageNamed ("moof.png");
buttonMenu.InsertItematIndex (menuItem, 0);
nibBasedPopUpDown.Menu = buttonMenu;
nibBasedPopUpRight.Menu = buttonMenu;
// create the pull down button pointing DOWN
RectangleF buttonFrame = placeHolder1.Frame;
codeBasedPopUpDown = new NSPopUpButton (buttonFrame, true);
((NSPopUpButtonCell)codeBasedPopUpDown.Cell).ArrowPosition = NSPopUpArrowPosition.Bottom;
((NSPopUpButtonCell)codeBasedPopUpDown.Cell).BezelStyle = NSBezelStyle.ThickSquare;
codeBasedPopUpDown.Menu = buttonMenu;
popupBox.AddSubview (codeBasedPopUpDown);
placeHolder1.RemoveFromSuperview ();
// create the pull down button pointing RIGHT
buttonFrame = placeHolder2.Frame;
codeBasedPopUpRight = new NSPopUpButton (buttonFrame, true);
((NSPopUpButtonCell)codeBasedPopUpRight.Cell).ArrowPosition = NSPopUpArrowPosition.Bottom;
((NSPopUpButtonCell)codeBasedPopUpRight.Cell).PreferredEdge = NSRectEdge.MaxXEdge;
((NSPopUpButtonCell)codeBasedPopUpRight.Cell).BezelStyle = NSBezelStyle.Circular;
codeBasedPopUpRight.Menu = buttonMenu;
((NSPopUpButtonCell)codeBasedPopUpRight.Cell).HighlightsBy = (int)NSCellMask.ChangeGrayCell;
popupBox.AddSubview (codeBasedPopUpRight);
placeHolder2.RemoveFromSuperview ();
#endregion
#region second two buttons
// create the rounded button
buttonFrame = placeHolder3.Frame;
// note: this button we want alternate title and image, so we need to call this:
codeBasedButtonRound = new NSButton (buttonFrame) {
Title = "NSButton",
AlternateTitle = "(pressed)",
Image = NSImage.ImageNamed ("moof.png"),
AlternateImage = NSImage.ImageNamed ("moof2.png"),
BezelStyle = NSBezelStyle.RegularSquare,
ImagePosition = NSCellImagePosition.ImageLeft,
Font = NSFont.SystemFontOfSize (NSFont.SmallSystemFontSize),
Sound = NSSound.FromName ("Pop"),
};
// Two choices, either use the .NET event system:
// foo.Activated += delegate {..} or += SomeMethod
//
// Or you can use the Target = this Action = new Selector ("buttonAction:")
// pattern
codeBasedButtonRound.Activated += delegate {
buttonAction (null);
};
codeBasedButtonRound.SetButtonType (NSButtonType.MomentaryChange);
codeBasedButtonRound.Cell.Alignment = NSTextAlignment.Left;
buttonBox.AddSubview (codeBasedButtonRound);
placeHolder3.RemoveFromSuperview (); // we are done with the place holder, remove it from the window
// create the square button
buttonFrame = placeHolder4.Frame;
codeBasedButtonSquare = new NSButton (buttonFrame){
Title = "NSButton",
BezelStyle = NSBezelStyle.ShadowlessSquare,
ImagePosition = NSCellImagePosition.ImageLeft,
Image = NSImage.ImageNamed ("moof.png"),
Font = NSFont.SystemFontOfSize (NSFont.SmallSystemFontSize),
Sound = NSSound.FromName ("Pop"),
};
codeBasedButtonSquare.Activated += delegate { buttonAction (null); };
codeBasedButtonSquare.Cell.Alignment = NSTextAlignment.Left;
buttonBox.AddSubview (codeBasedButtonSquare);
placeHolder4.RemoveFromSuperview (); // we are done with the place holder, remove it from the window
#endregion
#region segmented control
buttonFrame = placeHolder5.Frame;
codeBasedSegmentControl = new NSSegmentedControl(buttonFrame) {
SegmentCount = 3,
Target = this,
Action = new Selector("segmentAction:")
};
codeBasedSegmentControl.SetWidth (nibBasedSegControl.GetWidth(0), 0);
codeBasedSegmentControl.SetWidth (nibBasedSegControl.GetWidth (1), 1);
codeBasedSegmentControl.SetWidth (nibBasedSegControl.GetWidth (2), 2);
codeBasedSegmentControl.SetLabel ("One", 0);
codeBasedSegmentControl.SetLabel ("Two", 1);
codeBasedSegmentControl.SetLabel ("Three", 2);
segmentBox.AddSubview (codeBasedSegmentControl);
placeHolder5.RemoveFromSuperview ();
// use a menu to the first segment (applied to both nib-based and code-based)
codeBasedSegmentControl.SetMenu (buttonMenu, 0);
nibBasedSegControl.SetMenu (buttonMenu, 0);
// add icons to each segment (applied to both nib-based and code-based)
NSImage segmentIcon1 = NSWorkspace.SharedWorkspace.IconForFileType(NSFileTypeForHFSTypeCode.ComputerIcon);
segmentIcon1.Size = new SizeF(16, 16);
nibBasedSegControl.SetImage (segmentIcon1, 0);
codeBasedSegmentControl.SetImage (segmentIcon1, 0);
NSImage segmentIcon2 = NSWorkspace.SharedWorkspace.IconForFileType (NSFileTypeForHFSTypeCode.DesktopIcon);
segmentIcon2.Size = new SizeF (16, 16);
nibBasedSegControl.SetImage (segmentIcon2, 1);
codeBasedSegmentControl.SetImage (segmentIcon2, 1);
NSImage segmentIcon3 = NSWorkspace.SharedWorkspace.IconForFileType (NSFileTypeForHFSTypeCode.FinderIcon);
segmentIcon3.Size = new SizeF (16, 16);
nibBasedSegControl.SetImage (segmentIcon3, 2);
codeBasedSegmentControl.SetImage (segmentIcon3, 2);
#endregion
#region level indicator
buttonFrame = placeHolder8.Frame;
codeBasedIndicator = new NSLevelIndicator(buttonFrame) {
MaxValue = 10,
MajorTickMarkCount = 4,
TickMarkCount = 7,
WarningValue = 5,
CriticalValue = 8,
Action = new Selector("levelAction:")
};
codeBasedIndicator.Cell.LevelIndicatorStyle = NSLevelIndicatorStyle.DiscreteCapacity;
indicatorBox.AddSubview(codeBasedIndicator);
placeHolder8.RemoveFromSuperview();
#endregion
}
#endregion
#region event handlers
partial void dropDownAction (NSObject sender)
{
Console.WriteLine ("Drop down button clicked");
}
partial void buttonAction (NSObject sender)
{
Console.WriteLine ("Button clicked");
}
partial void segmentAction (NSObject sender)
{
Console.WriteLine ("Segment button clicked");
}
partial void levelAction (NSObject sender)
{
Console.WriteLine ("Level action clicked");
}
partial void unselectAction (NSObject sender)
{
nibBasedSegControl.UnselectAllSegments();
codeBasedSegmentControl.UnselectAllSegments();
}
partial void levelAdjustAction (NSObject sender)
{
NSStepper stepper = sender as NSStepper;
Console.WriteLine ("Change level: {0}", stepper.IntValue);
nibBasedIndicator.IntValue = stepper.IntValue;
codeBasedIndicator.IntValue = stepper.IntValue;
}
#endregion
}
}
| |
/*
* Copyright (c) 2011-2016, Will Strohl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of Will Strohl, Disqus Module, 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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Modules.WillStrohlDisqus.Components;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Scheduling;
namespace DotNetNuke.Modules.WillStrohlDisqus
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The EditWillStrohlDisqus class is used to manage content
/// </summary>
/// -----------------------------------------------------------------------------
public partial class Edit : WillStrohlDisqusModuleBase
{
#region Private Properties
private const string RECEIVER_FILE_NAME = "disqus.htm";
private const string URL_FORMAT = "<a href=\"{0}\" target=\"_blank\">{0}</a>";
private int AttachedModule { get; set; }
private string DisqusView { get; set; }
private int DisplayItems { get; set; }
private bool ShowModerators { get; set; }
private string ColorTheme { get; set; }
private string DefaultTab { get; set; }
private int CommentLength { get; set; }
private bool ShowAvatar { get; set; }
private int AvatarSize { get; set; }
#endregion
#region Event Handlers
/// <summary>
/// OnInit - initialization of the module
/// </summary>
/// <param name="e"></param>
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.PageLoad);
this.cmdSave.Click += new System.EventHandler(this.CmdSaveClick);
this.cmdReturn.Click += new System.EventHandler(this.CmdReturnClick);
this.cboModuleView.SelectedIndexChanged += new System.EventHandler(this.CboModuleViewSelectedIndexChanged);
this.cmdReceiverFile.Click += new EventHandler(this.CmdReceiverFileClick);
chkSsoEnabled.CheckedChanged += new EventHandler(this.ChkSsoEnabledClick);
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Page_Load runs when the control is loaded
/// </summary>
/// -----------------------------------------------------------------------------
private void PageLoad(object sender, System.EventArgs e)
{
try
{
if(!this.IsPostBack)
{
this.BindData();
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
/// <summary>
/// Runs when the Save linkbutton is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CmdSaveClick(object sender, System.EventArgs e)
{
if (this.Page.IsValid)
{
this.SaveSettings();
this.SendBackToModule();
}
}
/// <summary>
/// Runs when the Return linkbutton is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CmdReturnClick(object sender, System.EventArgs e)
{
this.SendBackToModule();
}
/// <summary>
/// Runs when the DisqusView widget selection is changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CboModuleViewSelectedIndexChanged(object sender, System.EventArgs e)
{
this.ChangeView(this.cboModuleView.SelectedValue);
}
/// <summary>
/// Runs when the ReceiverFile linkbutton is clicked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void CmdReceiverFileClick(object sender, System.EventArgs e)
{
this.CreateReceiverFile();
this.SendBackToModule();
}
/// <summary>
/// Runs with the chkSsoEnabled checkbox is checked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ChkSsoEnabledClick(object sender, System.EventArgs e)
{
if (chkSsoEnabled.Checked)
{
chkRequireDnnLogin.Checked = true;
}
}
#endregion
#region Private Helper Methods
private void BindData()
{
this.LocalizeModule();
Dictionary<int, ModuleInfo>.ValueCollection collModule = new ModuleController().GetTabModules(this.TabId).Values;
foreach (ModuleInfo objModule in collModule)
{
if (objModule.ModuleID == this.ModuleId && objModule.IsDeleted == false) continue;
if (!string.IsNullOrEmpty(objModule.ModuleTitle.Trim()))
{
this.cboModuleList.Items.Add(new ListItem(objModule.ModuleTitle, objModule.ModuleID.ToString()));
}
else
{
this.cboModuleList.Items.Add(new ListItem(this.GetLocalizedString("NoName.Text"), objModule.ModuleID.ToString()));
}
}
this.cboModuleList.Items.Insert(0, new ListItem("---"));
this.cboModuleView.Items.Add(new ListItem(this.GetLocalizedString("cboModuleView.Items.Comments"), "comments"));
this.cboModuleView.Items.Add(new ListItem(this.GetLocalizedString("cboModuleView.Items.Combination"), "combination"));
this.cboModuleView.Items.Add(new ListItem(this.GetLocalizedString("cboModuleView.Items.RecentComments"), "recent-comments"));
this.cboModuleView.Items.Add(new ListItem(this.GetLocalizedString("cboModuleView.Items.PopularThreads"), "popular-threads"));
this.cboModuleView.Items.Add(new ListItem(this.GetLocalizedString("cboModuleView.Items.TopCommenters"), "top-commenters"));
for(int i = 1; i < 21; i++)
{
this.cboDisplayItems.Items.Add(new ListItem(i.ToString()));
}
this.cboColorTheme.Items.Add(new ListItem(this.GetLocalizedString("cboColorTheme.Items.Blue"), "blue"));
this.cboColorTheme.Items.Add(new ListItem(this.GetLocalizedString("cboColorTheme.Items.Grey"), "grey"));
this.cboColorTheme.Items.Add(new ListItem(this.GetLocalizedString("cboColorTheme.Items.Green"), "green"));
this.cboColorTheme.Items.Add(new ListItem(this.GetLocalizedString("cboColorTheme.Items.Red"), "red"));
this.cboColorTheme.Items.Add(new ListItem(this.GetLocalizedString("cboColorTheme.Items.Orange"), "orange"));
this.cboDefaultTab.Items.Add(new ListItem(this.GetLocalizedString("cboDefaultTab.Items.People"), "people"));
this.cboDefaultTab.Items.Add(new ListItem(this.GetLocalizedString("cboDefaultTab.Items.Recent"), "recent"));
this.cboDefaultTab.Items.Add(new ListItem(this.GetLocalizedString("cboDefaultTab.Items.Popular"), "popular"));
this.cboAvatarSize.Items.Add(new ListItem(this.GetLocalizedString("cboAvatarSize.Items.Small"), "24"));
this.cboAvatarSize.Items.Add(new ListItem(this.GetLocalizedString("cboAvatarSize.Items.Medium"), "32"));
this.cboAvatarSize.Items.Add(new ListItem(this.GetLocalizedString("cboAvatarSize.Items.Large"), "48"));
this.cboAvatarSize.Items.Add(new ListItem(this.GetLocalizedString("cboAvatarSize.Items.XLarge"), "92"));
this.cboAvatarSize.Items.Add(new ListItem(this.GetLocalizedString("cboAvatarSize.Items.Ginormous"), "128"));
this.cmdReceiverFile.Visible = (!this.DoesReceiverFileExist() || string.IsNullOrEmpty(DisqusApplicationName) == false);
this.pnlReceiverFile.Visible = (this.DoesReceiverFileExist());
if (this.pnlReceiverFile.Visible)
{
this.lblReceiverFile.Text = this.Page.ResolveUrl(this.CrossDomainReceiverUrlPath());
}
pnlHost.Visible = UserInfo.IsSuperUser;
this.LoadSettings();
this.LoadFormFields();
}
private void LocalizeModule()
{
this.rfvModuleList.ErrorMessage = this.GetLocalizedString("rfvModuleList.ErrorMessage");
this.rfvAppName.ErrorMessage = this.GetLocalizedString("rfvAppName.ErrorMessage");
this.cmdSave.Text = this.GetLocalizedString("cmdSave.Text");
this.cmdReturn.Text = this.GetLocalizedString("cmdReturn.Text");
this.cmdReceiverFile.Text = this.GetLocalizedString("cmdReceiverFile.Text");
rfvApiSecret.ErrorMessage = GetLocalizedString("rfvApiSecret.ErrorMessage");
}
private void LoadSettings()
{
if (this.Settings["AttachedModuleId"] != null)
this.AttachedModule = int.Parse(this.Settings["AttachedModuleId"].ToString(), NumberStyles.Integer);
if (this.Settings["DisqusView"] != null)
this.DisqusView = this.Settings["DisqusView"].ToString();
if (this.Settings["DisplayItems"] != null)
this.DisplayItems = int.Parse(this.Settings["DisplayItems"].ToString(), NumberStyles.Integer);
if (this.Settings["ShowModerators"] != null)
this.ShowModerators = bool.Parse(this.Settings["ShowModerators"].ToString());
if (this.Settings["ColorTheme"] != null)
this.ColorTheme = this.Settings["ColorTheme"].ToString();
if (this.Settings["DefaultTab"] != null)
this.DefaultTab = this.Settings["DefaultTab"].ToString();
if (this.Settings["CommentLength"] != null)
this.CommentLength = int.Parse(this.Settings["CommentLength"].ToString(), NumberStyles.Integer);
if (this.Settings["ShowAvatar"] != null)
this.ShowAvatar = bool.Parse(this.Settings["ShowAvatar"].ToString());
if (this.Settings["AvatarSize"] != null)
this.AvatarSize = int.Parse(this.Settings["AvatarSize"].ToString(), NumberStyles.Integer);
}
private void LoadFormFields()
{
try
{
if (this.AttachedModule > 0)
this.cboModuleList.Items.FindByValue(this.AttachedModule.ToString()).Selected = true;
}
catch
{
ModuleController ctlModule = new ModuleController();
ctlModule.DeleteModuleSetting(this.ModuleId, "AttachedModuleId");
ModuleController.SynchronizeModule(this.ModuleId);
this.cboModuleList.SelectedIndex = 0;
}
this.txtAppName.Text = DisqusApplicationName;
chkRequireDnnLogin.Checked = RequireDnnLogin;
if (string.IsNullOrEmpty(this.DisqusView))
{
this.cboModuleView.Items.FindByValue("comments").Selected = true;
this.DisqusView = "comments";
}
else
{
this.cboModuleView.Items.FindByValue(this.DisqusView).Selected = true;
}
if (this.DisplayItems > 0)
{
this.cboDisplayItems.Items.FindByValue(this.DisplayItems.ToString()).Selected = true;
}
else
{
this.cboDisplayItems.Items[0].Selected = true;
}
this.chkShowModerators.Checked = this.ShowModerators;
if (string.IsNullOrEmpty(this.ColorTheme))
{
this.cboColorTheme.Items.FindByValue("blue").Selected = true;
}
else
{
this.cboColorTheme.Items.FindByValue(this.ColorTheme).Selected = true;
}
if (string.IsNullOrEmpty(this.DefaultTab))
{
this.cboDefaultTab.Items.FindByValue("people").Selected = true;
}
else
{
this.cboDefaultTab.Items.FindByValue(this.DefaultTab).Selected = true;
}
if (this.CommentLength > 0)
{
this.txtCommentLength.Text = this.CommentLength.ToString();
}
else
{
this.txtCommentLength.Text = "200";
}
this.chkShowAvatar.Checked = this.ShowAvatar;
if (this.AvatarSize > 0)
{
this.cboAvatarSize.Items.FindByValue(this.AvatarSize.ToString()).Selected = true;
}
else
{
this.cboAvatarSize.Items[0].Selected = true;
}
/* SITE-LEVEL SETTINGS */
if (string.IsNullOrEmpty(DisqusApiSecret) == false)
{
txtApiSecret.Text = DisqusApiSecret;
}
if (UserInfo.IsSuperUser)
{
chkSchedule.Checked = ScheduleEnabled;
}
chkDeveloperMode.Checked = DisqusDeveloperMode;
chkSsoEnabled.Checked = DisqusSsoEnabled;
txtSsoApiKey.Text = DisqusSsoApiKey;
this.ChangeView(this.DisqusView);
}
private void SaveSettings()
{
ModuleController ctlModule = new ModuleController();
var sec = new Security.PortalSecurity();
ctlModule.DeleteModuleSettings(this.ModuleId);
ctlModule.DeleteTabModuleSettings(this.TabModuleId);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApplicationName", sec.InputFilter(txtAppName.Text, PortalSecurity.FilterFlag.NoMarkup), true, PortalSettings.CultureCode);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusApiSecret", sec.InputFilter(txtApiSecret.Text, PortalSecurity.FilterFlag.NoMarkup), true, PortalSettings.CultureCode);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusRequireDnnLogin", chkRequireDnnLogin.Checked.ToString(), true, PortalSettings.CultureCode);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusDeveloperMode", chkDeveloperMode.Checked.ToString(), true, PortalSettings.CultureCode);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusSsoEnabled", chkSsoEnabled.Checked.ToString(), true);
Entities.Portals.PortalController.UpdatePortalSetting(PortalId, "wnsDisqusSsoApiKey", sec.InputFilter(txtSsoApiKey.Text, PortalSecurity.FilterFlag.NoMarkup), true);
if (UserInfo.IsSuperUser)
{
// save & apply schedule preferences
ManageSchedulerItem();
}
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DisqusView", this.cboModuleView.SelectedValue);
switch (this.cboModuleView.SelectedValue)
{
case "comments":
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "AttachedModuleId", this.cboModuleList.SelectedValue);
break;
case "combination":
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DisplayItems", this.cboDisplayItems.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "ShowModerators", this.chkShowModerators.Checked.ToString());
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "ColorTheme", this.cboColorTheme.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DefaultTab", this.cboDefaultTab.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "CommentLength", sec.InputFilter(this.txtCommentLength.Text, PortalSecurity.FilterFlag.NoMarkup));
break;
case "recent-comments":
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DisplayItems", this.cboDisplayItems.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "ShowAvatar", this.chkShowAvatar.Checked.ToString());
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "AvatarSize", this.cboAvatarSize.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "CommentLength", sec.InputFilter(this.txtCommentLength.Text, PortalSecurity.FilterFlag.NoMarkup));
break;
case "popular-threads":
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DisplayItems", this.cboDisplayItems.SelectedValue);
break;
case "top-commenters":
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "DisplayItems", this.cboDisplayItems.SelectedValue);
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "ShowModerators", this.chkShowModerators.Checked.ToString());
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "ShowAvatar", this.chkShowAvatar.Checked.ToString());
ctlModule.UpdateTabModuleSetting(this.TabModuleId, "AvatarSize", this.cboAvatarSize.SelectedValue);
break;
}
ModuleController.SynchronizeModule(this.ModuleId);
}
private void SendBackToModule()
{
Response.Redirect(Globals.NavigateURL());
}
private void ChangeView(string newView)
{
switch (newView)
{
case "comments":
this.liModuleList.Visible = true;
this.liDisplayItems.Visible = false;
this.liShowModerators.Visible = false;
this.liColorTheme.Visible = false;
this.liDefaultTab.Visible = false;
this.liCommentLength.Visible = false;
this.liShowAvatar.Visible = false;
this.liAvatarSize.Visible = false;
break;
case "combination":
this.liModuleList.Visible = false;
this.liDisplayItems.Visible = true;
this.liShowModerators.Visible = true;
this.liColorTheme.Visible = true;
this.liDefaultTab.Visible = true;
this.liCommentLength.Visible = true;
this.liShowAvatar.Visible = false;
this.liAvatarSize.Visible = false;
break;
case "recent-comments":
this.liModuleList.Visible = false;
this.liDisplayItems.Visible = true;
this.liShowModerators.Visible = false;
this.liColorTheme.Visible = false;
this.liDefaultTab.Visible = false;
this.liCommentLength.Visible = true;
this.liShowAvatar.Visible = true;
this.liAvatarSize.Visible = true;
break;
case "popular-threads":
this.liModuleList.Visible = false;
this.liDisplayItems.Visible = true;
this.liShowModerators.Visible = false;
this.liColorTheme.Visible = false;
this.liDefaultTab.Visible = false;
this.liCommentLength.Visible = false;
this.liShowAvatar.Visible = false;
this.liAvatarSize.Visible = false;
break;
case "top-commenters":
this.liModuleList.Visible = false;
this.liDisplayItems.Visible = true;
this.liShowModerators.Visible = true;
this.liColorTheme.Visible = false;
this.liDefaultTab.Visible = false;
this.liCommentLength.Visible = false;
this.liShowAvatar.Visible = true;
this.liAvatarSize.Visible = true;
break;
}
}
#region Cross Domain Receiver File
private void CreateReceiverFile()
{
if (this.DoesReceiverFileExist() == false)
{
var strPath = CrossDomainReceiverFilePath();
File.Create(strPath);
Common.Utilities.Config.Touch();
this.BindData();
}
}
private bool DoesReceiverFileExist()
{
var strPath = CrossDomainReceiverFilePath();
return File.Exists(strPath);
}
private string CrossDomainReceiverFilePath()
{
var strPath = string.Concat(this.PortalSettings.HomeDirectoryMapPath, RECEIVER_FILE_NAME);
return strPath.Replace("\"", string.Empty);
}
private string CrossDomainReceiverUrlPath()
{
var strPath = string.Concat("http://", this.PortalSettings.PortalAlias.HTTPAlias, this.PortalSettings.HomeDirectory, RECEIVER_FILE_NAME);
return string.Format(URL_FORMAT, strPath);
}
#endregion
private ScheduleItem CreateScheduleItem()
{
var scheduleItem = new ScheduleItem();
scheduleItem.TypeFullName = FeatureController.DISQUS_COMMENT_SCHEDULE_TYPE;
scheduleItem.FriendlyName = FeatureController.DISQUS_COMMENT_SCHEDULE_NAME;
scheduleItem.TimeLapse = 1;
scheduleItem.TimeLapseMeasurement = "d"; // d == days
scheduleItem.RetryTimeLapse = 1;
scheduleItem.RetryTimeLapseMeasurement = "h"; // h == hours
scheduleItem.RetainHistoryNum = 10;
scheduleItem.AttachToEvent = string.Empty;
scheduleItem.CatchUpEnabled = false;
scheduleItem.Enabled = true;
scheduleItem.ObjectDependencies = string.Empty;
scheduleItem.Servers = string.Empty;
return scheduleItem;
}
private void ManageSchedulerItem()
{
try
{
// update the host setting
HostController.Instance.Update(FeatureController.HOST_SETTING_COMMENT_SCHEDULE, chkSchedule.Checked.ToString());
// get an instance of the scheduler item
ScheduleItem oSchedule = SchedulingProvider.Instance().GetSchedule(FeatureController.DISQUS_COMMENT_SCHEDULE_NAME, string.Empty);
if (chkSchedule.Checked)
{
if (oSchedule == null)
{
// there isn't a scheduler item
// create and enable one
oSchedule = CreateScheduleItem();
SchedulingProvider.Instance().AddSchedule(oSchedule);
}
else
{
// there is a scheduler item
// enable it
oSchedule.Enabled = true;
SchedulingProvider.Instance().UpdateSchedule(oSchedule);
}
}
else
{
if (oSchedule != null)
{
// be sure to disable the scheduler if it exists
oSchedule.Enabled = false;
SchedulingProvider.Instance().UpdateSchedule(oSchedule);
}
}
if (SchedulingProvider.SchedulerMode == SchedulerMode.TIMER_METHOD)
{
SchedulingProvider.Instance().ReStart("Change made to schedule.");
}
}
catch (Exception ex)
{
Exceptions.LogException(ex);
}
}
/*
private bool DoesBlogExist()
{
var oModule = DesktopModuleController.GetDesktopModuleByModuleName("Blog", this.PortalId);
return (oModule != null);
}
*/
#endregion
}
}
| |
// 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.Cloud.Gaming.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedGameServerDeploymentsServiceClientSnippets
{
/// <summary>Snippet for ListGameServerDeployments</summary>
public void ListGameServerDeploymentsRequestObject()
{
// Snippet: ListGameServerDeployments(ListGameServerDeploymentsRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
ListGameServerDeploymentsRequest request = new ListGameServerDeploymentsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerDeploymentsAsync</summary>
public async Task ListGameServerDeploymentsRequestObjectAsync()
{
// Snippet: ListGameServerDeploymentsAsync(ListGameServerDeploymentsRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
ListGameServerDeploymentsRequest request = new ListGameServerDeploymentsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerDeployments</summary>
public void ListGameServerDeployments()
{
// Snippet: ListGameServerDeployments(string, string, int?, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerDeploymentsAsync</summary>
public async Task ListGameServerDeploymentsAsync()
{
// Snippet: ListGameServerDeploymentsAsync(string, string, int?, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerDeployments</summary>
public void ListGameServerDeploymentsResourceNames()
{
// Snippet: ListGameServerDeployments(LocationName, string, int?, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (GameServerDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListGameServerDeploymentsAsync</summary>
public async Task ListGameServerDeploymentsResourceNamesAsync()
{
// Snippet: ListGameServerDeploymentsAsync(LocationName, string, int?, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((GameServerDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (GameServerDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (GameServerDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetGameServerDeployment</summary>
public void GetGameServerDeploymentRequestObject()
{
// Snippet: GetGameServerDeployment(GetGameServerDeploymentRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(request);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentAsync</summary>
public async Task GetGameServerDeploymentRequestObjectAsync()
{
// Snippet: GetGameServerDeploymentAsync(GetGameServerDeploymentRequest, CallSettings)
// Additional: GetGameServerDeploymentAsync(GetGameServerDeploymentRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(request);
// End snippet
}
/// <summary>Snippet for GetGameServerDeployment</summary>
public void GetGameServerDeployment()
{
// Snippet: GetGameServerDeployment(string, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentAsync</summary>
public async Task GetGameServerDeploymentAsync()
{
// Snippet: GetGameServerDeploymentAsync(string, CallSettings)
// Additional: GetGameServerDeploymentAsync(string, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeployment</summary>
public void GetGameServerDeploymentResourceNames()
{
// Snippet: GetGameServerDeployment(GameServerDeploymentName, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentAsync</summary>
public async Task GetGameServerDeploymentResourceNamesAsync()
{
// Snippet: GetGameServerDeploymentAsync(GameServerDeploymentName, CallSettings)
// Additional: GetGameServerDeploymentAsync(GameServerDeploymentName, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(name);
// End snippet
}
/// <summary>Snippet for CreateGameServerDeployment</summary>
public void CreateGameServerDeploymentRequestObject()
{
// Snippet: CreateGameServerDeployment(CreateGameServerDeploymentRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
CreateGameServerDeploymentRequest request = new CreateGameServerDeploymentRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
DeploymentId = "",
GameServerDeployment = new GameServerDeployment(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerDeploymentAsync</summary>
public async Task CreateGameServerDeploymentRequestObjectAsync()
{
// Snippet: CreateGameServerDeploymentAsync(CreateGameServerDeploymentRequest, CallSettings)
// Additional: CreateGameServerDeploymentAsync(CreateGameServerDeploymentRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
CreateGameServerDeploymentRequest request = new CreateGameServerDeploymentRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
DeploymentId = "",
GameServerDeployment = new GameServerDeployment(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerDeployment</summary>
public void CreateGameServerDeployment()
{
// Snippet: CreateGameServerDeployment(string, GameServerDeployment, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
GameServerDeployment gameServerDeployment = new GameServerDeployment();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(parent, gameServerDeployment);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerDeploymentAsync</summary>
public async Task CreateGameServerDeploymentAsync()
{
// Snippet: CreateGameServerDeploymentAsync(string, GameServerDeployment, CallSettings)
// Additional: CreateGameServerDeploymentAsync(string, GameServerDeployment, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
GameServerDeployment gameServerDeployment = new GameServerDeployment();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(parent, gameServerDeployment);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerDeployment</summary>
public void CreateGameServerDeploymentResourceNames()
{
// Snippet: CreateGameServerDeployment(LocationName, GameServerDeployment, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
GameServerDeployment gameServerDeployment = new GameServerDeployment();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(parent, gameServerDeployment);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateGameServerDeploymentAsync</summary>
public async Task CreateGameServerDeploymentResourceNamesAsync()
{
// Snippet: CreateGameServerDeploymentAsync(LocationName, GameServerDeployment, CallSettings)
// Additional: CreateGameServerDeploymentAsync(LocationName, GameServerDeployment, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
GameServerDeployment gameServerDeployment = new GameServerDeployment();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(parent, gameServerDeployment);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeployment</summary>
public void DeleteGameServerDeploymentRequestObject()
{
// Snippet: DeleteGameServerDeployment(DeleteGameServerDeploymentRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
DeleteGameServerDeploymentRequest request = new DeleteGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeploymentAsync</summary>
public async Task DeleteGameServerDeploymentRequestObjectAsync()
{
// Snippet: DeleteGameServerDeploymentAsync(DeleteGameServerDeploymentRequest, CallSettings)
// Additional: DeleteGameServerDeploymentAsync(DeleteGameServerDeploymentRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteGameServerDeploymentRequest request = new DeleteGameServerDeploymentRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeployment</summary>
public void DeleteGameServerDeployment()
{
// Snippet: DeleteGameServerDeployment(string, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeploymentAsync</summary>
public async Task DeleteGameServerDeploymentAsync()
{
// Snippet: DeleteGameServerDeploymentAsync(string, CallSettings)
// Additional: DeleteGameServerDeploymentAsync(string, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeployment</summary>
public void DeleteGameServerDeploymentResourceNames()
{
// Snippet: DeleteGameServerDeployment(GameServerDeploymentName, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteGameServerDeploymentAsync</summary>
public async Task DeleteGameServerDeploymentResourceNamesAsync()
{
// Snippet: DeleteGameServerDeploymentAsync(GameServerDeploymentName, CallSettings)
// Additional: DeleteGameServerDeploymentAsync(GameServerDeploymentName, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeployment</summary>
public void UpdateGameServerDeploymentRequestObject()
{
// Snippet: UpdateGameServerDeployment(UpdateGameServerDeploymentRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
UpdateGameServerDeploymentRequest request = new UpdateGameServerDeploymentRequest
{
GameServerDeployment = new GameServerDeployment(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeployment(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentAsync</summary>
public async Task UpdateGameServerDeploymentRequestObjectAsync()
{
// Snippet: UpdateGameServerDeploymentAsync(UpdateGameServerDeploymentRequest, CallSettings)
// Additional: UpdateGameServerDeploymentAsync(UpdateGameServerDeploymentRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateGameServerDeploymentRequest request = new UpdateGameServerDeploymentRequest
{
GameServerDeployment = new GameServerDeployment(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeployment</summary>
public void UpdateGameServerDeployment()
{
// Snippet: UpdateGameServerDeployment(GameServerDeployment, FieldMask, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeployment gameServerDeployment = new GameServerDeployment();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeployment(gameServerDeployment, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeployment(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentAsync</summary>
public async Task UpdateGameServerDeploymentAsync()
{
// Snippet: UpdateGameServerDeploymentAsync(GameServerDeployment, FieldMask, CallSettings)
// Additional: UpdateGameServerDeploymentAsync(GameServerDeployment, FieldMask, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerDeployment gameServerDeployment = new GameServerDeployment();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentAsync(gameServerDeployment, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRollout</summary>
public void GetGameServerDeploymentRolloutRequestObject()
{
// Snippet: GetGameServerDeploymentRollout(GetGameServerDeploymentRolloutRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(request);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary>
public async Task GetGameServerDeploymentRolloutRequestObjectAsync()
{
// Snippet: GetGameServerDeploymentRolloutAsync(GetGameServerDeploymentRolloutRequest, CallSettings)
// Additional: GetGameServerDeploymentRolloutAsync(GetGameServerDeploymentRolloutRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest
{
GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"),
};
// Make the request
GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(request);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRollout</summary>
public void GetGameServerDeploymentRollout()
{
// Snippet: GetGameServerDeploymentRollout(string, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary>
public async Task GetGameServerDeploymentRolloutAsync()
{
// Snippet: GetGameServerDeploymentRolloutAsync(string, CallSettings)
// Additional: GetGameServerDeploymentRolloutAsync(string, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]";
// Make the request
GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRollout</summary>
public void GetGameServerDeploymentRolloutResourceNames()
{
// Snippet: GetGameServerDeploymentRollout(GameServerDeploymentName, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(name);
// End snippet
}
/// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary>
public async Task GetGameServerDeploymentRolloutResourceNamesAsync()
{
// Snippet: GetGameServerDeploymentRolloutAsync(GameServerDeploymentName, CallSettings)
// Additional: GetGameServerDeploymentRolloutAsync(GameServerDeploymentName, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]");
// Make the request
GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentRollout</summary>
public void UpdateGameServerDeploymentRolloutRequestObject()
{
// Snippet: UpdateGameServerDeploymentRollout(UpdateGameServerDeploymentRolloutRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
UpdateGameServerDeploymentRolloutRequest request = new UpdateGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRollout(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRollout(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentRolloutAsync</summary>
public async Task UpdateGameServerDeploymentRolloutRequestObjectAsync()
{
// Snippet: UpdateGameServerDeploymentRolloutAsync(UpdateGameServerDeploymentRolloutRequest, CallSettings)
// Additional: UpdateGameServerDeploymentRolloutAsync(UpdateGameServerDeploymentRolloutRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateGameServerDeploymentRolloutRequest request = new UpdateGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRolloutAsync(request);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRolloutAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentRollout</summary>
public void UpdateGameServerDeploymentRollout()
{
// Snippet: UpdateGameServerDeploymentRollout(GameServerDeploymentRollout, FieldMask, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
GameServerDeploymentRollout rollout = new GameServerDeploymentRollout();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRollout(rollout, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRollout(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateGameServerDeploymentRolloutAsync</summary>
public async Task UpdateGameServerDeploymentRolloutAsync()
{
// Snippet: UpdateGameServerDeploymentRolloutAsync(GameServerDeploymentRollout, FieldMask, CallSettings)
// Additional: UpdateGameServerDeploymentRolloutAsync(GameServerDeploymentRollout, FieldMask, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
GameServerDeploymentRollout rollout = new GameServerDeploymentRollout();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRolloutAsync(rollout, updateMask);
// Poll until the returned long-running operation is complete
Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
GameServerDeployment result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRolloutAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
GameServerDeployment retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for PreviewGameServerDeploymentRollout</summary>
public void PreviewGameServerDeploymentRolloutRequestObject()
{
// Snippet: PreviewGameServerDeploymentRollout(PreviewGameServerDeploymentRolloutRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewGameServerDeploymentRolloutResponse response = gameServerDeploymentsServiceClient.PreviewGameServerDeploymentRollout(request);
// End snippet
}
/// <summary>Snippet for PreviewGameServerDeploymentRolloutAsync</summary>
public async Task PreviewGameServerDeploymentRolloutRequestObjectAsync()
{
// Snippet: PreviewGameServerDeploymentRolloutAsync(PreviewGameServerDeploymentRolloutRequest, CallSettings)
// Additional: PreviewGameServerDeploymentRolloutAsync(PreviewGameServerDeploymentRolloutRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest
{
Rollout = new GameServerDeploymentRollout(),
UpdateMask = new FieldMask(),
PreviewTime = new Timestamp(),
};
// Make the request
PreviewGameServerDeploymentRolloutResponse response = await gameServerDeploymentsServiceClient.PreviewGameServerDeploymentRolloutAsync(request);
// End snippet
}
/// <summary>Snippet for FetchDeploymentState</summary>
public void FetchDeploymentStateRequestObject()
{
// Snippet: FetchDeploymentState(FetchDeploymentStateRequest, CallSettings)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create();
// Initialize request argument(s)
FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "", };
// Make the request
FetchDeploymentStateResponse response = gameServerDeploymentsServiceClient.FetchDeploymentState(request);
// End snippet
}
/// <summary>Snippet for FetchDeploymentStateAsync</summary>
public async Task FetchDeploymentStateRequestObjectAsync()
{
// Snippet: FetchDeploymentStateAsync(FetchDeploymentStateRequest, CallSettings)
// Additional: FetchDeploymentStateAsync(FetchDeploymentStateRequest, CancellationToken)
// Create client
GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync();
// Initialize request argument(s)
FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "", };
// Make the request
FetchDeploymentStateResponse response = await gameServerDeploymentsServiceClient.FetchDeploymentStateAsync(request);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
using Orleans.Runtime;
namespace Orleans.Serialization
{
internal static class BinaryTokenStreamWriterExtensions
{
internal static void Write(this IBinaryTokenStreamWriter @this, SerializationTokenType t)
{
@this.Write((byte)t);
}
/// <summary> Write a <c>CorrelationId</c> value to the stream. </summary>
internal static void Write(this IBinaryTokenStreamWriter @this, CorrelationId id)
{
@this.Write(id.ToByteArray());
}
/// <summary> Write a <c>ActivationAddress</c> value to the stream. </summary>
internal static void Write(this IBinaryTokenStreamWriter @this, ActivationAddress addr)
{
@this.Write(addr.Silo ?? SiloAddress.Zero);
// GrainId must not be null
@this.Write(addr.Grain);
@this.Write(addr.Activation ?? ActivationId.Zero);
}
internal static void Write(this IBinaryTokenStreamWriter @this, UniqueKey key)
{
@this.Write(key.N0);
@this.Write(key.N1);
@this.Write(key.TypeCodeData);
@this.Write(key.KeyExt);
}
/// <summary> Write a <c>ActivationId</c> value to the stream. </summary>
internal static void Write(this IBinaryTokenStreamWriter @this, ActivationId id)
{
@this.Write(id.Key);
}
/// <summary> Write a <c>GrainId</c> value to the stream. </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
internal static void Write(this IBinaryTokenStreamWriter @this, GrainId id)
{
@this.Write(id.Key);
}
/// <summary>
/// Write header for an <c>Array</c> to the output stream.
/// </summary>
/// <param name="this">The IBinaryTokenStreamReader to read from</param>
/// <param name="a">Data object for which header should be written.</param>
/// <param name="expected">The most recent Expected Type currently active for this stream.</param>
internal static void WriteArrayHeader(this IBinaryTokenStreamWriter @this, Array a, Type expected = null)
{
@this.WriteTypeHeader(a.GetType(), expected);
for (var i = 0; i < a.Rank; i++)
{
@this.Write(a.GetLength(i));
}
}
// Back-references
internal static void WriteReference(this IBinaryTokenStreamWriter @this, int offset)
{
@this.Write((byte)SerializationTokenType.Reference);
@this.Write(offset);
}
}
/// <summary>
/// Writer for Orleans binary token streams
/// </summary>
public class BinaryTokenStreamWriter : IBinaryTokenStreamWriter
{
private readonly ByteArrayBuilder ab;
private static readonly Dictionary<RuntimeTypeHandle, SerializationTokenType> typeTokens;
private static readonly Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>> writers;
static BinaryTokenStreamWriter()
{
typeTokens = new Dictionary<RuntimeTypeHandle, SerializationTokenType>(RuntimeTypeHandlerEqualityComparer.Instance);
typeTokens[typeof(bool).TypeHandle] = SerializationTokenType.Boolean;
typeTokens[typeof(int).TypeHandle] = SerializationTokenType.Int;
typeTokens[typeof(uint).TypeHandle] = SerializationTokenType.Uint;
typeTokens[typeof(short).TypeHandle] = SerializationTokenType.Short;
typeTokens[typeof(ushort).TypeHandle] = SerializationTokenType.Ushort;
typeTokens[typeof(long).TypeHandle] = SerializationTokenType.Long;
typeTokens[typeof(ulong).TypeHandle] = SerializationTokenType.Ulong;
typeTokens[typeof(byte).TypeHandle] = SerializationTokenType.Byte;
typeTokens[typeof(sbyte).TypeHandle] = SerializationTokenType.Sbyte;
typeTokens[typeof(float).TypeHandle] = SerializationTokenType.Float;
typeTokens[typeof(double).TypeHandle] = SerializationTokenType.Double;
typeTokens[typeof(decimal).TypeHandle] = SerializationTokenType.Decimal;
typeTokens[typeof(string).TypeHandle] = SerializationTokenType.String;
typeTokens[typeof(char).TypeHandle] = SerializationTokenType.Character;
typeTokens[typeof(Guid).TypeHandle] = SerializationTokenType.Guid;
typeTokens[typeof(DateTime).TypeHandle] = SerializationTokenType.Date;
typeTokens[typeof(TimeSpan).TypeHandle] = SerializationTokenType.TimeSpan;
typeTokens[typeof(GrainId).TypeHandle] = SerializationTokenType.GrainId;
typeTokens[typeof(ActivationId).TypeHandle] = SerializationTokenType.ActivationId;
typeTokens[typeof(SiloAddress).TypeHandle] = SerializationTokenType.SiloAddress;
typeTokens[typeof(ActivationAddress).TypeHandle] = SerializationTokenType.ActivationAddress;
typeTokens[typeof(IPAddress).TypeHandle] = SerializationTokenType.IpAddress;
typeTokens[typeof(IPEndPoint).TypeHandle] = SerializationTokenType.IpEndPoint;
typeTokens[typeof(CorrelationId).TypeHandle] = SerializationTokenType.CorrelationId;
typeTokens[typeof(InvokeMethodRequest).TypeHandle] = SerializationTokenType.Request;
typeTokens[typeof(Response).TypeHandle] = SerializationTokenType.Response;
typeTokens[typeof(Dictionary<string, object>).TypeHandle] = SerializationTokenType.StringObjDict;
typeTokens[typeof(Object).TypeHandle] = SerializationTokenType.Object;
typeTokens[typeof(List<>).TypeHandle] = SerializationTokenType.List;
typeTokens[typeof(SortedList<,>).TypeHandle] = SerializationTokenType.SortedList;
typeTokens[typeof(Dictionary<,>).TypeHandle] = SerializationTokenType.Dictionary;
typeTokens[typeof(HashSet<>).TypeHandle] = SerializationTokenType.Set;
typeTokens[typeof(SortedSet<>).TypeHandle] = SerializationTokenType.SortedSet;
typeTokens[typeof(KeyValuePair<,>).TypeHandle] = SerializationTokenType.KeyValuePair;
typeTokens[typeof(LinkedList<>).TypeHandle] = SerializationTokenType.LinkedList;
typeTokens[typeof(Stack<>).TypeHandle] = SerializationTokenType.Stack;
typeTokens[typeof(Queue<>).TypeHandle] = SerializationTokenType.Queue;
typeTokens[typeof(Tuple<>).TypeHandle] = SerializationTokenType.Tuple + 1;
typeTokens[typeof(Tuple<,>).TypeHandle] = SerializationTokenType.Tuple + 2;
typeTokens[typeof(Tuple<,,>).TypeHandle] = SerializationTokenType.Tuple + 3;
typeTokens[typeof(Tuple<,,,>).TypeHandle] = SerializationTokenType.Tuple + 4;
typeTokens[typeof(Tuple<,,,,>).TypeHandle] = SerializationTokenType.Tuple + 5;
typeTokens[typeof(Tuple<,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 6;
typeTokens[typeof(Tuple<,,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 7;
writers = new Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>>(RuntimeTypeHandlerEqualityComparer.Instance);
writers[typeof(bool).TypeHandle] = (stream, obj) => stream.Write((bool) obj);
writers[typeof(int).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Int); stream.Write((int) obj); };
writers[typeof(uint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Uint); stream.Write((uint) obj); };
writers[typeof(short).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Short); stream.Write((short) obj); };
writers[typeof(ushort).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ushort); stream.Write((ushort) obj); };
writers[typeof(long).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Long); stream.Write((long) obj); };
writers[typeof(ulong).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ulong); stream.Write((ulong) obj); };
writers[typeof(byte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Byte); stream.Write((byte) obj); };
writers[typeof(sbyte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Sbyte); stream.Write((sbyte) obj); };
writers[typeof(float).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Float); stream.Write((float) obj); };
writers[typeof(double).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Double); stream.Write((double) obj); };
writers[typeof(decimal).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Decimal); stream.Write((decimal)obj); };
writers[typeof(string).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.String); stream.Write((string)obj); };
writers[typeof(char).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Character); stream.Write((char) obj); };
writers[typeof(Guid).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Guid); stream.Write((Guid) obj); };
writers[typeof(DateTime).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Date); stream.Write((DateTime) obj); };
writers[typeof(TimeSpan).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.TimeSpan); stream.Write((TimeSpan) obj); };
writers[typeof(GrainId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.GrainId); stream.Write((GrainId) obj); };
writers[typeof(ActivationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationId); stream.Write((ActivationId) obj); };
writers[typeof(SiloAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.SiloAddress); stream.Write((SiloAddress) obj); };
writers[typeof(ActivationAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationAddress); stream.Write((ActivationAddress) obj); };
writers[typeof(IPAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpAddress); stream.Write((IPAddress) obj); };
writers[typeof(IPEndPoint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpEndPoint); stream.Write((IPEndPoint) obj); };
writers[typeof(CorrelationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.CorrelationId); stream.Write((CorrelationId) obj); };
}
/// <summary> Default constructor. </summary>
public BinaryTokenStreamWriter()
{
ab = new ByteArrayBuilder();
Trace("Starting new binary token stream");
}
/// <summary> Return the output stream as a set of <c>ArraySegment</c>. </summary>
/// <returns>Data from this stream, converted to output type.</returns>
public List<ArraySegment<byte>> ToBytes()
{
return ab.ToBytes();
}
/// <summary> Return the output stream as a <c>byte[]</c>. </summary>
/// <returns>Data from this stream, converted to output type.</returns>
public byte[] ToByteArray()
{
return ab.ToByteArray();
}
/// <summary> Release any serialization buffers being used by this stream. </summary>
public void ReleaseBuffers()
{
ab.ReleaseBuffers();
}
/// <summary> Current write position in the stream. </summary>
public int CurrentOffset { get { return ab.Length; } }
// Numbers
/// <summary> Write an <c>Int32</c> value to the stream. </summary>
public void Write(int i)
{
Trace("--Wrote integer {0}", i);
ab.Append(i);
}
/// <summary> Write an <c>Int16</c> value to the stream. </summary>
public void Write(short s)
{
Trace("--Wrote short {0}", s);
ab.Append(s);
}
/// <summary> Write an <c>Int64</c> value to the stream. </summary>
public void Write(long l)
{
Trace("--Wrote long {0}", l);
ab.Append(l);
}
/// <summary> Write a <c>sbyte</c> value to the stream. </summary>
public void Write(sbyte b)
{
Trace("--Wrote sbyte {0}", b);
ab.Append(b);
}
/// <summary> Write a <c>UInt32</c> value to the stream. </summary>
public void Write(uint u)
{
Trace("--Wrote uint {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>UInt16</c> value to the stream. </summary>
public void Write(ushort u)
{
Trace("--Wrote ushort {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>UInt64</c> value to the stream. </summary>
public void Write(ulong u)
{
Trace("--Wrote ulong {0}", u);
ab.Append(u);
}
/// <summary> Write a <c>byte</c> value to the stream. </summary>
public void Write(byte b)
{
Trace("--Wrote byte {0}", b);
ab.Append(b);
}
/// <summary> Write a <c>float</c> value to the stream. </summary>
public void Write(float f)
{
Trace("--Wrote float {0}", f);
ab.Append(f);
}
/// <summary> Write a <c>double</c> value to the stream. </summary>
public void Write(double d)
{
Trace("--Wrote double {0}", d);
ab.Append(d);
}
/// <summary> Write a <c>decimal</c> value to the stream. </summary>
public void Write(decimal d)
{
Trace("--Wrote decimal {0}", d);
ab.Append(Decimal.GetBits(d));
}
// Text
/// <summary> Write a <c>string</c> value to the stream. </summary>
public void Write(string s)
{
Trace("--Wrote string '{0}'", s);
if (null == s)
{
ab.Append(-1);
}
else
{
var bytes = Encoding.UTF8.GetBytes(s);
ab.Append(bytes.Length);
ab.Append(bytes);
}
}
/// <summary> Write a <c>char</c> value to the stream. </summary>
public void Write(char c)
{
Trace("--Wrote char {0}", c);
ab.Append(Convert.ToInt16(c));
}
// Other primitives
/// <summary> Write a <c>bool</c> value to the stream. </summary>
public void Write(bool b)
{
Trace("--Wrote Boolean {0}", b);
ab.Append((byte)(b ? SerializationTokenType.True : SerializationTokenType.False));
}
/// <summary> Write a <c>null</c> value to the stream. </summary>
public void WriteNull()
{
Trace("--Wrote null");
ab.Append((byte)SerializationTokenType.Null);
}
// Types
/// <summary> Write a type header for the specified Type to the stream. </summary>
/// <param name="t">Type to write header for.</param>
/// <param name="expected">Currently expected Type for this stream.</param>
public void WriteTypeHeader(Type t, Type expected = null)
{
Trace("-Writing type header for type {0}, expected {1}", t, expected);
if (t == expected)
{
ab.Append((byte)SerializationTokenType.ExpectedType);
return;
}
ab.Append((byte) SerializationTokenType.SpecifiedType);
if (t.IsArray)
{
ab.Append((byte)(SerializationTokenType.Array + (byte)t.GetArrayRank()));
WriteTypeHeader(t.GetElementType());
return;
}
SerializationTokenType token;
if (typeTokens.TryGetValue(t.TypeHandle, out token))
{
ab.Append((byte) token);
return;
}
if (t.IsGenericType)
{
if (typeTokens.TryGetValue(t.GetGenericTypeDefinition().TypeHandle, out token))
{
ab.Append((byte)token);
foreach (var tp in t.GetGenericArguments())
{
WriteTypeHeader(tp);
}
return;
}
}
ab.Append((byte)SerializationTokenType.NamedType);
var typeKey = t.OrleansTypeKey();
ab.Append(typeKey.Length);
ab.Append(typeKey);
}
// Primitive arrays
/// <summary> Write a <c>byte[]</c> value to the stream. </summary>
public void Write(byte[] b)
{
Trace("--Wrote byte array of length {0}", b.Length);
ab.Append(b);
}
/// <summary> Write a list of byte array segments to the stream. </summary>
public void Write(List<ArraySegment<byte>> bytes)
{
ab.Append(bytes);
}
/// <summary> Write the specified number of bytes to the stream, starting at the specified offset in the input <c>byte[]</c>. </summary>
/// <param name="b">The input data to be written.</param>
/// <param name="offset">The offset into the inout byte[] to start writing bytes from.</param>
/// <param name="count">The number of bytes to be written.</param>
public void Write(byte[] b, int offset, int count)
{
if (count <= 0)
{
return;
}
Trace("--Wrote byte array of length {0}", count);
if ((offset == 0) && (count == b.Length))
{
Write(b);
}
else
{
var temp = new byte[count];
Buffer.BlockCopy(b, offset, temp, 0, count);
Write(temp);
}
}
/// <summary> Write a <c>Int16[]</c> value to the stream. </summary>
public void Write(short[] i)
{
Trace("--Wrote short array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>Int32[]</c> value to the stream. </summary>
public void Write(int[] i)
{
Trace("--Wrote short array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>Int64[]</c> value to the stream. </summary>
public void Write(long[] l)
{
Trace("--Wrote long array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>UInt16[]</c> value to the stream. </summary>
public void Write(ushort[] i)
{
Trace("--Wrote ushort array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>UInt32[]</c> value to the stream. </summary>
public void Write(uint[] i)
{
Trace("--Wrote uint array of length {0}", i.Length);
ab.Append(i);
}
/// <summary> Write a <c>UInt64[]</c> value to the stream. </summary>
public void Write(ulong[] l)
{
Trace("--Wrote ulong array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>sbyte[]</c> value to the stream. </summary>
public void Write(sbyte[] l)
{
Trace("--Wrote sbyte array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>char[]</c> value to the stream. </summary>
public void Write(char[] l)
{
Trace("--Wrote char array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>bool[]</c> value to the stream. </summary>
public void Write(bool[] l)
{
Trace("--Wrote bool array of length {0}", l.Length);
ab.Append(l);
}
/// <summary> Write a <c>double[]</c> value to the stream. </summary>
public void Write(double[] d)
{
Trace("--Wrote double array of length {0}", d.Length);
ab.Append(d);
}
/// <summary> Write a <c>float[]</c> value to the stream. </summary>
public void Write(float[] f)
{
Trace("--Wrote float array of length {0}", f.Length);
ab.Append(f);
}
// Other simple types
/// <summary> Write a <c>IPEndPoint</c> value to the stream. </summary>
public void Write(IPEndPoint ep)
{
Write(ep.Address);
Write(ep.Port);
}
/// <summary> Write a <c>IPAddress</c> value to the stream. </summary>
public void Write(IPAddress ip)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
for (var i = 0; i < 12; i++)
{
Write((byte)0);
}
Write(ip.GetAddressBytes()); // IPv4 -- 4 bytes
}
else
{
Write(ip.GetAddressBytes()); // IPv6 -- 16 bytes
}
}
/// <summary> Write a <c>SiloAddress</c> value to the stream. </summary>
public void Write(SiloAddress addr)
{
Write(addr.Endpoint);
Write(addr.Generation);
}
/// <summary> Write a <c>TimeSpan</c> value to the stream. </summary>
public void Write(TimeSpan ts)
{
Write(ts.Ticks);
}
/// <summary> Write a <c>DataTime</c> value to the stream. </summary>
public void Write(DateTime dt)
{
Write(dt.ToBinary());
}
/// <summary> Write a <c>Guid</c> value to the stream. </summary>
public void Write(Guid id)
{
Write(id.ToByteArray());
}
/// <summary>
/// Try to write a simple type (non-array) value to the stream.
/// </summary>
/// <param name="obj">Input object to be written to the output stream.</param>
/// <returns>Returns <c>true</c> if the value was successfully written to the output stream.</returns>
public bool TryWriteSimpleObject(object obj)
{
if (obj == null)
{
WriteNull();
return true;
}
Action<BinaryTokenStreamWriter, object> writer;
if (writers.TryGetValue(obj.GetType().TypeHandle, out writer))
{
writer(this, obj);
return true;
}
return false;
}
// General containers
private StreamWriter trace;
[Conditional("TRACE_SERIALIZATION")]
private void Trace(string format, params object[] args)
{
if (trace == null)
{
var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks);
Console.WriteLine("Opening trace file at '{0}'", path);
trace = File.CreateText(path);
}
trace.Write(format, args);
trace.WriteLine(" at offset {0}", CurrentOffset);
trace.Flush();
}
}
}
| |
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FluentBehave;
using Neutrino.Api.Specs.Infrastructure;
using Neutrino.Entities.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;
namespace Neutrino.Api.Specs.Implementations.Services
{
[Feature("ServicesPost", "Registering new service")]
public class ServicesPost
{
private string _serviceId;
private string _serviceType;
private string _serviceAddress;
private int _healthInterval;
private string _healthEndpoint;
private int _deregisterCriticalServiceAfter;
private HealthCheckType _healthCheckType;
private HttpResponseMessage _response;
[Scenario("Service have to be registered successfully when all required properties are given")]
public async Task ServiceHaveToBeRegisteredSuccessfullyWhenAllRequiredPropertiesAreGiven()
{
GivenServiceWithId("new-service-01");
GivenServiceWithServiceType("New Service 01");
GivenServiceWithAddress("http://localhost:8200");
GivenServiceHealthCheckTypeIs("None");
await WhenServiceIsRegistering();
ThenResponseCodeIs(201);
ThenLocationIsReturnedInHeaders("api/services/new-service-01");
await ThenServiceWasRegistered("new-service-01");
}
[Scenario("Service cannot be registered when id is not specified")]
public async Task ServiceCannotBeRegisteredWhenIdIsNotSpecified()
{
GivenServiceWithId("");
GivenServiceWithServiceType("New Service 02");
GivenServiceWithAddress("http://localhost:8200");
GivenServiceHealthCheckTypeIs("None");
await WhenServiceIsRegistering();
ThenResponseCodeIs(400);
await ThenErrorMessageContainsMessage("Service id wasn't specified");
}
[Scenario("Service cannot be registered when type is not specified")]
public async Task ServiceCannotBeRegisteredWhenTypeIsNotSpecified()
{
GivenServiceWithId("new-service-03");
GivenServiceWithServiceType("");
GivenServiceWithAddress("http://localhost:8200");
GivenServiceHealthCheckTypeIs("None");
await WhenServiceIsRegistering();
ThenResponseCodeIs(400);
await ThenErrorMessageContainsMessage("Service type wasn't specified");
}
[Scenario("Service cannot be registered when address is not specified")]
public async Task ServiceCannotBeRegisteredWhenAddressIsNotSpecified()
{
GivenServiceWithId("new-service-04");
GivenServiceWithServiceType("New Service 04");
GivenServiceWithAddress("");
GivenServiceHealthCheckTypeIs("None");
await WhenServiceIsRegistering();
ThenResponseCodeIs(400);
await ThenErrorMessageContainsMessage("Service address wasn't specified");
}
[Scenario("After registering helth of service should be passing when service is alive")]
public async Task AfterRegisteringHelthOfServiceShouldBePassingWhenServiceIsAlive()
{
GivenServiceWithId("new-service-05");
GivenServiceWithServiceType("New Service 05");
GivenServiceWithAddress("http://httpbin.org");
GivenServiceHealthCheckTypeIs("HttpRest");
GivenHelthEndpointIs("http://httpbin.org/get");
GivenHelthIntervalIs(30);
GivenDeregisteringCriticalServiceIs(60);
await WhenServiceIsRegistering();
ThenResponseCodeIs(201);
await ThenServiceHealthIs("Passing");
}
[Scenario("After registering helth of service should be unknown when health check type is None")]
public async Task AfterRegisteringHelthOfServiceShouldBeUnknownWhenHealthCheckTypeIsNone()
{
GivenServiceWithId("new-service-06");
GivenServiceWithServiceType("New Service 06");
GivenServiceWithAddress("http://httpbin.org");
GivenServiceHealthCheckTypeIs("None");
GivenHelthEndpointIs("http://httpbin.org/get");
GivenHelthIntervalIs(30);
await WhenServiceIsRegistering();
ThenResponseCodeIs(201);
await ThenServiceHealthIs("Unknown");
}
[Scenario("After registering helth of service should be error when service return 400")]
public async Task AfterRegisteringHelthOfServiceShouldBeErrorWhenServiceReturn400()
{
GivenServiceWithId("new-service-07");
GivenServiceWithServiceType("New Service 07");
GivenServiceWithAddress("http://httpbin.org");
GivenServiceHealthCheckTypeIs("HttpRest");
GivenHelthEndpointIs("http://httpbin.org/status/400");
GivenHelthIntervalIs(30);
GivenDeregisteringCriticalServiceIs(60);
await WhenServiceIsRegistering();
ThenResponseCodeIs(201);
await ThenServiceHealthIs("Error");
}
[Scenario("After registering helth of service should be critical when service is not responding")]
public async Task AfterRegisteringHelthOfServiceShouldBeCriticalWhenServiceIsNotResponding()
{
GivenServiceWithId("new-service-08");
GivenServiceWithServiceType("New Service 08");
GivenServiceWithAddress("http://notexistingaddress-qazwsx123.org");
GivenServiceHealthCheckTypeIs("HttpRest");
GivenHelthEndpointIs("http://notexistingaddress-qazwsx123.org/health");
GivenHelthIntervalIs(30);
GivenDeregisteringCriticalServiceIs(60);
await WhenServiceIsRegistering();
ThenResponseCodeIs(201);
await ThenServiceHealthIs("Critical");
}
[Scenario("Service cannot be registered when service with same id exists")]
public async Task ServiceCannotBeRegisteredWhenServiceWithSameIdExists()
{
await GivenServiceWithIdNameAddressAndTypeExists("new-service-09", "New Service 01", "http://localhost:8200", "None");
await WhenServiceWithIdIsRegistering("new-service-09");
ThenResponseCodeIs(400);
await ThenErrorMessageContainsMessage("Service with id 'new-service-09' already exists.");
}
[Scenario("Service cannot be registered when id contains unacceptable characters")]
public async Task ServiceCannotBeRegisteredWhenIdContainsUnacceptableCharacters()
{
GivenServiceWithId("this $%^ service");
GivenServiceWithServiceType("New Service 10");
GivenServiceWithAddress("http://localhost:8200");
GivenServiceHealthCheckTypeIs("None");
await WhenServiceIsRegistering();
ThenResponseCodeIs(400);
await ThenErrorMessageContainsMessage("Service id contains unacceptable characters (only alphanumeric letters and dash is acceptable).");
}
[Given("Service with id (.*)")]
private void GivenServiceWithId(string id)
{
_serviceId = id;
}
[Given("Service with name (.*)")]
private void GivenServiceWithServiceType(string serviceType)
{
_serviceType = serviceType;
}
[Given("Service with address (.*)")]
private void GivenServiceWithAddress(string serviceAddress)
{
_serviceAddress = serviceAddress;
}
[Given("Helth interval is (.*)")]
private void GivenHelthIntervalIs(int healthInterval)
{
_healthInterval = healthInterval;
}
[Given("Helth endpoint is (.*)")]
private void GivenHelthEndpointIs(string healthEndpoint)
{
_healthEndpoint = healthEndpoint;
}
[Given("Service health check type is (.*)")]
private void GivenServiceHealthCheckTypeIs(string healthCheckType)
{
SetHealthCheckType(healthCheckType);
}
[Given("Deregistering critical service is (.*)")]
private void GivenDeregisteringCriticalServiceIs(int deregisterCriticalServiceAfter)
{
_deregisterCriticalServiceAfter = deregisterCriticalServiceAfter;
}
[Given("Service with id (.*) name (.*) address (.*) and type (.*) exists")]
public async Task GivenServiceWithIdNameAddressAndTypeExists(string serviceId, string serviceType, string address, string healthCheckType)
{
_serviceId = serviceId;
_serviceType = serviceType;
_serviceAddress = address;
SetHealthCheckType(healthCheckType);
await RegisterService();
Assert.Equal(HttpStatusCode.Created, _response.StatusCode);
}
[When("Service is registering")]
private async Task WhenServiceIsRegistering()
{
await RegisterService();
}
[When("Service with id (.*) is registering")]
private async Task WhenServiceWithIdIsRegistering(string serviceId)
{
_serviceId = serviceId;
await RegisterService();
}
[Then("Response code is (.*)")]
private void ThenResponseCodeIs(int statusCode)
{
Assert.Equal(statusCode, (int) _response.StatusCode);
}
[Then("Location (.*) is returned in headers")]
private void ThenLocationIsReturnedInHeaders(string location)
{
var locationInHeader = _response.Headers.GetValues("location").FirstOrDefault();
Assert.Equal(location, locationInHeader);
}
[Then("Service (.*) was registered")]
private async Task ThenServiceWasRegistered(string serviceId)
{
var httpClient = ApiTestServer.GetHttpClient();
var serviceResponse = await httpClient.GetStringAsync($"/api/services/{serviceId}");
var service = JsonConvert.DeserializeObject<Service>(serviceResponse);
Assert.NotNull(service);
}
[Then("Error message contains message (.*)")]
private async Task ThenErrorMessageContainsMessage(string errorMessage)
{
var response = await _response.Content.ReadAsStringAsync();
Assert.True(response.Contains(errorMessage));
}
[Then("Service health is (.*)")]
private async Task ThenServiceHealthIs(string healthStatus)
{
Thread.Sleep(2000);
var httpClient = ApiTestServer.GetHttpClient();
var httpResponseMessage = await httpClient.GetAsync($"/api/services/{_serviceId}/health/current");
var response = await httpResponseMessage.Content.ReadAsStringAsync();
dynamic parsedResponse = JObject.Parse(response);
Assert.Equal(healthStatus, (string) parsedResponse.healthState);
}
private async Task RegisterService()
{
var service = new Service
{
Id = _serviceId,
ServiceType = _serviceType,
Address = _serviceAddress,
HealthCheck = new HealthCheck
{
HealthCheckType = _healthCheckType,
Address = _healthEndpoint,
Interval = _healthInterval,
DeregisterCriticalServiceAfter = _deregisterCriticalServiceAfter
}
};
var jsonString = JsonConvert.SerializeObject(service);
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var httpClient = ApiTestServer.GetHttpClient();
_response = await httpClient.PostAsync("/api/services", httpContent);
}
private void SetHealthCheckType(string healthCheckType)
{
if (healthCheckType == "None")
{
_healthCheckType = HealthCheckType.None;
}
else if (healthCheckType == "HttpRest")
{
_healthCheckType = HealthCheckType.HttpRest;
}
}
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: 476843 $
* $Date: 2006-11-19 17:07:45 +0100 (dim., 19 nov. 2006) $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
********************************************************************************/
#endregion
using System.Collections;
//#if dotnet2
using System.Collections.Generic;
//#endif
using IBatisNet.DataMapper.Commands;
using IBatisNet.DataMapper.Configuration.Statements;
namespace IBatisNet.DataMapper.MappedStatements
{
/// <summary>
/// ExecuteEventHandler.
/// </summary>
public delegate void ExecuteEventHandler(object sender, ExecuteEventArgs e);
/// <summary>
/// IMappedStatement.
/// </summary>
public interface IMappedStatement
{
#region Event
/// <summary>
/// Event launch on exceute query
/// </summary>
event ExecuteEventHandler Execute;
#endregion
#region Properties
/// <summary>
/// The IPreparedCommand to use
/// </summary>
IPreparedCommand PreparedCommand
{
get;
}
/// <summary>
/// Name used to identify the MappedStatement amongst the others.
/// This the name of the SQL statment by default.
/// </summary>
string Id
{
get;
}
/// <summary>
/// The SQL statment used by this MappedStatement
/// </summary>
IStatement Statement
{
get;
}
/// <summary>
/// The SqlMap used by this MappedStatement
/// </summary>
ISqlMapper SqlMap
{
get;
}
#endregion
#region ExecuteQueryForMap
/// <summary>
/// Executes the SQL and retuns all rows selected in a map that is keyed on the property named
/// in the keyProperty parameter. The value at each key will be the value of the property specified
/// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
///<exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
IDictionary ExecuteQueryForMap(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty);
#endregion
#region ExecuteQueryForMap .NET 2.0
//#if dotnet2
/// <summary>
/// Executes the SQL and retuns all rows selected in a map that is keyed on the property named
/// in the keyProperty parameter. The value at each key will be the value of the property specified
/// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <returns>A IDictionary of object containing the rows keyed by keyProperty.</returns>
///<exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
IDictionary<K, V> ExecuteQueryForDictionary<K, V>(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty);
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <param name="rowDelegate">A delegate called once per row in the QueryForDictionary method</param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
/// <exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
IDictionary<K, V> ExecuteQueryForDictionary<K, V>(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate<K, V> rowDelegate);
//#endif
#endregion
#region ExecuteUpdate
/// <summary>
/// Execute an update statement. Also used for delete statement.
/// Return the number of row effected.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>The number of row effected.</returns>
int ExecuteUpdate(ISqlMapSession session, object parameterObject);
#endregion
#region ExecuteInsert
/// <summary>
/// Execute an insert statement. Fill the parameter object with
/// the ouput parameters if any, also could return the insert generated key
/// </summary>
/// <param name="session">The session</param>
/// <param name="parameterObject">The parameter object used to fill the statement.</param>
/// <returns>Can return the insert generated key.</returns>
object ExecuteInsert(ISqlMapSession session, object parameterObject);
#endregion
#region ExecuteQueryForList
/// <summary>
/// Executes the SQL and and fill a strongly typed collection.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">A strongly typed collection of result objects.</param>
void ExecuteQueryForList(ISqlMapSession session, object parameterObject, IList resultObject);
/// <summary>
/// Executes the SQL and retuns a subset of the rows selected.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="skipResults">The number of rows to skip over.</param>
/// <param name="maxResults">The maximum number of rows to return.</param>
/// <returns>A List of result objects.</returns>
IList ExecuteQueryForList(ISqlMapSession session, object parameterObject, int skipResults, int maxResults);
/// <summary>
/// Executes the SQL and retuns all rows selected. This is exactly the same as
/// calling ExecuteQueryForList(session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS).
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>A List of result objects.</returns>
IList ExecuteQueryForList(ISqlMapSession session, object parameterObject);
#endregion
#region ExecuteQueryForList .NET 2.0
//#if dotnet2
/// <summary>
/// Executes the SQL and and fill a strongly typed collection.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">A strongly typed collection of result objects.</param>
void ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject, IList<T> resultObject);
/// <summary>
/// Executes the SQL and retuns a subset of the rows selected.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="skipResults">The number of rows to skip over.</param>
/// <param name="maxResults">The maximum number of rows to return.</param>
/// <returns>A List of result objects.</returns>
IList<T> ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject, int skipResults, int maxResults);
/// <summary>
/// Executes the SQL and retuns all rows selected. This is exactly the same as
/// calling ExecuteQueryForList(session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS).
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>A List of result objects.</returns>
IList<T> ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject);
//#endif
#endregion
#region ExecuteForObject
/// <summary>
/// Executes an SQL statement that returns a single row as an Object.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>The object</returns>
object ExecuteQueryForObject(ISqlMapSession session, object parameterObject);
/// <summary>
/// Executes an SQL statement that returns a single row as an Object of the type of
/// the resultObject passed in as a parameter.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">The result object.</param>
/// <returns>The object</returns>
object ExecuteQueryForObject(ISqlMapSession session, object parameterObject, object resultObject);
#endregion
#region ExecuteForObject .NET 2.0
//#if dotnet2
/// <summary>
/// Executes an SQL statement that returns a single row as an Object.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <returns>The object</returns>
T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject);
/// <summary>
/// Executes an SQL statement that returns a single row as an Object of the type of
/// the resultObject passed in as a parameter.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="resultObject">The result object.</param>
/// <returns>The object</returns>
T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject, T resultObject);
//#endif
#endregion
#region Delegate
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="rowDelegate"></param>param>
/// <returns></returns>
IList ExecuteQueryForRowDelegate(ISqlMapSession session, object parameterObject, RowDelegate rowDelegate);
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL. </param>
/// <param name="keyProperty">The property of the result object to be used as the key. </param>
/// <param name="valueProperty">The property of the result object to be used as the value (or null)</param>
/// <param name="rowDelegate"></param>
/// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns>
/// <exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception>
IDictionary ExecuteQueryForMapWithRowDelegate(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate rowDelegate);
#endregion
#region ExecuteQueryForRowDelegate .NET 2.0
//#if dotnet2
/// <summary>
/// Runs a query with a custom object that gets a chance
/// to deal with each row as it is processed.
/// </summary>
/// <param name="session">The session used to execute the statement.</param>
/// <param name="parameterObject">The object used to set the parameters in the SQL.</param>
/// <param name="rowDelegate"></param>param>
/// <returns></returns>
IList<T> ExecuteQueryForRowDelegate<T>(ISqlMapSession session, object parameterObject, RowDelegate<T> rowDelegate);
//#endif
#endregion
}
}
| |
using LazyPI.Common;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace LazyPI.LazyObjects
{
public class AFElements : ObservableCollection<AFElement>
{
public AFElement this[string Name]
{
get
{
return this.SingleOrDefault(x => x.Name == Name);
}
}
internal AFElements(IEnumerable<AFElement> elements) : base(elements.ToList())
{
}
}
public class AFElement : CheckInAble
{
private AFElementTemplate _Template;
private AFElement _Parent;
private AFElements _Elements;
private AFAttributes _Attributes;
private List<string> _Categories;
private static IAFElementController _ElementController;
#region "Properties"
public List<string> Categories
{
get
{
if (_Categories == null)
{
_Categories = new List<string>(_ElementController.GetCategories(_Connection, WebID));
}
return _Categories;
}
}
public AFElementTemplate Template
{
get
{
if (_Template == null)
{
string templateName = _ElementController.GetElementTemplate(_Connection, WebID);
_Template = AFElementTemplate.Find(_Connection, templateName);
}
return _Template;
}
}
public AFElement Parent
{
get
{
if (_Parent == null)
{
string parentPath = this.Path.Substring(0, this.Path.LastIndexOf('\\'));
_Parent = _ElementController.FindByPath(_Connection, parentPath);
}
return _Parent;
}
}
public AFElements Elements
{
get
{
if (_Elements == null)
{
_Elements = new AFElements(_ElementController.GetElements(_Connection, WebID).ToList());
_Elements.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ItemsChangedMethod);
}
return _Elements;
}
set
{
_Elements = value;
IsDirty = true;
}
}
public AFAttributes Attributes
{
get
{
if (_Attributes == null)
{
_Attributes = new AFAttributes(_ElementController.GetAttributes(_Connection, WebID).ToList());
_Attributes.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(ItemsChangedMethod);
}
return _Attributes;
}
set
{
_Attributes = value;
IsDirty = true;
}
}
#endregion "Properties"
#region "Constructors"
public AFElement()
{
}
internal AFElement(Connection Connection, string WebID, string ID, string Name, string Description, string Path)
: base(Connection, WebID, ID, Name, Description, Path)
{
Initialize();
}
/// <summary>
/// Builds loader object and sets all callbacks for lazy loading
/// </summary>
private void Initialize()
{
_ElementController = GetController(_Connection);
//Initialize Category List
}
private static IAFElementController GetController(Connection Connection)
{
IAFElementController result = null;
if (Connection is WebAPI.WebAPIConnection)
{
result = new WebAPI.AFElementController();
}
return result;
}
#endregion "Constructors"
#region "Interactions"
public override void CheckIn()
{
if (IsDirty && !IsDeleted)
{
_ElementController.Update(_Connection, this);
if (_Elements != null)
{
foreach (AFElement ele in _Elements.Where(x => x.IsNew))
{
_ElementController.CreateChildElement(_Connection, WebID, ele);
}
}
if (_Attributes != null)
{
foreach (AFAttribute attr in _Attributes.Where(x => x.IsNew))
{
_ElementController.CreateAttribute(_Connection, WebID, attr);
}
}
ResetState();
}
}
protected override void ResetState()
{
IsNew = false;
IsDirty = false;
_Elements = null;
_Attributes = null;
_Template = null;
_Categories = null;
_Parent = null;
}
public void Delete()
{
_ElementController.Delete(_Connection, WebID);
IsDeleted = true;
}
#endregion "Interactions"
#region "Static Methods"
/// <summary>
/// Returns element requested
/// </summary>
/// <param name="ID"></param>
/// <returns></returns>
public static AFElement Find(Connection Connection, string ID)
{
return GetController(Connection).Find(Connection, ID);
}
/// <summary>
///
/// </summary>
/// <param name="Path"></param>
/// <returns></returns>
public static AFElement FindByPath(Connection Connection, string Path)
{
return GetController(Connection).FindByPath(Connection, Path);
}
/// <summary>
/// Find all of the child elements with a specific category.
/// </summary>
/// <param name="RootID">The parent or root for the search.</param>
/// <param name="CategoryName">Name of the category to be searched for.</param>
/// <param name="MaxCount">Max number of elements that should be searched for.</param>
/// <returns>A list of elements that have a specific category.</returns>
public static IEnumerable<AFElement> FindByCategory(Connection Connection, string RootID, string CategoryName, int MaxCount = 1000)
{
return GetController(Connection).GetElements(Connection, RootID, "*", CategoryName, "*", ElementType.Any, false, "Name", "Ascending", 0, MaxCount);
}
/// <summary>
/// Find all of the child elements with a specific template.
/// </summary>
/// <param name="RootID">The parent or root for the search</param>
/// <param name="TemplateName">Name of the template to be searched for.</param>
/// <param name="MaxCount">Max number of elements that should be searched for.</param>
/// <returns>A list of elements that have a specific template.</returns>
public static IEnumerable<AFElement> FindByTemplate(Connection Connection, string RootID, string TemplateName, int MaxCount = 1000)
{
return GetController(Connection).GetElements(Connection, RootID, "*", "*", TemplateName, ElementType.Any, false, "Name", "Ascending", 0, MaxCount);
}
#endregion "Static Methods"
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.ArcGISServices;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.Xamarin.Forms;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Colors = System.Drawing.Color;
namespace ArcGISRuntime.Samples.EditAndSyncFeatures
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Edit and sync features",
category: "Data",
description: "Synchronize offline edits with a feature service.",
instructions: "Pan and zoom to position the red rectangle around the area you want to take offline. Tap \"Generate geodatabase\" to take the area offline. When complete, the map will update to only show the offline area. To edit features, tap to select a feature, and tap again anywhere else on the map to move the selected feature to the clicked location. To sync the edits with the feature service, tap the \"Sync geodatabase\" button.",
tags: new[] { "feature service", "geodatabase", "offline", "synchronize" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("e4a398afe9a945f3b0f4dca1e4faccb5")]
public partial class EditAndSyncFeatures : ContentPage
{
// Enumeration to track which phase of the workflow the sample is in.
private enum EditState
{
NotReady, // Geodatabase has not yet been generated.
Editing, // A feature is in the process of being moved.
Ready // The geodatabase is ready for synchronization or further edits.
}
// URL for a feature service that supports geodatabase generation.
private Uri _featureServiceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/Sync/WildfireSync/FeatureServer");
// Path to the geodatabase file on disk.
private string _gdbPath;
// Task to be used for generating the geodatabase.
private GeodatabaseSyncTask _gdbSyncTask;
// Flag to indicate which stage of the edit process the sample is in.
private EditState _readyForEdits = EditState.NotReady;
// Hold a reference to the generated geodatabase.
private Geodatabase _resultGdb;
public EditAndSyncFeatures()
{
InitializeComponent();
// Create the UI, setup the control references and execute initialization.
Initialize();
}
private async void Initialize()
{
// Create a tile cache and load it with the SanFrancisco streets tpk.
try
{
TileCache tileCache = new TileCache(DataManager.GetDataFolder("e4a398afe9a945f3b0f4dca1e4faccb5", "SanFrancisco.tpkx"));
// Create the corresponding layer based on the tile cache.
ArcGISTiledLayer tileLayer = new ArcGISTiledLayer(tileCache);
// Create the basemap based on the tile cache.
Basemap sfBasemap = new Basemap(tileLayer);
// Create the map with the tile-based basemap.
Map myMap = new Map(sfBasemap);
// Assign the map to the MapView.
myMapView.Map = myMap;
// Create a new symbol for the extent graphic.
SimpleLineSymbol lineSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Colors.Red, 2);
// Create a graphics overlay for the extent graphic and apply a renderer.
GraphicsOverlay extentOverlay = new GraphicsOverlay
{
Renderer = new SimpleRenderer(lineSymbol)
};
// Add the graphics overlay to the map view.
myMapView.GraphicsOverlays.Add(extentOverlay);
// Set up an event handler for when the viewpoint (extent) changes.
myMapView.ViewpointChanged += MapViewExtentChanged;
// Create a task for generating a geodatabase (GeodatabaseSyncTask).
_gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);
// Add all layers from the service to the map.
foreach (IdInfo layer in _gdbSyncTask.ServiceInfo.LayerInfos)
{
// Get the URL for this layer.
Uri onlineTableUri = new Uri(_featureServiceUri + "/" + layer.Id);
// Create the ServiceFeatureTable.
ServiceFeatureTable onlineTable = new ServiceFeatureTable(onlineTableUri);
// Wait for the table to load.
await onlineTable.LoadAsync();
// Skip tables that aren't for point features.{
if (onlineTable.GeometryType != GeometryType.Point)
{
continue;
}
// Add the layer to the map's operational layers if load succeeds.
if (onlineTable.LoadStatus == Esri.ArcGISRuntime.LoadStatus.Loaded)
{
myMap.OperationalLayers.Add(new FeatureLayer(onlineTable));
}
}
// Update the graphic - needed in case the user decides not to interact before pressing the button.
UpdateMapExtent();
// Enable the generate button now that sample is ready.
myGenerateButton.IsEnabled = true;
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
}
}
private async void GeoViewTapped(object sender, GeoViewInputEventArgs e)
{
try
{
// Disregard if not ready for edits.
if (_readyForEdits == EditState.NotReady) { return; }
// If an edit is in process, finish it.
if (_readyForEdits == EditState.Editing)
{
// Hold a list of any selected features.
List<Feature> selectedFeatures = new List<Feature>();
// Get all selected features then clear selection.
foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
{
// Get the selected features.
FeatureQueryResult layerFeatures = await layer.GetSelectedFeaturesAsync();
// FeatureQueryResult implements IEnumerable, so it can be treated as a collection of features.
selectedFeatures.AddRange(layerFeatures);
// Clear the selection.
layer.ClearSelection();
}
// Update all selected features' geometry.
foreach (Feature feature in selectedFeatures)
{
// Get a reference to the correct feature table for the feature.
GeodatabaseFeatureTable table = (GeodatabaseFeatureTable)feature.FeatureTable;
// Ensure the geometry type of the table is point.
if (table.GeometryType != GeometryType.Point)
{
continue;
}
// Set the new geometry.
feature.Geometry = e.Location;
// Update the feature in the table.
await table.UpdateFeatureAsync(feature);
}
// Update the edit state.
_readyForEdits = EditState.Ready;
// Enable the sync button.
mySyncButton.IsEnabled = true;
// Update the help label.
MyHelpLabel.Text = "4. Click 'Synchronize' or keep editing";
}
// Otherwise, start an edit.
else
{
// Define a tolerance for use with identifying the feature.
double tolerance = 15 * myMapView.UnitsPerPixel;
// Define the selection envelope.
Envelope selectionEnvelope = new Envelope(e.Location.X - tolerance, e.Location.Y - tolerance, e.Location.X + tolerance, e.Location.Y + tolerance);
// Define query parameters for feature selection.
QueryParameters query = new QueryParameters()
{
Geometry = selectionEnvelope
};
// Track whether any selections were made.
bool selectedFeature = false;
// Select the feature in all applicable tables.
foreach (FeatureLayer layer in myMapView.Map.OperationalLayers)
{
FeatureQueryResult res = await layer.SelectFeaturesAsync(query, Esri.ArcGISRuntime.Mapping.SelectionMode.New);
selectedFeature = selectedFeature || res.Any();
}
// Only update state if a feature was selected.
if (selectedFeature)
{
// Set the edit state.
_readyForEdits = EditState.Editing;
// Update the help label.
MyHelpLabel.Text = "3. Tap on the map to move the point";
}
}
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
}
}
private void UpdateMapExtent()
{
// Return if mapview is null.
if (myMapView == null) { return; }
// Get the new viewpoint.
Viewpoint myViewPoint = myMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Return if viewpoint is null.
if (myViewPoint == null) { return; }
// Get the updated extent for the new viewpoint.
Envelope extent = myViewPoint.TargetGeometry as Envelope;
// Return if extent is null.
if (extent == null) { return; }
// Create an envelope that is a bit smaller than the extent.
EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent);
envelopeBldr.Expand(0.80);
// Get the (only) graphics overlay in the map view.
GraphicsOverlay extentOverlay = myMapView.GraphicsOverlays.FirstOrDefault();
// Return if the extent overlay is null.
if (extentOverlay == null) { return; }
// Get the extent graphic.
Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault();
// Create the extent graphic and add it to the overlay if it doesn't exist.
if (extentGraphic == null)
{
extentGraphic = new Graphic(envelopeBldr.ToGeometry());
extentOverlay.Graphics.Add(extentGraphic);
}
else
{
// Otherwise, update the graphic's geometry.
extentGraphic.Geometry = envelopeBldr.ToGeometry();
}
}
private async Task StartGeodatabaseGeneration()
{
// Update the geodatabase path.
_gdbPath = $"{Path.GetTempFileName()}.geodatabase";
// Create a task for generating a geodatabase (GeodatabaseSyncTask).
_gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri);
// Get the (only) graphic in the map view.
Graphic redPreviewBox = myMapView.GraphicsOverlays.First().Graphics.First();
// Get the current extent of the red preview box.
Envelope extent = redPreviewBox.Geometry as Envelope;
// Get the default parameters for the generate geodatabase task.
GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent);
// Create a generate geodatabase job.
GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath);
// Show the progress bar.
myProgressBar.IsVisible = true;
// Handle the progress changed event with an inline (lambda) function to show the progress bar.
generateGdbJob.ProgressChanged += (sender, e) =>
{
// Get the job.
GenerateGeodatabaseJob job = (GenerateGeodatabaseJob)sender;
// Update the progress bar.
UpdateProgressBar(job.Progress);
};
// Start the job.
generateGdbJob.Start();
// Get the result.
_resultGdb = await generateGdbJob.GetResultAsync();
// Hide the progress bar.
myProgressBar.IsVisible = false;
// Handle the job completion.
HandleGenerationStatusChange(generateGdbJob);
}
private async void HandleGenerationStatusChange(GenerateGeodatabaseJob job)
{
// If the job completed successfully, add the geodatabase data to the map.
if (job.Status == JobStatus.Succeeded)
{
// Clear out the existing layers.
myMapView.Map.OperationalLayers.Clear();
// Loop through all feature tables in the geodatabase and add a new layer to the map.
foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables)
{
// Skip non-point tables.
await table.LoadAsync();
if (table.GeometryType != GeometryType.Point)
{
continue;
}
// Create a new feature layer for the table.
FeatureLayer layer = new FeatureLayer(table);
// Add the new layer to the map.
myMapView.Map.OperationalLayers.Add(layer);
}
// Enable editing features.
_readyForEdits = EditState.Ready;
// Update the help label.
MyHelpLabel.Text = "2. Tap a point feature to select";
}
// See if the job failed.
else if (job.Status == JobStatus.Failed)
{
// Create a message to show the user.
string message = "Generate geodatabase job failed";
// Show an error message (if there is one).
if (job.Error != null)
{
message += ": " + job.Error.Message;
}
else
{
// If no error, show messages from the job.
foreach (JobMessage m in job.Messages)
{
// Get the text from the JobMessage and add it to the output string.
message += "\n" + m.Message;
}
}
// Show the message.
await Application.Current.MainPage.DisplayAlert("Error", message, "OK");
}
}
private async Task SyncGeodatabase()
{
// Return if not ready.
if (_readyForEdits != EditState.Ready) { return; }
// Create parameters for the sync task.
SyncGeodatabaseParameters parameters = new SyncGeodatabaseParameters()
{
GeodatabaseSyncDirection = SyncDirection.Bidirectional,
RollbackOnFailure = false
};
// Get the layer ID for each feature table in the geodatabase, then add to the sync job.
foreach (GeodatabaseFeatureTable table in _resultGdb.GeodatabaseFeatureTables)
{
// Get the ID for the layer.
long id = table.ServiceLayerId;
// Create the SyncLayerOption.
SyncLayerOption option = new SyncLayerOption(id);
// Add the option.
parameters.LayerOptions.Add(option);
}
// Create job.
SyncGeodatabaseJob job = _gdbSyncTask.SyncGeodatabase(parameters, _resultGdb);
// Subscribe to progress updates.
job.ProgressChanged += (o, e) =>
{
UpdateProgressBar(job.Progress);
};
// Show the progress bar.
myProgressBar.IsVisible = true;
// Disable the sync button.
mySyncButton.IsEnabled = false;
// Start the sync.
job.Start();
// Wait for the result.
await job.GetResultAsync();
// Hide the progress bar.
myProgressBar.IsVisible = false;
// Do the rest of the work.
HandleSyncCompleted(job);
// Re-enable the sync button.
mySyncButton.IsEnabled = true;
}
private void HandleSyncCompleted(SyncGeodatabaseJob job)
{
// Tell the user about job completion.
if (job.Status == JobStatus.Succeeded)
{
Application.Current.MainPage.DisplayAlert("Alert", "Geodatabase synchronization succeeded.", "OK");
}
// See if the job failed.
else if (job.Status == JobStatus.Failed)
{
// Create a message to show the user.
string message = "Sync geodatabase job failed";
// Show an error message (if there is one).
if (job.Error != null)
{
message += ": " + job.Error.Message;
}
else
{
// If no error, show messages from the job.
foreach (JobMessage m in job.Messages)
{
// Get the text from the JobMessage and add it to the output string.
message += "\n" + m.Message;
}
}
// Show the message.
Application.Current.MainPage.DisplayAlert("Error", message, "OK");
}
}
private async void GenerateButton_Clicked(object sender, EventArgs e)
{
// Fix the selection graphic extent.
myMapView.ViewpointChanged -= MapViewExtentChanged;
// Disable the generate button.
try
{
myGenerateButton.IsEnabled = false;
// Call the geodatabase generation method.
await StartGeodatabaseGeneration();
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
}
}
private void MapViewExtentChanged(object sender, EventArgs e)
{
// Call the map extent update method.
UpdateMapExtent();
}
private void UpdateProgressBar(int progress)
{
// Due to the nature of the threading implementation,
// the dispatcher needs to be used to interact with the UI.
// The dispatcher takes an Action, provided here as a lambda function.
Device.BeginInvokeOnMainThread(() =>
{
// Update the progress bar value.
myProgressBar.Progress = progress / 100.0;
});
}
private async void SyncButton_Click(object sender, EventArgs e)
{
try
{
await SyncGeodatabase();
}
catch (Exception ex)
{
await Application.Current.MainPage.DisplayAlert("Alert", ex.ToString(), "OK");
}
}
}
}
| |
using System;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace MyMeta
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(false), ClassInterface(ClassInterfaceType.AutoDual)]
#endif
public class Tables : Collection, ITables, IEnumerable, ICollection
{
public Tables()
{
}
internal DataColumn f_Catalog = null;
internal DataColumn f_Schema = null;
internal DataColumn f_Name = null;
internal DataColumn f_Type = null;
internal DataColumn f_Guid = null;
internal DataColumn f_Description = null;
internal DataColumn f_PropID = null;
internal DataColumn f_DateCreated = null;
internal DataColumn f_DateModified = null;
private void BindToColumns(DataTable metaData)
{
if(false == _fieldsBound)
{
if(metaData.Columns.Contains("TABLE_CATALOG")) f_Catalog = metaData.Columns["TABLE_CATALOG"];
if(metaData.Columns.Contains("TABLE_SCHEMA")) f_Schema = metaData.Columns["TABLE_SCHEMA"];
if(metaData.Columns.Contains("TABLE_NAME")) f_Name = metaData.Columns["TABLE_NAME"];
if(metaData.Columns.Contains("TABLE_TYPE")) f_Type = metaData.Columns["TABLE_TYPE"];
if(metaData.Columns.Contains("TABLE_GUID")) f_Guid = metaData.Columns["TABLE_GUID"];
if(metaData.Columns.Contains("DESCRIPTION")) f_Description = metaData.Columns["DESCRIPTION"];
if(metaData.Columns.Contains("TABLE_PROPID")) f_PropID = metaData.Columns["TABLE_PROPID"];
if(metaData.Columns.Contains("DATE_CREATED")) f_DateCreated = metaData.Columns["DATE_CREATED"];
if(metaData.Columns.Contains("DATE_MODIFIED")) f_DateModified = metaData.Columns["DATE_MODIFIED"];
}
}
internal virtual void LoadAll()
{
}
protected void PopulateArray(DataTable metaData)
{
BindToColumns(metaData);
Table table = null;
if(metaData.DefaultView.Count > 0)
{
IEnumerator enumerator = metaData.DefaultView.GetEnumerator();
while(enumerator.MoveNext())
{
DataRowView rowView = enumerator.Current as DataRowView;
table = (Table)this.dbRoot.ClassFactory.CreateTable();
table.dbRoot = this.dbRoot;
table.Tables = this;
table.Row = rowView.Row;
this._array.Add(table);
}
}
}
internal void AddTable(Table table)
{
this._array.Add(table);
}
#region indexers
#if ENTERPRISE
[DispId(0)]
#endif
public ITable this[object index]
{
get
{
if(index.GetType() == Type.GetType("System.String"))
{
return GetByPhysicalName(index as String);
}
else
{
int idx = Convert.ToInt32(index);
return this._array[idx] as Table;
}
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
public Table GetByName(string name)
{
Table table = null;
Table tmp = null;
int count = this._array.Count;
for(int i = 0; i < count; i++)
{
tmp = this._array[i] as Table;
if(this.CompareStrings(name,tmp.Name))
{
table = tmp;
break;
}
}
return table;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
internal Table GetByPhysicalName(string name)
{
Table table = null;
Table tmp = null;
int count = this._array.Count;
for(int i = 0; i < count; i++)
{
tmp = this._array[i] as Table;
if(this.CompareStrings(name,tmp.Name))
{
table = tmp;
break;
}
}
return table;
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
#endregion
#region IEnumerable<ITable> Members
public IEnumerator<ITable> GetEnumerator() {
foreach (object item in _array)
yield return item as ITable;
}
#endregion
#region XML User Data
#if ENTERPRISE
[ComVisible(false)]
#endif
override public string UserDataXPath
{
get
{
return Database.UserDataXPath + @"/Tables";
}
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override internal bool GetXmlNode(out XmlNode node, bool forceCreate)
{
node = null;
bool success = false;
if(null == _xmlNode)
{
// Get the parent node
XmlNode parentNode = null;
if(this.Database.GetXmlNode(out parentNode, forceCreate))
{
// See if our user data already exists
string xPath = @"./Tables";
if(!GetUserData(xPath, parentNode, out _xmlNode) && forceCreate)
{
// Create it, and try again
this.CreateUserMetaData(parentNode);
GetUserData(xPath, parentNode, out _xmlNode);
}
}
}
if(null != _xmlNode)
{
node = _xmlNode;
success = true;
}
return success;
}
#if ENTERPRISE
[ComVisible(false)]
#endif
override public void CreateUserMetaData(XmlNode parentNode)
{
XmlNode myNode = parentNode.OwnerDocument.CreateNode(XmlNodeType.Element, "Tables", null);
parentNode.AppendChild(myNode);
}
#endregion
#region IList Members
object System.Collections.IList.this[int index]
{
get { return this[index];}
set { }
}
#endregion
internal Database Database = null;
}
}
| |
//
// StreamPositionLabel.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2006-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Mono.Unix;
using Gtk;
namespace Banshee.Widgets
{
public enum StreamLabelState {
Idle,
Contacting,
Loading,
Buffering,
Playing
}
public class StreamPositionLabel : Alignment
{
private double buffering_progress;
private bool is_live;
private SeekSlider seekRange;
private string format_string = "<small>{0}</small>";
private Pango.Layout layout;
private StreamLabelState state;
public StreamPositionLabel (SeekSlider seekRange) : base (0.0f, 0.0f, 1.0f, 1.0f)
{
AppPaintable = true;
this.seekRange = seekRange;
this.seekRange.ValueChanged += OnSliderUpdated;
}
protected override void OnRealized ()
{
base.OnRealized ();
BuildLayouts ();
UpdateLabel ();
}
private void BuildLayouts ()
{
if (layout != null) {
layout.Dispose ();
}
layout = new Pango.Layout (PangoContext);
layout.FontDescription = PangoContext.FontDescription.Copy ();
layout.Ellipsize = Pango.EllipsizeMode.None;
}
private bool first_style_set = false;
protected override void OnStyleSet (Style old_style)
{
base.OnStyleSet (old_style);
if (first_style_set) {
BuildLayouts ();
UpdateLabel ();
}
first_style_set = true;
}
protected override void OnSizeRequested (ref Gtk.Requisition requisition)
{
if (!IsRealized || layout == null) {
return;
}
EnsureStyle ();
int width, height;
layout.GetPixelSize (out width, out height);
requisition.Width = width;
requisition.Height = height;
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
int bar_width = (int)((double)Allocation.Width * buffering_progress);
bool render_bar = false;
if (bar_width > 0 && IsBuffering) {
bar_width -= 2 * Style.XThickness;
render_bar = true;
Gtk.Style.PaintBox (Style, GdkWindow, StateType.Normal, ShadowType.In, evnt.Area, this, null,
Allocation.X, Allocation.Y, Allocation.Width, Allocation.Height);
if (bar_width > 0) {
Gtk.Style.PaintBox (Style, GdkWindow, StateType.Selected, ShadowType.EtchedOut,
evnt.Area, this, "bar",
Allocation.X + Style.XThickness, Allocation.Y + Style.YThickness,
bar_width, Allocation.Height - 2 * Style.YThickness);
}
}
int width, height;
layout.GetPixelSize (out width, out height);
int x = Allocation.X + ((Allocation.Width - width) / 2);
int y = Allocation.Y + ((Allocation.Height - height) / 2);
Gdk.Rectangle rect = evnt.Area;
if (render_bar) {
width = bar_width + Style.XThickness;
rect = new Gdk.Rectangle (evnt.Area.X, evnt.Area.Y, width, evnt.Area.Height);
Gtk.Style.PaintLayout (Style, GdkWindow, StateType.Selected, true, rect, this, null, x, y, layout);
rect.X += rect.Width;
rect.Width = evnt.Area.Width - rect.Width;
}
Gtk.Style.PaintLayout (Style, GdkWindow, StateType.Normal, false, rect, this, null, x, y, layout);
return true;
}
private static string idle = Catalog.GetString ("Idle");
private static string contacting = Catalog.GetString ("Contacting...");
private void UpdateLabel ()
{
if (!IsRealized || layout == null) {
return;
}
if (IsBuffering) {
double progress = buffering_progress * 100.0;
UpdateLabel (String.Format ("{0}: {1}%", Catalog.GetString("Buffering"), progress.ToString ("0.0")));
} else if (IsContacting) {
UpdateLabel (contacting);
} else if (IsLoading) {
// TODO replace w/ "Loading..." after string freeze
UpdateLabel (contacting);
} else if (IsIdle) {
UpdateLabel (idle);
} else if (seekRange.Duration == Int64.MaxValue) {
UpdateLabel (FormatDuration ((long)seekRange.Value));
} else if (seekRange.Value == 0 && seekRange.Duration == 0) {
// nop
} else {
UpdateLabel (String.Format (Catalog.GetString ("{0} of {1}"),
FormatDuration ((long)seekRange.Value), FormatDuration ((long)seekRange.Adjustment.Upper)));
}
}
private void UpdateLabel (string text)
{
if (!IsRealized || layout == null) {
return;
}
layout.SetMarkup (String.Format (format_string, GLib.Markup.EscapeText (text)));
QueueResize ();
}
private static string FormatDuration (long time)
{
time /= 1000;
return (time > 3600 ?
String.Format ("{0}:{1:00}:{2:00}", time / 3600, (time / 60) % 60, time % 60) :
String.Format ("{0}:{1:00}", time / 60, time % 60));
}
private void OnSliderUpdated (object o, EventArgs args)
{
UpdateLabel ();
}
public double BufferingProgress {
get { return buffering_progress; }
set {
buffering_progress = Math.Max (0.0, Math.Min (1.0, value));
UpdateLabel ();
QueueDraw ();
}
}
public bool IsIdle {
get { return StreamState == StreamLabelState.Idle; }
}
public bool IsBuffering {
get { return StreamState == StreamLabelState.Buffering; }
}
public bool IsContacting {
get { return StreamState == StreamLabelState.Contacting; }
}
public bool IsLoading {
get { return StreamState == StreamLabelState.Loading; }
}
public StreamLabelState StreamState {
get { return state; }
set {
if (state != value) {
state = value;
UpdateLabel ();
QueueDraw ();
}
}
}
public bool IsLive {
get { return is_live; }
set {
if (is_live != value) {
is_live = value;
UpdateLabel ();
QueueDraw ();
}
}
}
public string FormatString {
set {
format_string = value;
BuildLayouts ();
UpdateLabel ();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class CtorTests
{
[Fact]
public static void TestDefaultConstructor()
{
using (X509Certificate2 c = new X509Certificate2())
{
VerifyDefaultConstructor(c);
}
}
private static void VerifyDefaultConstructor(X509Certificate2 c)
{
IntPtr h = c.Handle;
object ignored;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters());
Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber());
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Issuer);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Subject);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.RawData);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Thumbprint);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SignatureAlgorithm);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.HasPrivateKey);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Version);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.Archived);
Assert.ThrowsAny<CryptographicException>(() => c.Archived = false);
Assert.ThrowsAny<CryptographicException>(() => c.FriendlyName = "Hi");
Assert.ThrowsAny<CryptographicException>(() => ignored = c.SubjectName);
Assert.ThrowsAny<CryptographicException>(() => ignored = c.IssuerName);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHashString());
Assert.ThrowsAny<CryptographicException>(() => c.GetEffectiveDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetExpirationDateString());
Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKeyString());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertData());
Assert.ThrowsAny<CryptographicException>(() => c.GetRawCertDataString());
Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumberString());
#pragma warning disable 0618
Assert.ThrowsAny<CryptographicException>(() => c.GetIssuerName());
Assert.ThrowsAny<CryptographicException>(() => c.GetName());
#pragma warning restore 0618
}
[Fact]
public static void TestConstructor_DER()
{
byte[] expectedThumbPrint = new byte[]
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (c) =>
{
IntPtr h = c.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = c.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestConstructor_PEM()
{
byte[] expectedThumbPrint =
{
0x10, 0x8e, 0x2b, 0xa2, 0x36, 0x32, 0x62, 0x0c,
0x42, 0x7c, 0x57, 0x0b, 0x6d, 0x9d, 0xb5, 0x1a,
0xc3, 0x13, 0x87, 0xfe,
};
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
byte[] actualThumbprint = cert.GetCertHash();
Assert.Equal(expectedThumbPrint, actualThumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificatePemBytes))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
public static void TestCopyConstructor_NoPal()
{
using (var c1 = new X509Certificate2())
using (var c2 = new X509Certificate2(c1))
{
VerifyDefaultConstructor(c1);
VerifyDefaultConstructor(c2);
}
}
[Fact]
public static void TestCopyConstructor_Pal()
{
using (var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var c2 = new X509Certificate2(c1))
{
Assert.Equal(c1.GetCertHash(), c2.GetCertHash());
Assert.Equal(c1.GetKeyAlgorithm(), c2.GetKeyAlgorithm());
Assert.Equal(c1.GetKeyAlgorithmParameters(), c2.GetKeyAlgorithmParameters());
Assert.Equal(c1.GetKeyAlgorithmParametersString(), c2.GetKeyAlgorithmParametersString());
Assert.Equal(c1.GetPublicKey(), c2.GetPublicKey());
Assert.Equal(c1.GetSerialNumber(), c2.GetSerialNumber());
Assert.Equal(c1.Issuer, c2.Issuer);
Assert.Equal(c1.Subject, c2.Subject);
Assert.Equal(c1.RawData, c2.RawData);
Assert.Equal(c1.Thumbprint, c2.Thumbprint);
Assert.Equal(c1.SignatureAlgorithm.Value, c2.SignatureAlgorithm.Value);
Assert.Equal(c1.HasPrivateKey, c2.HasPrivateKey);
Assert.Equal(c1.Version, c2.Version);
Assert.Equal(c1.Archived, c2.Archived);
Assert.Equal(c1.SubjectName.Name, c2.SubjectName.Name);
Assert.Equal(c1.IssuerName.Name, c2.IssuerName.Name);
Assert.Equal(c1.GetCertHashString(), c2.GetCertHashString());
Assert.Equal(c1.GetEffectiveDateString(), c2.GetEffectiveDateString());
Assert.Equal(c1.GetExpirationDateString(), c2.GetExpirationDateString());
Assert.Equal(c1.GetPublicKeyString(), c2.GetPublicKeyString());
Assert.Equal(c1.GetRawCertData(), c2.GetRawCertData());
Assert.Equal(c1.GetRawCertDataString(), c2.GetRawCertDataString());
Assert.Equal(c1.GetSerialNumberString(), c2.GetSerialNumberString());
#pragma warning disable 0618
Assert.Equal(c1.GetIssuerName(), c2.GetIssuerName());
Assert.Equal(c1.GetName(), c2.GetName());
#pragma warning restore 0618
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Independent()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
using (var c2 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
{
RSA rsa = c2.GetRSAPrivateKey();
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
c1.Dispose();
rsa.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
// Verify other cert and previous key do not affect cert
using (rsa = c2.GetRSAPrivateKey())
{
hash = new byte[20];
sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c2, false);
}
[Fact]
public static void TestCopyConstructor_Lifetime_Cloned_Reversed()
{
var c1 = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword);
var c2 = new X509Certificate2(c1);
TestPrivateKey(c1, true);
TestPrivateKey(c2, true);
c2.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, true);
TestPrivateKey(c2, false);
c1.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
TestPrivateKey(c1, false);
}
private static void TestPrivateKey(X509Certificate2 c, bool expectSuccess)
{
if (expectSuccess)
{
using (RSA rsa = c.GetRSAPrivateKey())
{
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
}
else
{
Assert.ThrowsAny<CryptographicException>(() => c.GetRSAPrivateKey());
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestConstructor_SerializedCert_Windows()
{
const string ExpectedThumbPrint = "71CB4E2B02738AD44F8B382C93BD17BA665F9914";
Action<X509Certificate2> assert = (cert) =>
{
IntPtr h = cert.Handle;
Assert.NotEqual(IntPtr.Zero, h);
Assert.Equal(ExpectedThumbPrint, cert.Thumbprint);
};
using (X509Certificate2 c = new X509Certificate2(TestData.StoreSavedAsSerializedCerData))
{
assert(c);
using (X509Certificate2 c2 = new X509Certificate2(c))
{
assert(c2);
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // StoreSavedAsSerializedCerData not supported on Unix
public static void TestByteArrayConstructor_SerializedCert_Unix()
{
Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.StoreSavedAsSerializedCerData));
}
[Fact]
public static void TestNullConstructorArguments()
{
Assert.Throws<ArgumentNullException>(() => new X509Certificate2((string)null));
Assert.Throws<ArgumentException>(() => new X509Certificate2(IntPtr.Zero));
Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (string)null));
Assert.Throws<ArgumentException>(() => new X509Certificate2(Array.Empty<byte>(), (string)null));
Assert.Throws<ArgumentException>(() => new X509Certificate2((byte[])null, (string)null, X509KeyStorageFlags.DefaultKeySet));
Assert.Throws<ArgumentException>(() => new X509Certificate2(Array.Empty<byte>(), (string)null, X509KeyStorageFlags.DefaultKeySet));
// A null string password does not throw
using (new X509Certificate2(TestData.MsCertificate, (string)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (string)null, X509KeyStorageFlags.DefaultKeySet)) { }
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromCertFile(null));
Assert.Throws<ArgumentNullException>(() => X509Certificate.CreateFromSignedFile(null));
AssertExtensions.Throws<ArgumentNullException>("cert", () => new X509Certificate2((X509Certificate2)null));
AssertExtensions.Throws<ArgumentException>("handle", () => new X509Certificate2(IntPtr.Zero));
// A null SecureString password does not throw
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null)) { }
using (new X509Certificate2(TestData.MsCertificate, (SecureString)null, X509KeyStorageFlags.DefaultKeySet)) { }
// For compat reasons, the (byte[]) constructor (and only that constructor) treats a null or 0-length array as the same
// as calling the default constructor.
{
using (X509Certificate2 c = new X509Certificate2((byte[])null))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
{
using (X509Certificate2 c = new X509Certificate2(Array.Empty<byte>()))
{
IntPtr h = c.Handle;
Assert.Equal(IntPtr.Zero, h);
Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash());
}
}
}
[Fact]
public static void InvalidCertificateBlob()
{
CryptographicException ex = Assert.ThrowsAny<CryptographicException>(
() => new X509Certificate2(new byte[] { 0x01, 0x02, 0x03 }));
CryptographicException defaultException = new CryptographicException();
Assert.NotEqual(defaultException.Message, ex.Message);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(unchecked((int)0x80092009), ex.HResult);
// TODO (3233): Test that Message is also set correctly
//Assert.Equal("Cannot find the requested object.", ex.Message);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Assert.Equal(-25257, ex.HResult);
}
else // Any Unix
{
Assert.Equal(0x0D07803A, ex.HResult);
Assert.Equal("error:0D07803A:asn1 encoding routines:ASN1_ITEM_EX_D2I:nested asn1 error", ex.Message);
}
}
[Fact]
public static void InvalidStorageFlags()
{
byte[] nonEmptyBytes = new byte[1];
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, (X509KeyStorageFlags)0xFF));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, (X509KeyStorageFlags)0xFF));
// No test is performed here for the ephemeral flag failing downlevel, because the live
// binary is always used by default, meaning it doesn't know EphemeralKeySet doesn't exist.
}
#if netcoreapp
[Fact]
public static void InvalidStorageFlags_PersistedEphemeral()
{
const X509KeyStorageFlags PersistedEphemeral =
X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet;
byte[] nonEmptyBytes = new byte[1];
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(nonEmptyBytes, string.Empty, PersistedEphemeral));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate(string.Empty, string.Empty, PersistedEphemeral));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(nonEmptyBytes, string.Empty, PersistedEphemeral));
Assert.Throws<ArgumentException>(
"keyStorageFlags",
() => new X509Certificate2(string.Empty, string.Empty, PersistedEphemeral));
}
#endif
}
}
| |
//
// (C) Copyright 2003-2011 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 ITS 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.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.FoundationSlab.CS
{
/// <summary>
/// A class collecting all useful datas from revit API for UI.
/// </summary>
public class SlabData
{
const double PlanarPrecision = 0.00033;
// For finding elements and creating foundations slabs.
public static Autodesk.Revit.UI.UIApplication m_revit;
public static Autodesk.Revit.Creation.Application CreApp;
// Foundation slab type for creating foundation slabs.
FloorType m_foundationSlabType;
// A set of levels to find out the lowest level of the building.
SortedList<double, Level> m_levelList = new SortedList<double,Level>();
// A set of views to find out the regular slab's bounding box.
List<View> m_viewList = new List<View>();
// A set of floors to find out all the regular slabs at the base of the building.
List<Floor> m_floorList = new List<Floor>();
// A set of regular slabs at the base of the building.
// This set supplies all the regular slabs' datas for UI.
List<RegularSlab> m_allBaseSlabList = new List<RegularSlab>();
// A set of the types of foundation slab.
// This set supplies all the types of foundation slab for UI.
List<FloorType> m_slabTypeList = new List<FloorType>();
/// <summary>
/// BaseSlabList property.
/// This property is for UI. It can be edited by user.
/// </summary>
public Collection<RegularSlab> BaseSlabList
{
get { return new Collection< RegularSlab >(m_allBaseSlabList); }
}
/// <summary>
/// FoundationSlabTypeList property.
/// This property is for UI. It can not be edited by user.
/// </summary>
public ReadOnlyCollection<FloorType> FoundationSlabTypeList
{
get { return new ReadOnlyCollection<FloorType>(m_slabTypeList); }
}
/// <summary>
/// FoundationSlabType property.
/// This property gets value from UI to create foundation slabs.
/// </summary>
public object FoundationSlabType
{
set { m_foundationSlabType = value as FloorType; }
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="revit">An application object that contains data related to revit command.</param>
public SlabData(UIApplication revit)
{
m_revit = revit;
CreApp = m_revit.Application.Create;
// Find out all useful elements.
FindElements();
// Get all base slabs. If no slab be found, throw an exception and return cancel.
if (!GetAllBaseSlabs())
throw new NullReferenceException("No planar slabs at the base of the building.");
}
/// <summary>
/// Check whether a regular slab is selected.
/// </summary>
/// <returns>The bool value suggest being selected or not.</returns>
public bool CheckHaveSelected()
{
foreach (RegularSlab slab in m_allBaseSlabList)
{
if (slab.Selected)
return true;
}
return false;
}
/// <summary>
/// Change the Selected property for all regular slabs.
/// </summary>
/// <param name="value">The value for Selected property</param>
public void ChangeAllSelected(bool value)
{
foreach (RegularSlab slab in m_allBaseSlabList)
{
slab.Selected = value;
}
}
/// <summary>
/// Create foundation slabs.
/// </summary>
/// <returns>The bool value suggest successful or not.</returns>
public bool CreateFoundationSlabs()
{
// Create a foundation slab for each selected regular slab.
foreach (RegularSlab slab in m_allBaseSlabList)
{
if (!slab.Selected)
{
continue;
}
// Create a new slab.
Autodesk.Revit.DB.XYZ normal = new Autodesk.Revit.DB.XYZ (0,0,1);
Transaction t = new Transaction(m_revit.ActiveUIDocument.Document, Guid.NewGuid().GetHashCode().ToString());
t.Start();
Floor foundationSlab = m_revit.ActiveUIDocument.Document.Create.NewFoundationSlab(
slab.OctagonalProfile, m_foundationSlabType, m_levelList.Values[0],
true, normal);
t.Commit();
if (null == foundationSlab)
{
return false;
}
// Delete the regular slab.
Transaction t2 = new Transaction(m_revit.ActiveUIDocument.Document, Guid.NewGuid().GetHashCode().ToString());
t2.Start();
Autodesk.Revit.DB.ElementId deleteSlabId = slab.Id;
m_revit.ActiveUIDocument.Document.Delete(deleteSlabId);
t2.Commit();
}
return true;
}
/// <summary>
/// Find out all useful elements.
/// </summary>
private void FindElements()
{
IList<ElementFilter> filters = new List<ElementFilter>(4);
filters.Add(new ElementClassFilter(typeof(Level)));
filters.Add(new ElementClassFilter(typeof(View)));
filters.Add(new ElementClassFilter(typeof(Floor)));
filters.Add(new ElementClassFilter(typeof(FloorType)));
LogicalOrFilter orFilter = new LogicalOrFilter(filters);
FilteredElementCollector collector = new FilteredElementCollector(m_revit.ActiveUIDocument.Document);
FilteredElementIterator iterator = collector.WherePasses(orFilter).GetElementIterator();
while (iterator.MoveNext())
{
// Find out all levels.
Level level = (iterator.Current) as Level;
if (null != level)
{
m_levelList.Add(level.Elevation, level);
continue;
}
// Find out all views.
View view = (iterator.Current) as View;
if (null != view && !view.IsTemplate)
{
m_viewList.Add(view);
continue;
}
// Find out all floors.
Floor floor = (iterator.Current) as Floor;
if (null != floor)
{
m_floorList.Add(floor);
continue;
}
// Find out all foundation slab types.
FloorType floorType = (iterator.Current) as FloorType;
if (null == floorType)
{
continue;
}
if ("Structural Foundations" == floorType.Category.Name)
{
m_slabTypeList.Add(floorType);
}
}
}
/// <summary>
/// Get all base slabs.
/// </summary>
/// <returns>A bool value suggests successful or not.</returns>
private bool GetAllBaseSlabs()
{
// No level, no slabs.
if (0 == m_levelList.Count)
return false;
// Find out the lowest level's view for finding the bounding box of slab.
View baseView = null;
foreach (View view in m_viewList)
{
if (view.ViewName == m_levelList.Values[0].Name)
{
baseView = view;
}
}
if (null == baseView)
return false;
// Get all slabs at the base of the building.
foreach (Floor floor in m_floorList)
{
if (floor.Level.Id.IntegerValue == m_levelList.Values[0].Id.IntegerValue)
{
BoundingBoxXYZ bbXYZ = floor.get_BoundingBox(baseView); // Get the slab's bounding box.
// Check the floor. If the floor is planar, deal with it, otherwise, leap it.
if (!IsPlanarFloor(bbXYZ, floor))
continue;
CurveArray floorProfile = GetFloorProfile(floor); // Get the slab's profile.
RegularSlab regularSlab = new RegularSlab(floor, floorProfile, bbXYZ); // Get a regular slab.
m_allBaseSlabList.Add(regularSlab); // Add regular slab to the set.
}
}
// Getting regular slabs.
if (0 != m_allBaseSlabList.Count)
return true;
else return false;
}
/// <summary>
/// Check whether the floor is planar.
/// </summary>
/// <param name="bbXYZ">The floor's bounding box.</param>
/// <param name="floor">The floor object.</param>
/// <returns>A bool value suggests the floor is planar or not.</returns>
private static bool IsPlanarFloor(BoundingBoxXYZ bbXYZ, Floor floor)
{
// Get floor thickness.
double floorThickness = 0.0;
ElementType floorType = m_revit.ActiveUIDocument.Document.get_Element(floor.GetTypeId()) as ElementType;
Parameter attribute = floorType.get_Parameter(BuiltInParameter.FLOOR_ATTR_DEFAULT_THICKNESS_PARAM);
if (null != attribute)
{
floorThickness = attribute.AsDouble();
}
// Get bounding box thickness.
double boundThickness = Math.Abs(bbXYZ.Max.Z - bbXYZ.Min.Z);
// Planar or not.
if (Math.Abs(boundThickness - floorThickness) < PlanarPrecision)
return true;
else
return false;
}
/// <summary>
/// Get a floor's profile.
/// </summary>
/// <param name="floor">The floor whose profile you want to get.</param>
/// <returns>The profile of the floor.</returns>
private CurveArray GetFloorProfile(Floor floor)
{
CurveArray floorProfile = new CurveArray();
// Structural slab's profile can be found in it's AnalyticalModel.
if (null != floor.GetAnalyticalModel())
{
AnalyticalModel analyticalModel = floor.GetAnalyticalModel();
IList<Curve> curveList= analyticalModel.GetCurves(AnalyticalCurveType.ActiveCurves);
for (int i = 0; i < curveList.Count; i++)
{
floorProfile.Append(curveList[i]);
}
return floorProfile;
}
// Nonstructural floor's profile can be formed through it's Geometry.
Options aOptions = m_revit.Application.Create.NewGeometryOptions();
Autodesk.Revit.DB.GeometryElement aElementOfGeometry = floor.get_Geometry(aOptions);
GeometryObjectArray geometryObjects = aElementOfGeometry.Objects;
foreach (GeometryObject o in geometryObjects)
{
Solid solid = o as Solid;
if (null == solid)
continue;
// Form the floor's profile through solid's edges.
EdgeArray edges = solid.Edges;
for (int i = 0; i < (edges.Size) / 3; i++)
{
Edge edge = edges.get_Item(i);
List<XYZ> xyzArray = edge.Tessellate() as List<XYZ>; // A set of points.
for (int j = 0; j < (xyzArray.Count - 1); j++)
{
Autodesk.Revit.DB.XYZ startPoint = xyzArray[j];
Autodesk.Revit.DB.XYZ endPoint = xyzArray[j + 1];
Line line = CreApp.NewLine(startPoint, endPoint,true);
floorProfile.Append(line);
}
}
}
return floorProfile;
}
}
}
| |
namespace gView.Plugins.MapTools.Dialogs
{
partial class FormIdentify
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormIdentify));
this.listValues = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.treeObjects = new System.Windows.Forms.TreeView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.txtLocation = new System.Windows.Forms.TextBox();
this.panelFeatures = new System.Windows.Forms.Panel();
this.splitter1 = new System.Windows.Forms.Splitter();
this.panelText = new System.Windows.Forms.Panel();
this.txtIdentify = new System.Windows.Forms.TextBox();
this.panelHTML = new System.Windows.Forms.Panel();
this.webBrowserControl = new System.Windows.Forms.WebBrowser();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPageFeatures = new System.Windows.Forms.TabPage();
this.tabPageText = new System.Windows.Forms.TabPage();
this.tabPageHTML = new System.Windows.Forms.TabPage();
this.panelFeatures.SuspendLayout();
this.panelText.SuspendLayout();
this.panelHTML.SuspendLayout();
this.tabControl1.SuspendLayout();
this.tabPageFeatures.SuspendLayout();
this.tabPageText.SuspendLayout();
this.tabPageHTML.SuspendLayout();
this.SuspendLayout();
//
// listValues
//
resources.ApplyResources(this.listValues, "listValues");
this.listValues.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.listValues.FullRowSelect = true;
this.listValues.GridLines = true;
this.listValues.Name = "listValues";
this.listValues.UseCompatibleStateImageBehavior = false;
this.listValues.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Tag = "Field";
resources.ApplyResources(this.columnHeader1, "columnHeader1");
//
// columnHeader2
//
this.columnHeader2.Tag = "Value";
resources.ApplyResources(this.columnHeader2, "columnHeader2");
//
// treeObjects
//
resources.ApplyResources(this.treeObjects, "treeObjects");
this.treeObjects.HideSelection = false;
this.treeObjects.ImageList = this.imageList1;
this.treeObjects.Name = "treeObjects";
this.treeObjects.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.treeObjects_BeforeExpand);
this.treeObjects.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeObjects_AfterSelect);
this.treeObjects.MouseClick += new System.Windows.Forms.MouseEventHandler(this.treeObjects_MouseClick);
this.treeObjects.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeObjects_MouseDown);
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "tab.gif");
this.imageList1.Images.SetKeyName(1, "");
//
// txtLocation
//
resources.ApplyResources(this.txtLocation, "txtLocation");
this.txtLocation.Name = "txtLocation";
//
// panelFeatures
//
resources.ApplyResources(this.panelFeatures, "panelFeatures");
this.panelFeatures.Controls.Add(this.listValues);
this.panelFeatures.Controls.Add(this.splitter1);
this.panelFeatures.Controls.Add(this.treeObjects);
this.panelFeatures.Name = "panelFeatures";
//
// splitter1
//
resources.ApplyResources(this.splitter1, "splitter1");
this.splitter1.Name = "splitter1";
this.splitter1.TabStop = false;
//
// panelText
//
resources.ApplyResources(this.panelText, "panelText");
this.panelText.Controls.Add(this.txtIdentify);
this.panelText.Name = "panelText";
//
// txtIdentify
//
resources.ApplyResources(this.txtIdentify, "txtIdentify");
this.txtIdentify.BackColor = System.Drawing.Color.White;
this.txtIdentify.Name = "txtIdentify";
this.txtIdentify.ReadOnly = true;
//
// panelHTML
//
resources.ApplyResources(this.panelHTML, "panelHTML");
this.panelHTML.Controls.Add(this.webBrowserControl);
this.panelHTML.Name = "panelHTML";
//
// webBrowserControl
//
resources.ApplyResources(this.webBrowserControl, "webBrowserControl");
this.webBrowserControl.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowserControl.Name = "webBrowserControl";
//
// tabControl1
//
resources.ApplyResources(this.tabControl1, "tabControl1");
this.tabControl1.Controls.Add(this.tabPageFeatures);
this.tabControl1.Controls.Add(this.tabPageText);
this.tabControl1.Controls.Add(this.tabPageHTML);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
//
// tabPageFeatures
//
resources.ApplyResources(this.tabPageFeatures, "tabPageFeatures");
this.tabPageFeatures.Controls.Add(this.panelFeatures);
this.tabPageFeatures.Name = "tabPageFeatures";
this.tabPageFeatures.UseVisualStyleBackColor = true;
//
// tabPageText
//
resources.ApplyResources(this.tabPageText, "tabPageText");
this.tabPageText.Controls.Add(this.panelText);
this.tabPageText.Name = "tabPageText";
this.tabPageText.UseVisualStyleBackColor = true;
//
// tabPageHTML
//
resources.ApplyResources(this.tabPageHTML, "tabPageHTML");
this.tabPageHTML.Controls.Add(this.panelHTML);
this.tabPageHTML.Name = "tabPageHTML";
this.tabPageHTML.UseVisualStyleBackColor = true;
//
// FormIdentify
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.txtLocation);
this.Name = "FormIdentify";
this.panelFeatures.ResumeLayout(false);
this.panelText.ResumeLayout(false);
this.panelText.PerformLayout();
this.panelHTML.ResumeLayout(false);
this.tabControl1.ResumeLayout(false);
this.tabPageFeatures.ResumeLayout(false);
this.tabPageText.ResumeLayout(false);
this.tabPageHTML.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ListView listValues;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.TextBox txtLocation;
private System.Windows.Forms.TreeView treeObjects;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.Panel panelFeatures;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panelText;
private System.Windows.Forms.TextBox txtIdentify;
private System.Windows.Forms.Panel panelHTML;
private System.Windows.Forms.WebBrowser webBrowserControl;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPageFeatures;
private System.Windows.Forms.TabPage tabPageText;
private System.Windows.Forms.TabPage tabPageHTML;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/logging/v2/logging_config.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Cloud.Logging.V2 {
/// <summary>Holder for reflection information generated from google/logging/v2/logging_config.proto</summary>
public static partial class LoggingConfigReflection {
#region Descriptor
/// <summary>File descriptor for google/logging/v2/logging_config.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static LoggingConfigReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiZnb29nbGUvbG9nZ2luZy92Mi9sb2dnaW5nX2NvbmZpZy5wcm90bxIRZ29v",
"Z2xlLmxvZ2dpbmcudjIaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8a",
"G2dvb2dsZS9wcm90b2J1Zi9lbXB0eS5wcm90bxofZ29vZ2xlL3Byb3RvYnVm",
"L3RpbWVzdGFtcC5wcm90byLXAgoHTG9nU2luaxIMCgRuYW1lGAEgASgJEhMK",
"C2Rlc3RpbmF0aW9uGAMgASgJEg4KBmZpbHRlchgFIAEoCRJHChVvdXRwdXRf",
"dmVyc2lvbl9mb3JtYXQYBiABKA4yKC5nb29nbGUubG9nZ2luZy52Mi5Mb2dT",
"aW5rLlZlcnNpb25Gb3JtYXQSFwoPd3JpdGVyX2lkZW50aXR5GAggASgJEhgK",
"EGluY2x1ZGVfY2hpbGRyZW4YCSABKAgSLgoKc3RhcnRfdGltZRgKIAEoCzIa",
"Lmdvb2dsZS5wcm90b2J1Zi5UaW1lc3RhbXASLAoIZW5kX3RpbWUYCyABKAsy",
"Gi5nb29nbGUucHJvdG9idWYuVGltZXN0YW1wIj8KDVZlcnNpb25Gb3JtYXQS",
"HgoaVkVSU0lPTl9GT1JNQVRfVU5TUEVDSUZJRUQQABIGCgJWMhABEgYKAlYx",
"EAIiSQoQTGlzdFNpbmtzUmVxdWVzdBIOCgZwYXJlbnQYASABKAkSEgoKcGFn",
"ZV90b2tlbhgCIAEoCRIRCglwYWdlX3NpemUYAyABKAUiVwoRTGlzdFNpbmtz",
"UmVzcG9uc2USKQoFc2lua3MYASADKAsyGi5nb29nbGUubG9nZ2luZy52Mi5M",
"b2dTaW5rEhcKD25leHRfcGFnZV90b2tlbhgCIAEoCSIjCg5HZXRTaW5rUmVx",
"dWVzdBIRCglzaW5rX25hbWUYASABKAkibQoRQ3JlYXRlU2lua1JlcXVlc3QS",
"DgoGcGFyZW50GAEgASgJEigKBHNpbmsYAiABKAsyGi5nb29nbGUubG9nZ2lu",
"Zy52Mi5Mb2dTaW5rEh4KFnVuaXF1ZV93cml0ZXJfaWRlbnRpdHkYAyABKAgi",
"cAoRVXBkYXRlU2lua1JlcXVlc3QSEQoJc2lua19uYW1lGAEgASgJEigKBHNp",
"bmsYAiABKAsyGi5nb29nbGUubG9nZ2luZy52Mi5Mb2dTaW5rEh4KFnVuaXF1",
"ZV93cml0ZXJfaWRlbnRpdHkYAyABKAgiJgoRRGVsZXRlU2lua1JlcXVlc3QS",
"EQoJc2lua19uYW1lGAEgASgJMv4ECg9Db25maWdTZXJ2aWNlVjISfQoJTGlz",
"dFNpbmtzEiMuZ29vZ2xlLmxvZ2dpbmcudjIuTGlzdFNpbmtzUmVxdWVzdBok",
"Lmdvb2dsZS5sb2dnaW5nLnYyLkxpc3RTaW5rc1Jlc3BvbnNlIiWC0+STAh8S",
"HS92Mi97cGFyZW50PXByb2plY3RzLyp9L3NpbmtzEnQKB0dldFNpbmsSIS5n",
"b29nbGUubG9nZ2luZy52Mi5HZXRTaW5rUmVxdWVzdBoaLmdvb2dsZS5sb2dn",
"aW5nLnYyLkxvZ1NpbmsiKoLT5JMCJBIiL3YyL3tzaW5rX25hbWU9cHJvamVj",
"dHMvKi9zaW5rcy8qfRJ7CgpDcmVhdGVTaW5rEiQuZ29vZ2xlLmxvZ2dpbmcu",
"djIuQ3JlYXRlU2lua1JlcXVlc3QaGi5nb29nbGUubG9nZ2luZy52Mi5Mb2dT",
"aW5rIiuC0+STAiUiHS92Mi97cGFyZW50PXByb2plY3RzLyp9L3NpbmtzOgRz",
"aW5rEoABCgpVcGRhdGVTaW5rEiQuZ29vZ2xlLmxvZ2dpbmcudjIuVXBkYXRl",
"U2lua1JlcXVlc3QaGi5nb29nbGUubG9nZ2luZy52Mi5Mb2dTaW5rIjCC0+ST",
"AioaIi92Mi97c2lua19uYW1lPXByb2plY3RzLyovc2lua3MvKn06BHNpbmsS",
"dgoKRGVsZXRlU2luaxIkLmdvb2dsZS5sb2dnaW5nLnYyLkRlbGV0ZVNpbmtS",
"ZXF1ZXN0GhYuZ29vZ2xlLnByb3RvYnVmLkVtcHR5IiqC0+STAiQqIi92Mi97",
"c2lua19uYW1lPXByb2plY3RzLyovc2lua3MvKn1CgQEKFWNvbS5nb29nbGUu",
"bG9nZ2luZy52MkISTG9nZ2luZ0NvbmZpZ1Byb3RvUAFaOGdvb2dsZS5nb2xh",
"bmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvbG9nZ2luZy92Mjtsb2dnaW5n",
"qgIXR29vZ2xlLkNsb3VkLkxvZ2dpbmcuVjJiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.EmptyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.LogSink), global::Google.Cloud.Logging.V2.LogSink.Parser, new[]{ "Name", "Destination", "Filter", "OutputVersionFormat", "WriterIdentity", "IncludeChildren", "StartTime", "EndTime" }, null, new[]{ typeof(global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat) }, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListSinksRequest), global::Google.Cloud.Logging.V2.ListSinksRequest.Parser, new[]{ "Parent", "PageToken", "PageSize" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.ListSinksResponse), global::Google.Cloud.Logging.V2.ListSinksResponse.Parser, new[]{ "Sinks", "NextPageToken" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.GetSinkRequest), global::Google.Cloud.Logging.V2.GetSinkRequest.Parser, new[]{ "SinkName" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.CreateSinkRequest), global::Google.Cloud.Logging.V2.CreateSinkRequest.Parser, new[]{ "Parent", "Sink", "UniqueWriterIdentity" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.UpdateSinkRequest), global::Google.Cloud.Logging.V2.UpdateSinkRequest.Parser, new[]{ "SinkName", "Sink", "UniqueWriterIdentity" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Logging.V2.DeleteSinkRequest), global::Google.Cloud.Logging.V2.DeleteSinkRequest.Parser, new[]{ "SinkName" }, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Describes a sink used to export log entries to one of the following
/// destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a
/// Cloud Pub/Sub topic. A logs filter controls which log entries are
/// exported. The sink must be created within a project, organization, billing
/// account, or folder.
/// </summary>
public sealed partial class LogSink : pb::IMessage<LogSink> {
private static readonly pb::MessageParser<LogSink> _parser = new pb::MessageParser<LogSink>(() => new LogSink());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<LogSink> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogSink() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogSink(LogSink other) : this() {
name_ = other.name_;
destination_ = other.destination_;
filter_ = other.filter_;
outputVersionFormat_ = other.outputVersionFormat_;
writerIdentity_ = other.writerIdentity_;
includeChildren_ = other.includeChildren_;
StartTime = other.startTime_ != null ? other.StartTime.Clone() : null;
EndTime = other.endTime_ != null ? other.EndTime.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public LogSink Clone() {
return new LogSink(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// Required. The client-assigned sink identifier, unique within the
/// project. Example: `"my-syslog-errors-to-pubsub"`. Sink identifiers are
/// limited to 100 characters and can include only the following characters:
/// upper and lower-case alphanumeric characters, underscores, hyphens, and
/// periods.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "destination" field.</summary>
public const int DestinationFieldNumber = 3;
private string destination_ = "";
/// <summary>
/// Required. The export destination:
///
/// "storage.googleapis.com/[GCS_BUCKET]"
/// "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]"
/// "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]"
///
/// The sink's `writer_identity`, set when the sink is created, must
/// have permission to write to the destination or else the log
/// entries are not exported. For more information, see
/// [Exporting Logs With Sinks](/logging/docs/api/tasks/exporting-logs).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Destination {
get { return destination_; }
set {
destination_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "filter" field.</summary>
public const int FilterFieldNumber = 5;
private string filter_ = "";
/// <summary>
/// Optional.
/// An [advanced logs filter](/logging/docs/view/advanced_filters). The only
/// exported log entries are those that are in the resource owning the sink and
/// that match the filter. The filter must use the log entry format specified
/// by the `output_version_format` parameter. For example, in the v2 format:
///
/// logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Filter {
get { return filter_; }
set {
filter_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "output_version_format" field.</summary>
public const int OutputVersionFormatFieldNumber = 6;
private global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat outputVersionFormat_ = 0;
/// <summary>
/// Optional. The log entry format to use for this sink's exported log
/// entries. The v2 format is used by default.
/// **The v1 format is deprecated** and should be used only as part of a
/// migration effort to v2.
/// See [Migration to the v2 API](/logging/docs/api/v2/migration-to-v2).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat OutputVersionFormat {
get { return outputVersionFormat_; }
set {
outputVersionFormat_ = value;
}
}
/// <summary>Field number for the "writer_identity" field.</summary>
public const int WriterIdentityFieldNumber = 8;
private string writerIdentity_ = "";
/// <summary>
/// Output only. An IAM identity&mdash;a service account or group&mdash;under
/// which Stackdriver Logging writes the exported log entries to the sink's
/// destination. This field is set by
/// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
/// and
/// [sinks.update](/logging/docs/api/reference/rest/v2/projects.sinks/update),
/// based on the setting of `unique_writer_identity` in those methods.
///
/// Until you grant this identity write-access to the destination, log entry
/// exports from this sink will fail. For more information,
/// see [Granting access for a
/// resource](/iam/docs/granting-roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource).
/// Consult the destination service's documentation to determine the
/// appropriate IAM roles to assign to the identity.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string WriterIdentity {
get { return writerIdentity_; }
set {
writerIdentity_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "include_children" field.</summary>
public const int IncludeChildrenFieldNumber = 9;
private bool includeChildren_;
/// <summary>
/// Optional. This field applies only to sinks owned by organizations and
/// folders. If the field is false, the default, only the logs owned by the
/// sink's parent resource are available for export. If the field is true, then
/// logs from all the projects, folders, and billing accounts contained in the
/// sink's parent resource are also available for export. Whether a particular
/// log entry from the children is exported depends on the sink's filter
/// expression. For example, if this field is true, then the filter
/// `resource.type=gce_instance` would export all Compute Engine VM instance
/// log entries from all projects in the sink's parent. To only export entries
/// from certain child projects, filter on the project part of the log name:
///
/// logName:("projects/test-project1/" OR "projects/test-project2/") AND
/// resource.type=gce_instance
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IncludeChildren {
get { return includeChildren_; }
set {
includeChildren_ = value;
}
}
/// <summary>Field number for the "start_time" field.</summary>
public const int StartTimeFieldNumber = 10;
private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_;
/// <summary>
/// Optional. The time at which this sink will begin exporting log entries.
/// Log entries are exported only if their timestamp is not earlier than the
/// start time. The default value of this field is the time the sink is
/// created or updated.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime {
get { return startTime_; }
set {
startTime_ = value;
}
}
/// <summary>Field number for the "end_time" field.</summary>
public const int EndTimeFieldNumber = 11;
private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_;
/// <summary>
/// Optional. The time at which this sink will stop exporting log entries. Log
/// entries are exported only if their timestamp is earlier than the end time.
/// If this field is not supplied, there is no end time. If both a start time
/// and an end time are provided, then the end time must be later than the
/// start time.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime {
get { return endTime_; }
set {
endTime_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as LogSink);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(LogSink other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Destination != other.Destination) return false;
if (Filter != other.Filter) return false;
if (OutputVersionFormat != other.OutputVersionFormat) return false;
if (WriterIdentity != other.WriterIdentity) return false;
if (IncludeChildren != other.IncludeChildren) return false;
if (!object.Equals(StartTime, other.StartTime)) return false;
if (!object.Equals(EndTime, other.EndTime)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Destination.Length != 0) hash ^= Destination.GetHashCode();
if (Filter.Length != 0) hash ^= Filter.GetHashCode();
if (OutputVersionFormat != 0) hash ^= OutputVersionFormat.GetHashCode();
if (WriterIdentity.Length != 0) hash ^= WriterIdentity.GetHashCode();
if (IncludeChildren != false) hash ^= IncludeChildren.GetHashCode();
if (startTime_ != null) hash ^= StartTime.GetHashCode();
if (endTime_ != null) hash ^= EndTime.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Destination.Length != 0) {
output.WriteRawTag(26);
output.WriteString(Destination);
}
if (Filter.Length != 0) {
output.WriteRawTag(42);
output.WriteString(Filter);
}
if (OutputVersionFormat != 0) {
output.WriteRawTag(48);
output.WriteEnum((int) OutputVersionFormat);
}
if (WriterIdentity.Length != 0) {
output.WriteRawTag(66);
output.WriteString(WriterIdentity);
}
if (IncludeChildren != false) {
output.WriteRawTag(72);
output.WriteBool(IncludeChildren);
}
if (startTime_ != null) {
output.WriteRawTag(82);
output.WriteMessage(StartTime);
}
if (endTime_ != null) {
output.WriteRawTag(90);
output.WriteMessage(EndTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Destination.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Destination);
}
if (Filter.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Filter);
}
if (OutputVersionFormat != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OutputVersionFormat);
}
if (WriterIdentity.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(WriterIdentity);
}
if (IncludeChildren != false) {
size += 1 + 1;
}
if (startTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime);
}
if (endTime_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(LogSink other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Destination.Length != 0) {
Destination = other.Destination;
}
if (other.Filter.Length != 0) {
Filter = other.Filter;
}
if (other.OutputVersionFormat != 0) {
OutputVersionFormat = other.OutputVersionFormat;
}
if (other.WriterIdentity.Length != 0) {
WriterIdentity = other.WriterIdentity;
}
if (other.IncludeChildren != false) {
IncludeChildren = other.IncludeChildren;
}
if (other.startTime_ != null) {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
StartTime.MergeFrom(other.StartTime);
}
if (other.endTime_ != null) {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
EndTime.MergeFrom(other.EndTime);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Name = input.ReadString();
break;
}
case 26: {
Destination = input.ReadString();
break;
}
case 42: {
Filter = input.ReadString();
break;
}
case 48: {
outputVersionFormat_ = (global::Google.Cloud.Logging.V2.LogSink.Types.VersionFormat) input.ReadEnum();
break;
}
case 66: {
WriterIdentity = input.ReadString();
break;
}
case 72: {
IncludeChildren = input.ReadBool();
break;
}
case 82: {
if (startTime_ == null) {
startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(startTime_);
break;
}
case 90: {
if (endTime_ == null) {
endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
}
input.ReadMessage(endTime_);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the LogSink message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// Available log entry formats. Log entries can be written to Stackdriver
/// Logging in either format and can be exported in either format.
/// Version 2 is the preferred format.
/// </summary>
public enum VersionFormat {
/// <summary>
/// An unspecified format version that will default to V2.
/// </summary>
[pbr::OriginalName("VERSION_FORMAT_UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// `LogEntry` version 2 format.
/// </summary>
[pbr::OriginalName("V2")] V2 = 1,
/// <summary>
/// `LogEntry` version 1 format.
/// </summary>
[pbr::OriginalName("V1")] V1 = 2,
}
}
#endregion
}
/// <summary>
/// The parameters to `ListSinks`.
/// </summary>
public sealed partial class ListSinksRequest : pb::IMessage<ListSinksRequest> {
private static readonly pb::MessageParser<ListSinksRequest> _parser = new pb::MessageParser<ListSinksRequest>(() => new ListSinksRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListSinksRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksRequest(ListSinksRequest other) : this() {
parent_ = other.parent_;
pageToken_ = other.pageToken_;
pageSize_ = other.pageSize_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksRequest Clone() {
return new ListSinksRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// Required. The parent resource whose sinks are to be listed:
///
/// "projects/[PROJECT_ID]"
/// "organizations/[ORGANIZATION_ID]"
/// "billingAccounts/[BILLING_ACCOUNT_ID]"
/// "folders/[FOLDER_ID]"
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_token" field.</summary>
public const int PageTokenFieldNumber = 2;
private string pageToken_ = "";
/// <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>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string PageToken {
get { return pageToken_; }
set {
pageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "page_size" field.</summary>
public const int PageSizeFieldNumber = 3;
private int pageSize_;
/// <summary>
/// Optional. The maximum number of results to return from this request.
/// Non-positive values are ignored. The presence of `nextPageToken` in the
/// response indicates that more results might be available.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int PageSize {
get { return pageSize_; }
set {
pageSize_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListSinksRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListSinksRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (PageToken != other.PageToken) return false;
if (PageSize != other.PageSize) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (PageToken.Length != 0) hash ^= PageToken.GetHashCode();
if (PageSize != 0) hash ^= PageSize.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (PageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PageToken);
}
if (PageSize != 0) {
output.WriteRawTag(24);
output.WriteInt32(PageSize);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (PageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PageToken);
}
if (PageSize != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PageSize);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListSinksRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.PageToken.Length != 0) {
PageToken = other.PageToken;
}
if (other.PageSize != 0) {
PageSize = other.PageSize;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Parent = input.ReadString();
break;
}
case 18: {
PageToken = input.ReadString();
break;
}
case 24: {
PageSize = input.ReadInt32();
break;
}
}
}
}
}
/// <summary>
/// Result returned from `ListSinks`.
/// </summary>
public sealed partial class ListSinksResponse : pb::IMessage<ListSinksResponse> {
private static readonly pb::MessageParser<ListSinksResponse> _parser = new pb::MessageParser<ListSinksResponse>(() => new ListSinksResponse());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ListSinksResponse> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksResponse() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksResponse(ListSinksResponse other) : this() {
sinks_ = other.sinks_.Clone();
nextPageToken_ = other.nextPageToken_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ListSinksResponse Clone() {
return new ListSinksResponse(this);
}
/// <summary>Field number for the "sinks" field.</summary>
public const int SinksFieldNumber = 1;
private static readonly pb::FieldCodec<global::Google.Cloud.Logging.V2.LogSink> _repeated_sinks_codec
= pb::FieldCodec.ForMessage(10, global::Google.Cloud.Logging.V2.LogSink.Parser);
private readonly pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink> sinks_ = new pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink>();
/// <summary>
/// A list of sinks.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Google.Cloud.Logging.V2.LogSink> Sinks {
get { return sinks_; }
}
/// <summary>Field number for the "next_page_token" field.</summary>
public const int NextPageTokenFieldNumber = 2;
private string nextPageToken_ = "";
/// <summary>
/// If there might be more results than appear in this response, then
/// `nextPageToken` is included. To get the next set of results, call the same
/// method again using the value of `nextPageToken` as `pageToken`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string NextPageToken {
get { return nextPageToken_; }
set {
nextPageToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ListSinksResponse);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ListSinksResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!sinks_.Equals(other.sinks_)) return false;
if (NextPageToken != other.NextPageToken) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= sinks_.GetHashCode();
if (NextPageToken.Length != 0) hash ^= NextPageToken.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
sinks_.WriteTo(output, _repeated_sinks_codec);
if (NextPageToken.Length != 0) {
output.WriteRawTag(18);
output.WriteString(NextPageToken);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += sinks_.CalculateSize(_repeated_sinks_codec);
if (NextPageToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(NextPageToken);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ListSinksResponse other) {
if (other == null) {
return;
}
sinks_.Add(other.sinks_);
if (other.NextPageToken.Length != 0) {
NextPageToken = other.NextPageToken;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
sinks_.AddEntriesFrom(input, _repeated_sinks_codec);
break;
}
case 18: {
NextPageToken = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The parameters to `GetSink`.
/// </summary>
public sealed partial class GetSinkRequest : pb::IMessage<GetSinkRequest> {
private static readonly pb::MessageParser<GetSinkRequest> _parser = new pb::MessageParser<GetSinkRequest>(() => new GetSinkRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<GetSinkRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSinkRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSinkRequest(GetSinkRequest other) : this() {
sinkName_ = other.sinkName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public GetSinkRequest Clone() {
return new GetSinkRequest(this);
}
/// <summary>Field number for the "sink_name" field.</summary>
public const int SinkNameFieldNumber = 1;
private string sinkName_ = "";
/// <summary>
/// Required. The resource name of the sink:
///
/// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
/// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
/// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
/// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
///
/// Example: `"projects/my-project-id/sinks/my-sink-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SinkName {
get { return sinkName_; }
set {
sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as GetSinkRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(GetSinkRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SinkName != other.SinkName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SinkName.Length != 0) hash ^= SinkName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SinkName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(SinkName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SinkName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(GetSinkRequest other) {
if (other == null) {
return;
}
if (other.SinkName.Length != 0) {
SinkName = other.SinkName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
SinkName = input.ReadString();
break;
}
}
}
}
}
/// <summary>
/// The parameters to `CreateSink`.
/// </summary>
public sealed partial class CreateSinkRequest : pb::IMessage<CreateSinkRequest> {
private static readonly pb::MessageParser<CreateSinkRequest> _parser = new pb::MessageParser<CreateSinkRequest>(() => new CreateSinkRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CreateSinkRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateSinkRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateSinkRequest(CreateSinkRequest other) : this() {
parent_ = other.parent_;
Sink = other.sink_ != null ? other.Sink.Clone() : null;
uniqueWriterIdentity_ = other.uniqueWriterIdentity_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CreateSinkRequest Clone() {
return new CreateSinkRequest(this);
}
/// <summary>Field number for the "parent" field.</summary>
public const int ParentFieldNumber = 1;
private string parent_ = "";
/// <summary>
/// Required. The resource in which to create the sink:
///
/// "projects/[PROJECT_ID]"
/// "organizations/[ORGANIZATION_ID]"
/// "billingAccounts/[BILLING_ACCOUNT_ID]"
/// "folders/[FOLDER_ID]"
///
/// Examples: `"projects/my-logging-project"`, `"organizations/123456789"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Parent {
get { return parent_; }
set {
parent_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "sink" field.</summary>
public const int SinkFieldNumber = 2;
private global::Google.Cloud.Logging.V2.LogSink sink_;
/// <summary>
/// Required. The new sink, whose `name` parameter is a sink identifier that
/// is not already in use.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Logging.V2.LogSink Sink {
get { return sink_; }
set {
sink_ = value;
}
}
/// <summary>Field number for the "unique_writer_identity" field.</summary>
public const int UniqueWriterIdentityFieldNumber = 3;
private bool uniqueWriterIdentity_;
/// <summary>
/// Optional. Determines the kind of IAM identity returned as `writer_identity`
/// in the new sink. If this value is omitted or set to false, and if the
/// sink's parent is a project, then the value returned as `writer_identity` is
/// the same group or service account used by Stackdriver Logging before the
/// addition of writer identities to this API. The sink's destination must be
/// in the same project as the sink itself.
///
/// If this field is set to true, or if the sink is owned by a non-project
/// resource such as an organization, then the value of `writer_identity` will
/// be a unique service account used only for exports from the new sink. For
/// more information, see `writer_identity` in [LogSink][google.logging.v2.LogSink].
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool UniqueWriterIdentity {
get { return uniqueWriterIdentity_; }
set {
uniqueWriterIdentity_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CreateSinkRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CreateSinkRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Parent != other.Parent) return false;
if (!object.Equals(Sink, other.Sink)) return false;
if (UniqueWriterIdentity != other.UniqueWriterIdentity) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Parent.Length != 0) hash ^= Parent.GetHashCode();
if (sink_ != null) hash ^= Sink.GetHashCode();
if (UniqueWriterIdentity != false) hash ^= UniqueWriterIdentity.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Parent.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Parent);
}
if (sink_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Sink);
}
if (UniqueWriterIdentity != false) {
output.WriteRawTag(24);
output.WriteBool(UniqueWriterIdentity);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Parent.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Parent);
}
if (sink_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sink);
}
if (UniqueWriterIdentity != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CreateSinkRequest other) {
if (other == null) {
return;
}
if (other.Parent.Length != 0) {
Parent = other.Parent;
}
if (other.sink_ != null) {
if (sink_ == null) {
sink_ = new global::Google.Cloud.Logging.V2.LogSink();
}
Sink.MergeFrom(other.Sink);
}
if (other.UniqueWriterIdentity != false) {
UniqueWriterIdentity = other.UniqueWriterIdentity;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Parent = input.ReadString();
break;
}
case 18: {
if (sink_ == null) {
sink_ = new global::Google.Cloud.Logging.V2.LogSink();
}
input.ReadMessage(sink_);
break;
}
case 24: {
UniqueWriterIdentity = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// The parameters to `UpdateSink`.
/// </summary>
public sealed partial class UpdateSinkRequest : pb::IMessage<UpdateSinkRequest> {
private static readonly pb::MessageParser<UpdateSinkRequest> _parser = new pb::MessageParser<UpdateSinkRequest>(() => new UpdateSinkRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UpdateSinkRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSinkRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSinkRequest(UpdateSinkRequest other) : this() {
sinkName_ = other.sinkName_;
Sink = other.sink_ != null ? other.Sink.Clone() : null;
uniqueWriterIdentity_ = other.uniqueWriterIdentity_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UpdateSinkRequest Clone() {
return new UpdateSinkRequest(this);
}
/// <summary>Field number for the "sink_name" field.</summary>
public const int SinkNameFieldNumber = 1;
private string sinkName_ = "";
/// <summary>
/// Required. The full resource name of the sink to update, including the
/// parent resource and the sink identifier:
///
/// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
/// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
/// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
/// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
///
/// Example: `"projects/my-project-id/sinks/my-sink-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SinkName {
get { return sinkName_; }
set {
sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "sink" field.</summary>
public const int SinkFieldNumber = 2;
private global::Google.Cloud.Logging.V2.LogSink sink_;
/// <summary>
/// Required. The updated sink, whose name is the same identifier that appears
/// as part of `sink_name`. If `sink_name` does not exist, then
/// this method creates a new sink.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Google.Cloud.Logging.V2.LogSink Sink {
get { return sink_; }
set {
sink_ = value;
}
}
/// <summary>Field number for the "unique_writer_identity" field.</summary>
public const int UniqueWriterIdentityFieldNumber = 3;
private bool uniqueWriterIdentity_;
/// <summary>
/// Optional. See
/// [sinks.create](/logging/docs/api/reference/rest/v2/projects.sinks/create)
/// for a description of this field. When updating a sink, the effect of this
/// field on the value of `writer_identity` in the updated sink depends on both
/// the old and new values of this field:
///
/// + If the old and new values of this field are both false or both true,
/// then there is no change to the sink's `writer_identity`.
/// + If the old value is false and the new value is true, then
/// `writer_identity` is changed to a unique service account.
/// + It is an error if the old value is true and the new value is false.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool UniqueWriterIdentity {
get { return uniqueWriterIdentity_; }
set {
uniqueWriterIdentity_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UpdateSinkRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UpdateSinkRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SinkName != other.SinkName) return false;
if (!object.Equals(Sink, other.Sink)) return false;
if (UniqueWriterIdentity != other.UniqueWriterIdentity) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SinkName.Length != 0) hash ^= SinkName.GetHashCode();
if (sink_ != null) hash ^= Sink.GetHashCode();
if (UniqueWriterIdentity != false) hash ^= UniqueWriterIdentity.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SinkName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(SinkName);
}
if (sink_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Sink);
}
if (UniqueWriterIdentity != false) {
output.WriteRawTag(24);
output.WriteBool(UniqueWriterIdentity);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SinkName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName);
}
if (sink_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sink);
}
if (UniqueWriterIdentity != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UpdateSinkRequest other) {
if (other == null) {
return;
}
if (other.SinkName.Length != 0) {
SinkName = other.SinkName;
}
if (other.sink_ != null) {
if (sink_ == null) {
sink_ = new global::Google.Cloud.Logging.V2.LogSink();
}
Sink.MergeFrom(other.Sink);
}
if (other.UniqueWriterIdentity != false) {
UniqueWriterIdentity = other.UniqueWriterIdentity;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
SinkName = input.ReadString();
break;
}
case 18: {
if (sink_ == null) {
sink_ = new global::Google.Cloud.Logging.V2.LogSink();
}
input.ReadMessage(sink_);
break;
}
case 24: {
UniqueWriterIdentity = input.ReadBool();
break;
}
}
}
}
}
/// <summary>
/// The parameters to `DeleteSink`.
/// </summary>
public sealed partial class DeleteSinkRequest : pb::IMessage<DeleteSinkRequest> {
private static readonly pb::MessageParser<DeleteSinkRequest> _parser = new pb::MessageParser<DeleteSinkRequest>(() => new DeleteSinkRequest());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<DeleteSinkRequest> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Cloud.Logging.V2.LoggingConfigReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSinkRequest() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSinkRequest(DeleteSinkRequest other) : this() {
sinkName_ = other.sinkName_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public DeleteSinkRequest Clone() {
return new DeleteSinkRequest(this);
}
/// <summary>Field number for the "sink_name" field.</summary>
public const int SinkNameFieldNumber = 1;
private string sinkName_ = "";
/// <summary>
/// Required. The full resource name of the sink to delete, including the
/// parent resource and the sink identifier:
///
/// "projects/[PROJECT_ID]/sinks/[SINK_ID]"
/// "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]"
/// "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]"
/// "folders/[FOLDER_ID]/sinks/[SINK_ID]"
///
/// Example: `"projects/my-project-id/sinks/my-sink-id"`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string SinkName {
get { return sinkName_; }
set {
sinkName_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as DeleteSinkRequest);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(DeleteSinkRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (SinkName != other.SinkName) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (SinkName.Length != 0) hash ^= SinkName.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (SinkName.Length != 0) {
output.WriteRawTag(10);
output.WriteString(SinkName);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (SinkName.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(SinkName);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(DeleteSinkRequest other) {
if (other == null) {
return;
}
if (other.SinkName.Length != 0) {
SinkName = other.SinkName;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
SinkName = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.
// #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count);
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>();
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count));
protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>();
protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection);
protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc);
protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result);
protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>());
protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection);
protected static TaskFactory ThreadFactory { get; } = new TaskFactory(
CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
private const double ConcurrencyTestSeconds =
#if StressTest
8.0;
#else
1.0;
#endif
[Fact]
public void Ctor_InvalidArgs_Throws()
{
Assert.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null));
}
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Equal(0, c.Count);
Assert.True(IsEmpty(c));
Assert.Equal(Enumerable.Empty<int>(), c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count));
Assert.Equal(oracle.Count == 0, IsEmpty(c));
Assert.Equal(oracle.Count, c.Count);
Assert.Equal<int>(oracle, c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
[InlineData(1000)]
public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems)
{
var expected = new HashSet<int>(Enumerable.Range(0, numItems));
IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected);
Assert.Equal(expected.Count, pcc.Count);
int item;
var actual = new HashSet<int>();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected.Count - i, pcc.Count);
Assert.True(pcc.TryTake(out item));
actual.Add(item);
}
Assert.False(pcc.TryTake(out item));
Assert.Equal(0, item);
AssertSetsEqual(expected, actual);
}
[Fact]
public void Add_TakeFromAnotherThread_ExpectedItemsTaken()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
const int NumItems = 100000;
Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i))));
var hs = new HashSet<int>();
while (hs.Count < NumItems)
{
int item;
if (c.TryTake(out item)) hs.Add(item);
}
producer.GetAwaiter().GetResult();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs);
}
[Fact]
public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle()
{
IProducerConsumerCollection<int> c = CreateOracle();
IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection();
Action take = () =>
{
int item1;
Assert.True(c.TryTake(out item1));
int item2;
Assert.True(oracle.TryTake(out item2));
Assert.Equal(item1, item2);
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
};
for (int i = 0; i < 100; i++)
{
Assert.True(oracle.TryAdd(i));
Assert.True(c.TryAdd(i));
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
// Start taking some after we've added some
if (i > 50)
{
take();
}
}
// Take the rest
while (c.Count > 0)
{
take();
}
}
[Fact]
public void AddTake_RandomChangesMatchOracle()
{
const int Iters = 1000;
var r = new Random(42);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Iters; i++)
{
if (r.NextDouble() < .5)
{
Assert.Equal(oracle.TryAdd(i), c.TryAdd(i));
}
else
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
Assert.Equal(oracle.Count, c.Count);
}
[Theory]
[InlineData(100, 1, 100, true)]
[InlineData(100, 4, 10, false)]
[InlineData(1000, 11, 100, true)]
[InlineData(100000, 2, 50000, true)]
public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems));
int successes = 0;
using (var b = new Barrier(threadsCount))
{
WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
for (int j = 0; j < itemsPerThread; j++)
{
int data;
if (take ? c.TryTake(out data) : TryPeek(c, out data))
{
Interlocked.Increment(ref successes);
Assert.NotEqual(0, data); // shouldn't be default(T)
}
}
})).ToArray());
}
Assert.Equal(
take ? numStartingItems : threadsCount * itemsPerThread,
successes);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < count; i++)
{
Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count));
}
Assert.Equal(oracle.ToArray(), c.ToArray());
if (count > 0)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Theory]
[InlineData(1, 10)]
[InlineData(2, 10)]
[InlineData(10, 10)]
[InlineData(100, 10)]
public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters)
{
IEnumerable<int> initialItems = Enumerable.Range(1, initialCount);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
for (int i = 0; i < iters; i++)
{
Assert.Equal<int>(oracle, c);
Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i));
Assert.Equal<int>(oracle, c);
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal<int>(oracle, c);
}
}
[Fact]
public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
for (int i = 0; i < 1000; i += 100)
{
// Create a thread that adds items to the collection
ThreadFactory.StartNew(() =>
{
for (int j = i; j < i + 100; j++)
{
Assert.True(c.TryAdd(j));
}
}).GetAwaiter().GetResult();
// Allow threads to be collected
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c));
}
[Fact]
public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000));
for (int i = 99999; i >= 0; --i)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
[Fact]
public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
int item;
for (int i = 0; i < 2; i++)
{
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
}
Assert.True(c.TryAdd(42));
for (int i = 0; i < 2; i++)
{
Assert.True(TryPeek(c, out item));
Assert.Equal(42, item);
}
Assert.True(c.TryTake(out item));
Assert.Equal(42, item);
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
Assert.False(c.TryTake(out item));
Assert.Equal(0, item);
}
[Fact]
public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse()
{
int items = 1000;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(0)); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c));
});
// Producer adds/takes a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(c.TryTake(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void CopyTo_Empty_NothingCopied()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
c.CopyTo(new int[0], 0);
c.CopyTo(new int[10], 10);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size];
c.CopyTo(actual, 0);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size];
oracle.CopyTo(expected, 0);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size + 2];
c.CopyTo(actual, 1);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size + 2];
oracle.CopyTo(expected, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
c.CopyTo(actual, 0);
ICollection oracle = CreateOracle(initialItems);
Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
oracle.CopyTo(expected, 0);
Assert.Equal(expected.Cast<int>(), actual.Cast<int>());
}
[Fact]
public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied()
{
int[] initialItems = Enumerable.Range(1, 10).ToArray();
const int LowerBound = 1;
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound });
c.CopyTo(actual, LowerBound);
ICollection oracle = CreateOracle(initialItems);
int[] expected = new int[initialItems.Length];
oracle.CopyTo(expected, 0);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual.GetValue(i + LowerBound));
}
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
int[] dest = new int[10];
Assert.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
Assert.Throws<ArgumentException>(() => c.CopyTo(new int[7, 7], 0));
}
[Fact]
public void ICollectionCopyTo_InvalidArgs_Throws()
{
ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
Array dest = new int[10];
Assert.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
}
[Theory]
[InlineData(100, 1, 10)]
[InlineData(4, 100000, 10)]
public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin)
{
var bc = new BlockingCollection<int>(CreateProducerConsumerCollection());
long dummy = 0;
Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 1; i <= numItemsPerThread; i++)
{
for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little
bc.Add(i);
}
})).ToArray();
Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 0; i < numItemsPerThread; i++)
{
const int TimeoutMs = 100000;
int item;
Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms");
Assert.NotEqual(0, item);
}
})).ToArray();
WaitAllOrAnyFailed(producers);
WaitAllOrAnyFailed(consumers);
}
[Fact]
public void GetEnumerator_NonGeneric()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IEnumerable e = c;
Assert.False(e.GetEnumerator().MoveNext());
Assert.True(c.TryAdd(42));
Assert.True(c.TryAdd(84));
var hs = new HashSet<int>(e.Cast<int>());
Assert.Equal(2, hs.Count);
Assert.Contains(42, hs);
Assert.Contains(84, hs);
}
[Fact]
public void GetEnumerator_EnumerationsAreSnapshots()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c);
using (IEnumerator<int> e1 = c.GetEnumerator())
{
Assert.True(c.TryAdd(1));
using (IEnumerator<int> e2 = c.GetEnumerator())
{
Assert.True(c.TryAdd(2));
using (IEnumerator<int> e3 = c.GetEnumerator())
{
int item;
Assert.True(c.TryTake(out item));
using (IEnumerator<int> e4 = c.GetEnumerator())
{
Assert.False(e1.MoveNext());
Assert.True(e2.MoveNext());
Assert.False(e2.MoveNext());
Assert.True(e3.MoveNext());
Assert.True(e3.MoveNext());
Assert.False(e3.MoveNext());
Assert.True(e4.MoveNext());
Assert.False(e4.MoveNext());
}
}
}
}
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(100, false)]
public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
using (var e = c.GetEnumerator())
{
Assert.False(e.MoveNext());
}
// Add, and validate enumeration after each item added
for (int i = 1; i <= numItems; i++)
{
Assert.True(c.TryAdd(i));
Assert.Equal(i, c.Count);
Assert.Equal(i, c.Distinct().Count());
}
// Take, and validate enumerate after each item removed.
Action consume = () =>
{
for (int i = 1; i <= numItems; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.Equal(numItems - i, c.Count);
Assert.Equal(numItems - i, c.Distinct().Count());
}
};
if (consumeFromSameThread)
{
consume();
}
else
{
await ThreadFactory.StartNew(consume);
}
}
[Fact]
public void TryAdd_TryTake_ToArray()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(42));
Assert.Equal(new[] { 42 }, c.ToArray());
Assert.True(c.TryAdd(84));
Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i));
int item;
Assert.True(c.TryTake(out item));
int remainingItem = item == 42 ? 84 : 42;
Assert.Equal(new[] { remainingItem }, c.ToArray());
Assert.True(c.TryTake(out item));
Assert.Equal(remainingItem, item);
Assert.Empty(c.ToArray());
}
[Fact]
public void ICollection_IsSynchronized_SyncRoot()
{
ICollection c = CreateProducerConsumerCollection();
Assert.False(c.IsSynchronized);
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ToArray_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c.ToArray());
Assert.Equal(NumItems, hs.Count);
});
}
[Fact]
public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes()
{
const int Items = 20;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(oracle.TryAdd(i));
Assert.Equal(oracle.ToArray(), c.ToArray());
}
for (int i = Items - 1; i >= 0; i--)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Fact]
public void GetEnumerator_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c);
Assert.Equal(NumItems, hs.Count);
});
}
[Theory]
[InlineData(1, ConcurrencyTestSeconds / 2)]
[InlineData(4, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
DateTime end = default(DateTime);
using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds)))
{
Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
int count = 0;
var rand = new Random();
while (DateTime.UtcNow < end)
{
if (rand.NextDouble() < .5)
{
Assert.True(c.TryAdd(rand.Next()));
count++;
}
else
{
int item;
if (c.TryTake(out item)) count--;
}
}
return count;
})).ToArray();
Task.WaitAll(tasks);
Assert.Equal(tasks.Sum(t => t.Result), c.Count);
}
}
[Theory]
[InlineData(3000000)]
[OuterLoop]
public void ManyConcurrentAddsTakes_CollectionRemainsConsistent(int operations)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
// Thread that adds
Task<HashSet<int>> adds = ThreadFactory.StartNew(() =>
{
for (int i = int.MinValue; i < (int.MinValue + operations); i++)
{
Assert.True(c.TryAdd(i));
}
return new HashSet<int>(Enumerable.Range(int.MinValue, operations));
});
// Thread that adds and takes
Task<KeyValuePair<HashSet<int>, HashSet<int>>> addsAndTakes = ThreadFactory.StartNew(() =>
{
var added = new HashSet<int>();
var taken = new HashSet<int>();
// avoid 0 as default(T), to detect accidentally reading a default value
for (int i = 1; i < (1 + operations); i++)
{
Assert.True(c.TryAdd(i));
added.Add(i);
int item;
if (c.TryTake(out item))
{
Assert.NotEqual(0, item);
taken.Add(item);
}
}
return new KeyValuePair<HashSet<int>, HashSet<int>>(added, taken);
});
// Thread that just takes
Task<HashSet<int>> takes = ThreadFactory.StartNew(() =>
{
var taken = new HashSet<int>();
for (int i = 1; i < (1 + operations); i++)
{
int item;
if (c.TryTake(out item))
{
Assert.NotEqual(0, item);
taken.Add(item);
}
}
return taken;
});
// Wait for them all to finish
WaitAllOrAnyFailed(adds, addsAndTakes, takes);
// Combine everything they added and remove everything they took
var total = new HashSet<int>(adds.Result);
total.UnionWith(addsAndTakes.Result.Key);
total.ExceptWith(addsAndTakes.Result.Value);
total.ExceptWith(takes.Result);
// What's left should match what's in the collection
Assert.Equal(total.OrderBy(i => i), c.OrderBy(i => i));
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
total++;
}
int item;
if (TryPeek(c, out item))
{
Assert.InRange(item, 1, MaxCount);
}
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item, 1, MaxCount);
}
}
}
return total;
});
Task<long> takesFromOtherThread = ThreadFactory.StartNew(() =>
{
long total = 0;
int item;
while (DateTime.UtcNow < end)
{
if (c.TryTake(out item))
{
total++;
Assert.InRange(item, 1, MaxCount);
}
}
return total;
});
WaitAllOrAnyFailed(addsTakes, takesFromOtherThread);
long remaining = addsTakes.Result - takesFromOtherThread.Result;
Assert.InRange(remaining, 0, long.MaxValue);
Assert.Equal(remaining, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds)
{
IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(new LargeStruct(i)));
total++;
}
LargeStruct item;
Assert.True(TryPeek(c, out item));
Assert.InRange(item.Value, 1, MaxCount);
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item.Value, 1, MaxCount);
}
}
}
return total;
});
Task peeksFromOtherThread = ThreadFactory.StartNew(() =>
{
LargeStruct item;
while (DateTime.UtcNow < end)
{
if (TryPeek(c, out item))
{
Assert.InRange(item.Value, 1, MaxCount);
}
}
});
WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread);
Assert.Equal(0, addsTakes.Result);
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.ToArray();
Assert.InRange(arr.Length, 0, MaxCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(0, ConcurrencyTestSeconds / 2)]
[InlineData(1, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.Select(i => i).ToArray();
Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(initialCount, c.Count);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
public void DebuggerAttributes_Success(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count);
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
}
[Fact]
public void DebuggerTypeProxy_Ctor_NullArgument_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Type proxyType = DebuggerAttributes.GetProxyType(c);
var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null }));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
Assert.Subset(expected, actual);
Assert.Subset(actual, expected);
}
protected static void WaitAllOrAnyFailed(params Task[] tasks)
{
if (tasks.Length == 0)
{
return;
}
int remaining = tasks.Length;
var mres = new ManualResetEventSlim();
foreach (Task task in tasks)
{
task.ContinueWith(t =>
{
if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted)
{
mres.Set();
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
mres.Wait();
// Either all tasks are completed or at least one failed
foreach (Task t in tasks)
{
if (t.IsFaulted)
{
t.GetAwaiter().GetResult(); // propagate for the first one that failed
}
}
}
private struct LargeStruct // used to help validate that values aren't torn while being read
{
private readonly long _a, _b, _c, _d, _e, _f, _g, _h;
public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; }
public long Value
{
get
{
if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h)
{
throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}");
}
return _a;
}
}
}
}
}
| |
/*
* Qa full api
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: all
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace HostMe.Sdk.Model
{
/// <summary>
/// TableMonitor
/// </summary>
[DataContract]
public partial class TableMonitor : IEquatable<TableMonitor>, IValidatableObject
{
/// <summary>
/// Gets or Sets Status
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum StatusEnum
{
/// <summary>
/// Enum Available for "Available"
/// </summary>
[EnumMember(Value = "Available")]
Available,
/// <summary>
/// Enum Busy for "Busy"
/// </summary>
[EnumMember(Value = "Busy")]
Busy,
/// <summary>
/// Enum Assigned for "Assigned"
/// </summary>
[EnumMember(Value = "Assigned")]
Assigned,
/// <summary>
/// Enum Reserved for "Reserved"
/// </summary>
[EnumMember(Value = "Reserved")]
Reserved,
/// <summary>
/// Enum Blocked for "Blocked"
/// </summary>
[EnumMember(Value = "Blocked")]
Blocked
}
/// <summary>
/// Gets or Sets Status
/// </summary>
[DataMember(Name="status", EmitDefaultValue=true)]
public StatusEnum? Status { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="TableMonitor" /> class.
/// </summary>
/// <param name="TableNumber">TableNumber.</param>
/// <param name="State">State.</param>
/// <param name="Status">Status.</param>
/// <param name="Type">Type.</param>
/// <param name="RegistrationTime">RegistrationTime.</param>
/// <param name="Id">Id.</param>
/// <param name="ReservationTime">ReservationTime.</param>
/// <param name="AssignmentTime">AssignmentTime.</param>
/// <param name="EstimatedReleaseTime">EstimatedReleaseTime.</param>
/// <param name="Waiter">Waiter.</param>
/// <param name="User">User.</param>
public TableMonitor(string TableNumber = null, string State = null, StatusEnum? Status = null, string Type = null, DateTimeOffset? RegistrationTime = null, string Id = null, DateTimeOffset? ReservationTime = null, DateTimeOffset? AssignmentTime = null, DateTimeOffset? EstimatedReleaseTime = null, WaiterMonitor Waiter = null, TableUserInfo User = null)
{
this.TableNumber = TableNumber;
this.State = State;
this.Status = Status;
this.Type = Type;
this.RegistrationTime = RegistrationTime;
this.Id = Id;
this.ReservationTime = ReservationTime;
this.AssignmentTime = AssignmentTime;
this.EstimatedReleaseTime = EstimatedReleaseTime;
this.Waiter = Waiter;
this.User = User;
}
/// <summary>
/// Gets or Sets TableNumber
/// </summary>
[DataMember(Name="tableNumber", EmitDefaultValue=true)]
public string TableNumber { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=true)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=true)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets RegistrationTime
/// </summary>
[DataMember(Name="registrationTime", EmitDefaultValue=true)]
public DateTimeOffset? RegistrationTime { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=true)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets ReservationTime
/// </summary>
[DataMember(Name="reservationTime", EmitDefaultValue=true)]
public DateTimeOffset? ReservationTime { get; set; }
/// <summary>
/// Gets or Sets AssignmentTime
/// </summary>
[DataMember(Name="assignmentTime", EmitDefaultValue=true)]
public DateTimeOffset? AssignmentTime { get; set; }
/// <summary>
/// Gets or Sets EstimatedReleaseTime
/// </summary>
[DataMember(Name="estimatedReleaseTime", EmitDefaultValue=true)]
public DateTimeOffset? EstimatedReleaseTime { get; set; }
/// <summary>
/// Gets or Sets Waiter
/// </summary>
[DataMember(Name="waiter", EmitDefaultValue=true)]
public WaiterMonitor Waiter { get; set; }
/// <summary>
/// Gets or Sets User
/// </summary>
[DataMember(Name="user", EmitDefaultValue=true)]
public TableUserInfo User { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class TableMonitor {\n");
sb.Append(" TableNumber: ").Append(TableNumber).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Status: ").Append(Status).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" RegistrationTime: ").Append(RegistrationTime).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ReservationTime: ").Append(ReservationTime).Append("\n");
sb.Append(" AssignmentTime: ").Append(AssignmentTime).Append("\n");
sb.Append(" EstimatedReleaseTime: ").Append(EstimatedReleaseTime).Append("\n");
sb.Append(" Waiter: ").Append(Waiter).Append("\n");
sb.Append(" User: ").Append(User).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as TableMonitor);
}
/// <summary>
/// Returns true if TableMonitor instances are equal
/// </summary>
/// <param name="other">Instance of TableMonitor to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(TableMonitor other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.TableNumber == other.TableNumber ||
this.TableNumber != null &&
this.TableNumber.Equals(other.TableNumber)
) &&
(
this.State == other.State ||
this.State != null &&
this.State.Equals(other.State)
) &&
(
this.Status == other.Status ||
this.Status != null &&
this.Status.Equals(other.Status)
) &&
(
this.Type == other.Type ||
this.Type != null &&
this.Type.Equals(other.Type)
) &&
(
this.RegistrationTime == other.RegistrationTime ||
this.RegistrationTime != null &&
this.RegistrationTime.Equals(other.RegistrationTime)
) &&
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.ReservationTime == other.ReservationTime ||
this.ReservationTime != null &&
this.ReservationTime.Equals(other.ReservationTime)
) &&
(
this.AssignmentTime == other.AssignmentTime ||
this.AssignmentTime != null &&
this.AssignmentTime.Equals(other.AssignmentTime)
) &&
(
this.EstimatedReleaseTime == other.EstimatedReleaseTime ||
this.EstimatedReleaseTime != null &&
this.EstimatedReleaseTime.Equals(other.EstimatedReleaseTime)
) &&
(
this.Waiter == other.Waiter ||
this.Waiter != null &&
this.Waiter.Equals(other.Waiter)
) &&
(
this.User == other.User ||
this.User != null &&
this.User.Equals(other.User)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.TableNumber != null)
hash = hash * 59 + this.TableNumber.GetHashCode();
if (this.State != null)
hash = hash * 59 + this.State.GetHashCode();
if (this.Status != null)
hash = hash * 59 + this.Status.GetHashCode();
if (this.Type != null)
hash = hash * 59 + this.Type.GetHashCode();
if (this.RegistrationTime != null)
hash = hash * 59 + this.RegistrationTime.GetHashCode();
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.ReservationTime != null)
hash = hash * 59 + this.ReservationTime.GetHashCode();
if (this.AssignmentTime != null)
hash = hash * 59 + this.AssignmentTime.GetHashCode();
if (this.EstimatedReleaseTime != null)
hash = hash * 59 + this.EstimatedReleaseTime.GetHashCode();
if (this.Waiter != null)
hash = hash * 59 + this.Waiter.GetHashCode();
if (this.User != null)
hash = hash * 59 + this.User.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// 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.Management.Automation;
using DiscUtils.PowerShell.VirtualDiskProvider;
namespace DiscUtils.PowerShell
{
[Cmdlet(VerbsCommon.New, "VirtualDisk")]
public class NewVirtualDiskCommand : PSCmdlet
{
[Parameter(Mandatory = true, Position = 0)]
public string LiteralPath { get; set; }
[Parameter(Mandatory = true, ParameterSetName="New")]
[ValidateLength(1,int.MaxValue)]
public string Type { get; set; }
[Parameter(Mandatory = true, ParameterSetName="New")]
public string Size { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Diff")]
public SwitchParameter Differencing { get; set; }
[Parameter(Mandatory = true, ParameterSetName = "Diff")]
public string BaseDisk { get; set; }
protected override void ProcessRecord()
{
if (ParameterSetName == "New")
{
CreateNewDisk();
}
else
{
CreateDiffDisk();
}
}
private void CreateNewDisk()
{
string[] typeAndVariant = Type.Split('-');
if (typeAndVariant.Length < 1 || typeAndVariant.Length > 2)
{
WriteError(new ErrorRecord(
new ArgumentException("Invalid Type of disk"),
"BadDiskType",
ErrorCategory.InvalidArgument,
null));
return;
}
long size;
if (!DiscUtils.Common.Utilities.TryParseDiskSize(Size, out size))
{
WriteError(new ErrorRecord(
new ArgumentException("Unable to parse the disk size"),
"BadDiskSize",
ErrorCategory.InvalidArgument,
null));
return;
}
string type = typeAndVariant[0];
string variant = typeAndVariant.Length > 1 ? typeAndVariant[1] : null;
string child;
PSObject parentObj = ResolveNewDiskPath(out child);
VirtualDisk disk = null;
if (parentObj.BaseObject is DirectoryInfo)
{
string path = Path.Combine(((DirectoryInfo)parentObj.BaseObject).FullName, child);
using (VirtualDisk realDisk = VirtualDisk.CreateDisk(type, variant, path, size, null, null)) { }
disk = new OnDemandVirtualDisk(path, FileAccess.ReadWrite);
}
else if (parentObj.BaseObject is DiscDirectoryInfo)
{
DiscDirectoryInfo ddi = (DiscDirectoryInfo)parentObj.BaseObject;
string path = Path.Combine(ddi.FullName, child);
using (VirtualDisk realDisk = VirtualDisk.CreateDisk(ddi.FileSystem, type, variant, path, size, null, null)) { }
disk = new OnDemandVirtualDisk(ddi.FileSystem, path, FileAccess.ReadWrite);
}
else
{
WriteError(new ErrorRecord(
new DirectoryNotFoundException("Cannot create a virtual disk in that location"),
"BadDiskLocation",
ErrorCategory.InvalidArgument,
null));
return;
}
WriteObject(disk, false);
}
private void CreateDiffDisk()
{
string child;
PSObject parentObj = ResolveNewDiskPath(out child);
PSObject baseDiskObj = SessionState.InvokeProvider.Item.Get(new string[] { BaseDisk }, false, true)[0];
VirtualDisk baseDisk = null;
try
{
if (baseDiskObj.BaseObject is FileInfo)
{
baseDisk = VirtualDisk.OpenDisk(((FileInfo)baseDiskObj.BaseObject).FullName, FileAccess.Read);
}
else if (baseDiskObj.BaseObject is DiscFileInfo)
{
DiscFileInfo dfi = (DiscFileInfo)baseDiskObj.BaseObject;
baseDisk = VirtualDisk.OpenDisk(dfi.FileSystem, dfi.FullName, FileAccess.Read);
}
else
{
WriteError(new ErrorRecord(
new FileNotFoundException("The file specified by the BaseDisk parameter doesn't exist"),
"BadBaseDiskLocation",
ErrorCategory.InvalidArgument,
null));
return;
}
VirtualDisk newDisk = null;
if (parentObj.BaseObject is DirectoryInfo)
{
string path = Path.Combine(((DirectoryInfo)parentObj.BaseObject).FullName, child);
using (baseDisk.CreateDifferencingDisk(path)) { }
newDisk = new OnDemandVirtualDisk(path, FileAccess.ReadWrite);
}
else if (parentObj.BaseObject is DiscDirectoryInfo)
{
DiscDirectoryInfo ddi = (DiscDirectoryInfo)parentObj.BaseObject;
string path = Path.Combine(ddi.FullName, child);
using (baseDisk.CreateDifferencingDisk(ddi.FileSystem, path)) { }
newDisk = new OnDemandVirtualDisk(ddi.FileSystem, path, FileAccess.ReadWrite);
}
else
{
WriteError(new ErrorRecord(
new DirectoryNotFoundException("Cannot create a virtual disk in that location"),
"BadDiskLocation",
ErrorCategory.InvalidArgument,
null));
return;
}
WriteObject(newDisk, false);
}
finally
{
if (baseDisk != null)
{
baseDisk.Dispose();
}
}
}
private PSObject ResolveNewDiskPath(out string child)
{
PSObject parentObj;
child = SessionState.Path.ParseChildName(LiteralPath);
string parent = SessionState.Path.ParseParent(LiteralPath, null);
PathInfo parentPath = this.SessionState.Path.GetResolvedPSPathFromPSPath(parent)[0];
parentObj = SessionState.InvokeProvider.Item.Get(new string[] { parentPath.Path }, false, true)[0];
// If we got a Volume, then we need to send a special marker to the provider indicating that we
// actually wanted the root directory on the volume, not the volume itself.
if (parentObj.BaseObject is VolumeInfo)
{
parentObj = SessionState.InvokeProvider.Item.Get(new string[] { Path.Combine(parentPath.Path, @"$Root") }, false, true)[0];
}
return parentObj;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Workflow.ComponentModel;
using System.Runtime.Serialization;
using System.Messaging;
namespace System.Workflow.Runtime
{
[Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")]
public class WorkflowQueuingService
{
Object syncRoot = new Object();
IWorkflowCoreRuntime rootWorkflowExecutor;
List<IComparable> dirtyQueues;
EventQueueState pendingQueueState = new EventQueueState();
Dictionary<IComparable, EventQueueState> persistedQueueStates;
// event handler used by atomic execution context's Q service for message delivery
List<WorkflowQueuingService> messageArrivalEventHandlers;
// set for inner queuing service
WorkflowQueuingService rootQueuingService;
// Runtime information visible to host, stored on the root activity
[SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
Justification = "Design has been approved. This is a false positive. DependencyProperty is an immutable type.")]
public readonly static DependencyProperty PendingMessagesProperty = DependencyProperty.RegisterAttached("PendingMessages", typeof(Queue), typeof(WorkflowQueuingService), new PropertyMetadata(DependencyPropertyOptions.NonSerialized));
// Persisted state properties
internal static DependencyProperty RootPersistedQueueStatesProperty = DependencyProperty.RegisterAttached("RootPersistedQueueStates", typeof(Dictionary<IComparable, EventQueueState>), typeof(WorkflowQueuingService));
internal static DependencyProperty LocalPersistedQueueStatesProperty = DependencyProperty.RegisterAttached("LocalPersistedQueueStates", typeof(Dictionary<IComparable, EventQueueState>), typeof(WorkflowQueuingService));
private const string pendingNotification = "*PendingNotifications";
// Snapshots created during pre-persist and dumped during post-persist
// If persistence fails, changes made to queuing service during pre-persist must be undone
// in post-persist.
// Created for ref. 20575.
private Dictionary<IComparable, EventQueueState> persistedQueueStatesSnapshot = null;
private EventQueueState pendingQueueStateSnapshot = null;
// root Q service constructor
internal WorkflowQueuingService(IWorkflowCoreRuntime rootWorkflowExecutor)
{
this.rootWorkflowExecutor = rootWorkflowExecutor;
this.rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.PendingMessagesProperty, this.pendingQueueState.Messages);
this.persistedQueueStates = (Dictionary<IComparable, EventQueueState>)this.rootWorkflowExecutor.RootActivity.GetValue(WorkflowQueuingService.RootPersistedQueueStatesProperty);
if (this.persistedQueueStates == null)
{
this.persistedQueueStates = new Dictionary<IComparable, EventQueueState>();
this.rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.RootPersistedQueueStatesProperty, this.persistedQueueStates);
}
if (!this.Exists(pendingNotification))
this.CreateWorkflowQueue(pendingNotification, false);
}
// inner Q service constructor
internal WorkflowQueuingService(WorkflowQueuingService copyFromQueuingService)
{
this.rootQueuingService = copyFromQueuingService;
this.rootWorkflowExecutor = copyFromQueuingService.rootWorkflowExecutor;
this.rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.PendingMessagesProperty, this.pendingQueueState.Messages);
this.persistedQueueStates = new Dictionary<IComparable, EventQueueState>();
this.rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.LocalPersistedQueueStatesProperty, this.persistedQueueStates);
SubscribeForRootMessageDelivery();
}
public WorkflowQueue CreateWorkflowQueue(IComparable queueName, bool transactional)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
// if not transactional create one at the root
// so it is visible outside this transaction
if (this.rootQueuingService != null && !transactional)
{
return this.rootQueuingService.CreateWorkflowQueue(queueName, false);
}
NewQueue(queueName, true, transactional);
return new WorkflowQueue(this, queueName);
}
}
public void DeleteWorkflowQueue(IComparable queueName)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
// when we are deleting the queue from activity
// message delivery should not happen.
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
this.rootQueuingService.DeleteWorkflowQueue(queueName);
return;
}
EventQueueState queueState = GetEventQueueState(queueName);
Queue queue = queueState.Messages;
Queue pendingQueue = this.pendingQueueState.Messages;
while (queue.Count != 0)
{
pendingQueue.Enqueue(queue.Dequeue());
}
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Deleting Queue with ID {0} for {1}", queueName.GetHashCode(), queueName);
this.persistedQueueStates.Remove(queueName);
}
}
public bool Exists(IComparable queueName)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
return this.rootQueuingService.Exists(queueName);
}
return this.persistedQueueStates.ContainsKey(queueName);
}
}
public WorkflowQueue GetWorkflowQueue(IComparable queueName)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
return this.rootQueuingService.GetWorkflowQueue(queueName);
}
GetEventQueueState(queueName);
return new WorkflowQueue(this, queueName);
}
}
#region internal functions
internal Object SyncRoot
{
get { return syncRoot; }
}
internal void EnqueueEvent(IComparable queueName, Object item)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
this.rootQueuingService.EnqueueEvent(queueName, item);
return;
}
EventQueueState qState = GetQueue(queueName);
if (!qState.Enabled)
{
throw new QueueException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.QueueNotEnabled, queueName), MessageQueueErrorCode.QueueNotAvailable);
}
// note enqueue allowed irrespective of dirty flag since it is delivered through
qState.Messages.Enqueue(item);
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Enqueue item Queue ID {0} for {1}", queueName.GetHashCode(), queueName);
// notify message arrived subscribers
for (int i = 0; messageArrivalEventHandlers != null && i < messageArrivalEventHandlers.Count; ++i)
{
this.messageArrivalEventHandlers[i].OnItemEnqueued(queueName, item);
}
NotifyExternalSubscribers(queueName, qState, item);
}
}
internal bool SafeEnqueueEvent(IComparable queueName, Object item)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
return this.rootQueuingService.SafeEnqueueEvent(queueName, item);
}
EventQueueState qState = GetQueue(queueName);
if (!qState.Enabled)
{
throw new QueueException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.QueueNotEnabled, queueName), MessageQueueErrorCode.QueueNotAvailable);
}
// note enqueue allowed irrespective of dirty flag since it is delivered through
qState.Messages.Enqueue(item);
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Enqueue item Queue ID {0} for {1}", queueName.GetHashCode(), queueName);
// notify message arrived subscribers
for (int i = 0; messageArrivalEventHandlers != null && i < messageArrivalEventHandlers.Count; ++i)
{
this.messageArrivalEventHandlers[i].OnItemSafeEnqueued(queueName, item);
}
NotifySynchronousSubscribers(queueName, qState, item);
return QueueAsynchronousEvent(queueName, qState);
}
}
internal object Peek(IComparable queueName)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
return this.rootQueuingService.Peek(queueName);
}
EventQueueState queueState = GetEventQueueState(queueName);
if (queueState.Messages.Count != 0)
return queueState.Messages.Peek();
object[] args = new object[] { System.Messaging.MessageQueueErrorCode.MessageNotFound, queueName };
string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, args);
throw new QueueException(message, MessageQueueErrorCode.MessageNotFound);
}
}
internal Object DequeueEvent(IComparable queueName)
{
if (queueName == null)
throw new ArgumentNullException("queueName");
lock (SyncRoot)
{
if (this.rootQueuingService != null && !IsTransactionalQueue(queueName))
{
return this.rootQueuingService.DequeueEvent(queueName);
}
EventQueueState queueState = GetEventQueueState(queueName);
if (queueState.Messages.Count != 0)
return queueState.Messages.Dequeue();
object[] args = new object[] { System.Messaging.MessageQueueErrorCode.MessageNotFound, queueName };
string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, args);
throw new QueueException(message, MessageQueueErrorCode.MessageNotFound);
}
}
internal EventQueueState GetQueueState(IComparable eventType)
{
lock (SyncRoot)
{
return GetQueue(eventType);
}
}
Activity caller;
internal Activity CallingActivity
{
get
{
if (this.rootQueuingService != null)
return this.rootQueuingService.CallingActivity;
return this.caller;
}
set
{
if (this.rootQueuingService != null)
this.rootQueuingService.CallingActivity = value;
this.caller = value;
}
}
private bool QueueAsynchronousEvent(IComparable queueName, EventQueueState qState)
{
if (qState.AsynchronousListeners.Count != 0 || IsNestedListenersExist(queueName))
{
Queue q = GetQueue(pendingNotification).Messages;
q.Enqueue(new KeyValuePair<IComparable, EventQueueState>(queueName, qState));
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Queued delayed message notification for '{0}'", queueName.ToString());
return q.Count == 1;
}
return false;
}
bool IsNestedListenersExist(IComparable queueName)
{
for (int i = 0; messageArrivalEventHandlers != null && i < messageArrivalEventHandlers.Count; ++i)
{
WorkflowQueuingService qService = messageArrivalEventHandlers[i];
EventQueueState queueState = null;
if (qService.persistedQueueStates.TryGetValue(queueName, out queueState) &&
queueState.AsynchronousListeners.Count != 0)
return true;
}
return false;
}
internal void ProcessesQueuedAsynchronousEvents()
{
Queue q = GetQueue(pendingNotification).Messages;
while (q.Count > 0)
{
KeyValuePair<IComparable, EventQueueState> pair = (KeyValuePair<IComparable, EventQueueState>)q.Dequeue();
// notify message arrived subscribers
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Processing delayed message notification '{0}'", pair.Key.ToString());
for (int i = 0; messageArrivalEventHandlers != null && i < messageArrivalEventHandlers.Count; ++i)
{
WorkflowQueuingService service = this.messageArrivalEventHandlers[i];
if (service.persistedQueueStates.ContainsKey(pair.Key))
{
EventQueueState qState = service.GetQueue(pair.Key);
if (qState.Enabled)
{
service.NotifyAsynchronousSubscribers(pair.Key, qState, 1);
}
}
}
NotifyAsynchronousSubscribers(pair.Key, pair.Value, 1);
}
}
internal void NotifyAsynchronousSubscribers(IComparable queueName, EventQueueState qState, int numberOfNotification)
{
for (int i = 0; i < numberOfNotification; ++i)
{
QueueEventArgs args = new QueueEventArgs(queueName);
lock (SyncRoot)
{
foreach (ActivityExecutorDelegateInfo<QueueEventArgs> subscriber in qState.AsynchronousListeners)
{
Activity contextActivity = rootWorkflowExecutor.GetContextActivityForId(subscriber.ContextId);
Debug.Assert(contextActivity != null);
subscriber.InvokeDelegate(contextActivity, args, false);
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Notifying async subscriber on queue:'{0}' activity:{1}", queueName.ToString(), subscriber.ActivityQualifiedName);
}
}
}
}
/// <summary>
/// At termination/completion point, need to move messages from all queues to the pending queue
/// </summary>
internal void MoveAllMessagesToPendingQueue()
{
lock (SyncRoot)
{
Queue pendingQueue = this.pendingQueueState.Messages;
foreach (EventQueueState queueState in this.persistedQueueStates.Values)
{
Queue queue = queueState.Messages;
while (queue.Count != 0)
{
pendingQueue.Enqueue(queue.Dequeue());
}
}
}
}
#endregion
#region private root q service helpers
private EventQueueState GetEventQueueState(IComparable queueName)
{
EventQueueState queueState = GetQueue(queueName);
if (queueState.Dirty)
{
string message =
string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.QueueBusyException, new object[] { queueName });
throw new QueueException(message, MessageQueueErrorCode.QueueNotAvailable);
}
return queueState;
}
private void NewQueue(IComparable queueID, bool enabled, bool transactional)
{
WorkflowTrace.Runtime.TraceInformation("Queuing Service: Creating new Queue with ID {0} for {1}", queueID.GetHashCode(), queueID);
if (this.persistedQueueStates.ContainsKey(queueID))
{
object[] args =
new object[] { System.Messaging.MessageQueueErrorCode.QueueExists, queueID };
string message =
string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, args);
throw new QueueException(message, MessageQueueErrorCode.QueueExists);
}
EventQueueState queueState = new EventQueueState();
queueState.Enabled = enabled;
queueState.queueName = queueID;
queueState.Transactional = transactional;
this.persistedQueueStates.Add(queueID, queueState);
}
internal EventQueueState GetQueue(IComparable queueID)
{
EventQueueState queue;
if (this.persistedQueueStates.TryGetValue(queueID, out queue))
{
queue.queueName = queueID;
return queue;
}
object[] args =
new object[] { System.Messaging.MessageQueueErrorCode.QueueNotFound, queueID };
string message =
string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, args);
throw new QueueException(message, MessageQueueErrorCode.QueueNotFound);
}
internal IEnumerable<IComparable> QueueNames
{
get
{
List<IComparable> list = new List<IComparable>(this.persistedQueueStates.Keys);
foreach (IComparable name in list)
{
if (name is String && (String)name == pendingNotification)
{
list.Remove(name);
break;
}
}
return list;
}
}
private void ApplyChangesFrom(EventQueueState srcPendingQueueState, Dictionary<IComparable, EventQueueState> srcPersistedQueueStates)
{
lock (SyncRoot)
{
Dictionary<IComparable, EventQueueState> modifiedItems = new Dictionary<IComparable, EventQueueState>();
foreach (KeyValuePair<IComparable, EventQueueState> mergeItem in srcPersistedQueueStates)
{
Debug.Assert(mergeItem.Value.Transactional, "Queue inside a transactional context is not transactional!");
if (mergeItem.Value.Transactional)
{
if (this.persistedQueueStates.ContainsKey(mergeItem.Key))
{
EventQueueState oldvalue = this.persistedQueueStates[mergeItem.Key];
if (!oldvalue.Dirty)
{
// we could get here when there
// are conflicting create Qs
string message =
string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.QueueBusyException, new object[] { mergeItem.Key });
throw new QueueException(message, MessageQueueErrorCode.QueueNotAvailable);
}
}
modifiedItems.Add(mergeItem.Key, mergeItem.Value);
}
}
// no conflicts detected now make the updates visible
foreach (KeyValuePair<IComparable, EventQueueState> modifiedItem in modifiedItems)
{
// shared queue in the root, swap out to new value
// or add new item
this.persistedQueueStates[modifiedItem.Key] = modifiedItem.Value;
}
this.pendingQueueState.CopyFrom(srcPendingQueueState);
}
}
// message arrival async notification
private void NotifyExternalSubscribers(IComparable queueName, EventQueueState qState, Object eventInstance)
{
NotifySynchronousSubscribers(queueName, qState, eventInstance);
NotifyAsynchronousSubscribers(queueName, qState, 1);
}
private void NotifySynchronousSubscribers(IComparable queueName, EventQueueState qState, Object eventInstance)
{
QueueEventArgs args = new QueueEventArgs(queueName);
for (int i = 0; i < qState.SynchronousListeners.Count; ++i)
{
if (qState.SynchronousListeners[i].HandlerDelegate != null)
qState.SynchronousListeners[i].HandlerDelegate(new WorkflowQueue(this, queueName), args);
else
qState.SynchronousListeners[i].EventListener.OnEvent(new WorkflowQueue(this, queueName), args);
}
}
// returns a valid state only if transactional and entry exists
private EventQueueState MarkQueueDirtyIfTransactional(IComparable queueName)
{
lock (SyncRoot)
{
Debug.Assert(this.rootQueuingService == null, "MarkQueueDirty should be done at root");
if (!this.persistedQueueStates.ContainsKey(queueName))
return null;
EventQueueState queueState = GetQueue(queueName);
if (!queueState.Transactional)
return null;
if (queueState.Dirty)
return queueState; // already marked
queueState.Dirty = true;
if (this.dirtyQueues == null)
this.dirtyQueues = new List<IComparable>();
// add to the list of dirty queues
this.dirtyQueues.Add(queueName);
return queueState;
}
}
private void AddMessageArrivedEventHandler(WorkflowQueuingService handler)
{
lock (SyncRoot)
{
if (this.messageArrivalEventHandlers == null)
this.messageArrivalEventHandlers = new List<WorkflowQueuingService>();
this.messageArrivalEventHandlers.Add(handler);
}
}
private void RemoveMessageArrivedEventHandler(WorkflowQueuingService handler)
{
lock (SyncRoot)
{
if (this.messageArrivalEventHandlers != null)
this.messageArrivalEventHandlers.Remove(handler);
if (this.dirtyQueues != null)
{
foreach (IComparable queueName in this.dirtyQueues)
{
EventQueueState qState = GetQueue(queueName);
qState.Dirty = false;
}
}
}
}
#endregion
#region inner QueuingService functions
private bool IsTransactionalQueue(IComparable queueName)
{
// check inner service for existense
if (!this.persistedQueueStates.ContainsKey(queueName))
{
EventQueueState queueState = this.rootQueuingService.MarkQueueDirtyIfTransactional(queueName);
if (queueState != null)
{
// if transactional proceed to the inner queue service
// for this operation after adding the state
EventQueueState snapshotState = new EventQueueState();
snapshotState.CopyFrom(queueState);
this.persistedQueueStates.Add(queueName, snapshotState);
return true;
}
return false;
}
return true; // if entry exits, it must be transactional
}
private void SubscribeForRootMessageDelivery()
{
if (this.rootQueuingService == null)
return;
this.rootQueuingService.AddMessageArrivedEventHandler(this);
}
private void UnSubscribeFromRootMessageDelivery()
{
if (this.rootQueuingService == null)
return;
this.rootQueuingService.RemoveMessageArrivedEventHandler(this);
}
// listen on its internal(parent) queuing service
// messages and pull messages. There is one parent queuing service visible to the external
// host environment. A queueing service snapshot exists per atomic scope and external messages
// for existing queues need to be pushed through
private void OnItemEnqueued(IComparable queueName, object item)
{
if (this.persistedQueueStates.ContainsKey(queueName))
{
// make the message visible to inner queueing service
EventQueueState qState = GetQueue(queueName);
if (!qState.Enabled)
{
object[] msgArgs = new object[] { System.Messaging.MessageQueueErrorCode.QueueNotFound, queueName };
string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, msgArgs);
throw new QueueException(message, MessageQueueErrorCode.QueueNotAvailable);
}
qState.Messages.Enqueue(item);
NotifyExternalSubscribers(queueName, qState, item);
}
}
private void OnItemSafeEnqueued(IComparable queueName, object item)
{
if (this.persistedQueueStates.ContainsKey(queueName))
{
// make the message visible to inner queueing service
EventQueueState qState = GetQueue(queueName);
if (!qState.Enabled)
{
object[] msgArgs = new object[] { System.Messaging.MessageQueueErrorCode.QueueNotFound, queueName };
string message = string.Format(CultureInfo.CurrentCulture, ExecutionStringManager.EventQueueException, msgArgs);
throw new QueueException(message, MessageQueueErrorCode.QueueNotAvailable);
}
qState.Messages.Enqueue(item);
NotifySynchronousSubscribers(queueName, qState, item);
}
}
internal void Complete(bool commitSucceeded)
{
if (commitSucceeded)
{
this.rootQueuingService.ApplyChangesFrom(this.pendingQueueState, this.persistedQueueStates);
}
UnSubscribeFromRootMessageDelivery();
}
#endregion
#region Pre-persist and Post-persist helpers for queuing service states
// Created for ref. 20575
internal void PostPersist(bool isPersistSuccessful)
{
// If persist is unsuccessful, we'll undo the changes done
// because of the call to .Complete() in PrePresist
if (!isPersistSuccessful)
{
Debug.Assert(rootWorkflowExecutor.CurrentAtomicActivity != null);
Debug.Assert(pendingQueueStateSnapshot != null);
Debug.Assert(persistedQueueStatesSnapshot != null);
TransactionalProperties transactionalProperties = rootWorkflowExecutor.CurrentAtomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty) as TransactionalProperties;
Debug.Assert(transactionalProperties != null);
// Restore queuing states and set root activity's dependency properties to the new values.
pendingQueueState = pendingQueueStateSnapshot;
persistedQueueStates = persistedQueueStatesSnapshot;
rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.RootPersistedQueueStatesProperty, persistedQueueStatesSnapshot);
rootWorkflowExecutor.RootActivity.SetValue(WorkflowQueuingService.PendingMessagesProperty, pendingQueueStateSnapshot.Messages);
// Also call Subscribe...() because the .Complete() call called Unsubscribe
transactionalProperties.LocalQueuingService.SubscribeForRootMessageDelivery();
}
// The backups are no longer necessary.
// The next call to PrePresistQueuingServiceState() will do a re-backup.
persistedQueueStatesSnapshot = null;
pendingQueueStateSnapshot = null;
}
// Created for ref. 20575
internal void PrePersist()
{
if (rootWorkflowExecutor.CurrentAtomicActivity != null)
{
// Create transactionalProperties from currentAtomicActivity
TransactionalProperties transactionalProperties = this.rootWorkflowExecutor.CurrentAtomicActivity.GetValue(WorkflowExecutor.TransactionalPropertiesProperty) as TransactionalProperties;
// Create backup snapshot of root queuing service's persistedQueuesStates
// qService.persistedQueueStates is changed when LocalQueuingService.Complete is called later.
persistedQueueStatesSnapshot = new Dictionary<IComparable, EventQueueState>();
foreach (KeyValuePair<IComparable, EventQueueState> kv in persistedQueueStates)
{
EventQueueState individualPersistedQueueStateValue = new EventQueueState();
individualPersistedQueueStateValue.CopyFrom(kv.Value);
persistedQueueStatesSnapshot.Add(kv.Key, individualPersistedQueueStateValue);
}
// Create backup snapshot of root queuing service's pendingQueueState
// qService.pendingQueueState is changed when LocalQueuingService.Complete is called later.
pendingQueueStateSnapshot = new EventQueueState();
pendingQueueStateSnapshot.CopyFrom(pendingQueueState);
// Reconcile differences between root and local queuing services.
transactionalProperties.LocalQueuingService.Complete(true);
}
}
#endregion Pre-persist and post-persist helpers for queuing service states
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operations for managing User Groups.
/// </summary>
internal partial class UserGroupsOperations : IServiceOperations<ApiManagementClient>, IUserGroupsOperations
{
/// <summary>
/// Initializes a new instance of the UserGroupsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal UserGroupsOperations(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Adds existing user to existing group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> AddToGroupAsync(string resourceGroupName, string serviceName, string uid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "AddToGroupAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all user groups.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListAsync(string resourceGroupName, string serviceName, string uid, QueryParameters query, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("query", query);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
url = url + "/groups";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
List<string> odataFilter = new List<string>();
if (query != null && query.Filter != null)
{
odataFilter.Add(Uri.EscapeDataString(query.Filter));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (query != null && query.Top != null)
{
queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString()));
}
if (query != null && query.Skip != null)
{
queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString()));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// List all user groups.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public async Task<GroupListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
GroupListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new GroupListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
GroupPaged resultInstance = new GroupPaged();
result.Result = resultInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
GroupContract groupContractInstance = new GroupContract();
resultInstance.Values.Add(groupContractInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
groupContractInstance.IdPath = idInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
groupContractInstance.Name = nameInstance;
}
JToken descriptionValue = valueValue["description"];
if (descriptionValue != null && descriptionValue.Type != JTokenType.Null)
{
string descriptionInstance = ((string)descriptionValue);
groupContractInstance.Description = descriptionInstance;
}
JToken builtInValue = valueValue["builtIn"];
if (builtInValue != null && builtInValue.Type != JTokenType.Null)
{
bool builtInInstance = ((bool)builtInValue);
groupContractInstance.System = builtInInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
GroupTypeContract typeInstance = ((GroupTypeContract)Enum.Parse(typeof(GroupTypeContract), ((string)typeValue), true));
groupContractInstance.Type = typeInstance;
}
JToken externalIdValue = valueValue["externalId"];
if (externalIdValue != null && externalIdValue.Type != JTokenType.Null)
{
string externalIdInstance = ((string)externalIdValue);
groupContractInstance.ExternalId = externalIdInstance;
}
}
}
JToken countValue = responseDoc["count"];
if (countValue != null && countValue.Type != JTokenType.Null)
{
long countInstance = ((long)countValue);
resultInstance.TotalCount = countInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
resultInstance.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Remove existing user from existing group.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='uid'>
/// Required. Identifier of the user.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RemoveFromGroupAsync(string resourceGroupName, string serviceName, string uid, string gid, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
if (uid == null)
{
throw new ArgumentNullException("uid");
}
if (gid == null)
{
throw new ArgumentNullException("gid");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
tracingParameters.Add("uid", uid);
tracingParameters.Add("gid", gid);
TracingAdapter.Enter(invocationId, this, "RemoveFromGroupAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/groups/";
url = url + Uri.EscapeDataString(gid);
url = url + "/users/";
url = url + Uri.EscapeDataString(uid);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2016-07-07");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/* ====================================================================
Licensed to the 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 NPOI.HSSF.Record
{
using System;
using NPOI.HSSF.Model;
using NPOI.HSSF.Record.CF;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using NPOI.Util;
/**
* Conditional Formatting Rules. This can hold old-style rules
*
*
* <p>This is for the older-style Excel conditional formattings,
* new-style (Excel 2007+) also make use of {@link CFRule12Record}
* and {@link CFExRuleRecord} for their rules.
*/
public abstract class CFRuleBase : StandardRecord, ICloneable
{
public static class ComparisonOperator {
public static byte NO_COMPARISON = 0;
public static byte BETWEEN = 1;
public static byte NOT_BETWEEN = 2;
public static byte EQUAL = 3;
public static byte NOT_EQUAL = 4;
public static byte GT = 5;
public static byte LT = 6;
public static byte GE = 7;
public static byte LE = 8;
public static byte max_operator = 8;
}
private byte condition_type;
// The only kinds that CFRuleRecord handles
public const byte CONDITION_TYPE_CELL_VALUE_IS = 1;
public const byte CONDITION_TYPE_FORMULA = 2;
// These are CFRule12Rule only
public const byte CONDITION_TYPE_COLOR_SCALE = 3;
public const byte CONDITION_TYPE_DATA_BAR = 4;
public const byte CONDITION_TYPE_FILTER = 5;
public const byte CONDITION_TYPE_ICON_SET = 6;
private byte comparison_operator;
public static int TEMPLATE_CELL_VALUE = 0x0000;
public static int TEMPLATE_FORMULA = 0x0001;
public static int TEMPLATE_COLOR_SCALE_FORMATTING = 0x0002;
public static int TEMPLATE_DATA_BAR_FORMATTING = 0x0003;
public static int TEMPLATE_ICON_SET_FORMATTING = 0x0004;
public static int TEMPLATE_FILTER = 0x0005;
public static int TEMPLATE_UNIQUE_VALUES = 0x0007;
public static int TEMPLATE_CONTAINS_TEXT = 0x0008;
public static int TEMPLATE_CONTAINS_BLANKS = 0x0009;
public static int TEMPLATE_CONTAINS_NO_BLANKS = 0x000A;
public static int TEMPLATE_CONTAINS_ERRORS = 0x000B;
public static int TEMPLATE_CONTAINS_NO_ERRORS = 0x000C;
public static int TEMPLATE_TODAY = 0x000F;
public static int TEMPLATE_TOMORROW = 0x0010;
public static int TEMPLATE_YESTERDAY = 0x0011;
public static int TEMPLATE_LAST_7_DAYS = 0x0012;
public static int TEMPLATE_LAST_MONTH = 0x0013;
public static int TEMPLATE_NEXT_MONTH = 0x0014;
public static int TEMPLATE_THIS_WEEK = 0x0015;
public static int TEMPLATE_NEXT_WEEK = 0x0016;
public static int TEMPLATE_LAST_WEEK = 0x0017;
public static int TEMPLATE_THIS_MONTH = 0x0018;
public static int TEMPLATE_ABOVE_AVERAGE = 0x0019;
public static int TEMPLATE_BELOW_AVERAGE = 0x001A;
public static int TEMPLATE_DUPLICATE_VALUES = 0x001B;
public static int TEMPLATE_ABOVE_OR_EQUAL_TO_AVERAGE = 0x001D;
public static int TEMPLATE_BELOW_OR_EQUAL_TO_AVERAGE = 0x001E;
internal static BitField modificationBits = bf(0x003FFFFF); // Bits: font,align,bord,patt,prot
internal static BitField alignHor = bf(0x00000001); // 0 = Horizontal alignment modified
internal static BitField alignVer = bf(0x00000002); // 0 = Vertical alignment modified
internal static BitField alignWrap = bf(0x00000004); // 0 = Text wrapped flag modified
internal static BitField alignRot = bf(0x00000008); // 0 = Text rotation modified
internal static BitField alignJustLast = bf(0x00000010); // 0 = Justify last line flag modified
internal static BitField alignIndent = bf(0x00000020); // 0 = Indentation modified
internal static BitField alignShrin = bf(0x00000040); // 0 = Shrink to fit flag modified
internal static BitField mergeCell = bf(0x00000080); // Normally 1, 0 = Merge Cell flag modified
internal static BitField protLocked = bf(0x00000100); // 0 = Cell locked flag modified
internal static BitField protHidden = bf(0x00000200); // 0 = Cell hidden flag modified
internal static BitField bordLeft = bf(0x00000400); // 0 = Left border style and colour modified
internal static BitField bordRight = bf(0x00000800); // 0 = Right border style and colour modified
internal static BitField bordTop = bf(0x00001000); // 0 = Top border style and colour modified
internal static BitField bordBot = bf(0x00002000); // 0 = Bottom border style and colour modified
internal static BitField bordTlBr = bf(0x00004000); // 0 = Top-left to bottom-right border flag modified
internal static BitField bordBlTr = bf(0x00008000); // 0 = Bottom-left to top-right border flag modified
internal static BitField pattStyle = bf(0x00010000); // 0 = Pattern style modified
internal static BitField pattCol = bf(0x00020000); // 0 = Pattern colour modified
internal static BitField pattBgCol = bf(0x00040000); // 0 = Pattern background colour modified
internal static BitField notUsed2 = bf(0x00380000); // Always 111 (ifmt / ifnt / 1)
internal static BitField undocumented = bf(0x03C00000); // Undocumented bits
internal static BitField fmtBlockBits = bf(0x7C000000); // Bits: font,align,bord,patt,prot
internal static BitField font = bf(0x04000000); // 1 = Record Contains font formatting block
internal static BitField align = bf(0x08000000); // 1 = Record Contains alignment formatting block
internal static BitField bord = bf(0x10000000); // 1 = Record Contains border formatting block
internal static BitField patt = bf(0x20000000); // 1 = Record Contains pattern formatting block
internal static BitField prot = bf(0x40000000); // 1 = Record Contains protection formatting block
internal static BitField alignTextDir = bf(0x80000000); // 0 = Text direction modified
private static BitField bf(long i) {
return BitFieldFactory.GetInstance((int)i);
}
protected int formatting_options;
protected short formatting_not_used; // TODO Decode this properly
protected FontFormatting _fontFormatting;
protected BorderFormatting _borderFormatting;
protected PatternFormatting _patternFormatting;
private Formula formula1;
private Formula formula2;
/** Creates new CFRuleRecord */
protected CFRuleBase(byte conditionType, byte comparisonOperation) {
ConditionType = (conditionType);
ComparisonOperation = (comparisonOperation);
formula1 = Formula.Create(Ptg.EMPTY_PTG_ARRAY);
formula2 = Formula.Create(Ptg.EMPTY_PTG_ARRAY);
}
protected CFRuleBase(byte conditionType, byte comparisonOperation, Ptg[] formula1, Ptg[] formula2)
: this(conditionType, comparisonOperation)
{
this.formula1 = Formula.Create(formula1);
this.formula2 = Formula.Create(formula2);
}
protected CFRuleBase() { }
protected int ReadFormatOptions(RecordInputStream in1) {
formatting_options = in1.ReadInt();
formatting_not_used = in1.ReadShort();
int len = 6;
if (ContainsFontFormattingBlock) {
_fontFormatting = new FontFormatting(in1);
len += _fontFormatting.DataLength;
}
if (ContainsBorderFormattingBlock) {
_borderFormatting = new BorderFormatting(in1);
len += _borderFormatting.DataLength;
}
if (ContainsPatternFormattingBlock) {
_patternFormatting = new PatternFormatting(in1);
len += _patternFormatting.DataLength;
}
return len;
}
public byte ConditionType
{
get { return condition_type; }
set
{
if ((this is CFRuleRecord))
{
if (value == CONDITION_TYPE_CELL_VALUE_IS ||
value == CONDITION_TYPE_FORMULA)
{
// Good, valid combination
}
else
{
throw new ArgumentException("CFRuleRecord only accepts Value-Is and Formula types");
}
}
this.condition_type = value;
}
}
public byte ComparisonOperation
{
get { return comparison_operator; }
set
{
if (value < 0 || value > ComparisonOperator.max_operator)
throw new ArgumentException(
"Valid operators are only in the range 0 to " + ComparisonOperator.max_operator);
this.comparison_operator = value;
}
}
public bool ContainsFontFormattingBlock
{
get { return GetOptionFlag(font); }
}
public FontFormatting FontFormatting
{
get
{
if (ContainsFontFormattingBlock)
{
return _fontFormatting;
}
return null;
}
set
{
_fontFormatting = value;
SetOptionFlag(value != null, font);
}
}
public bool ContainsAlignFormattingBlock() {
return GetOptionFlag(align);
}
public void SetAlignFormattingUnChanged() {
SetOptionFlag(false, align);
}
public bool ContainsBorderFormattingBlock
{
get { return GetOptionFlag(bord); }
}
public BorderFormatting BorderFormatting {
get
{
if (ContainsBorderFormattingBlock)
{
return _borderFormatting;
}
return null;
}
set
{
_borderFormatting = value;
SetOptionFlag(value != null, bord);
}
}
public bool ContainsPatternFormattingBlock
{
get { return GetOptionFlag(patt); }
}
public PatternFormatting PatternFormatting
{
get
{
if (ContainsPatternFormattingBlock)
{
return _patternFormatting;
}
return null;
}
set
{
_patternFormatting = value;
SetOptionFlag(value != null, patt);
}
}
public bool ContainsProtectionFormattingBlock() {
return GetOptionFlag(prot);
}
public void SetProtectionFormattingUnChanged() {
SetOptionFlag(false, prot);
}
/**
* Get the option flags
*
* @return bit mask
*/
public int Options
{
get
{
return formatting_options;
}
}
private bool IsModified(BitField field) {
return !field.IsSet(formatting_options);
}
private void SetModified(bool modified, BitField field) {
formatting_options = field.SetBoolean(formatting_options, !modified);
}
public bool IsLeftBorderModified
{
get
{
return IsModified(bordLeft);
}
set
{
SetModified(value, bordLeft);
}
}
public bool IsRightBorderModified {
get
{
return IsModified(bordRight);
}
set
{
SetModified(value, bordRight);
}
}
public bool IsTopBorderModified
{
get
{
return IsModified(bordTop);
}
set
{
SetModified(value, bordTop);
}
}
public bool IsBottomBorderModified
{
get
{
return IsModified(bordBot);
}
set
{
SetModified(value, bordBot);
}
}
public bool IsTopLeftBottomRightBorderModified
{
get
{
return IsModified(bordTlBr);
}
set
{
SetModified(value, bordTlBr);
}
}
public bool IsBottomLeftTopRightBorderModified
{
get
{
return IsModified(bordBlTr);
}
set
{
SetModified(value, bordBlTr);
}
}
public bool IsPatternStyleModified
{
get
{
return IsModified(pattStyle);
}
set
{
SetModified(value, pattStyle);
}
}
public bool IsPatternColorModified
{
get
{
return IsModified(pattCol);
}
set
{
SetModified(value, pattCol);
}
}
public bool IsPatternBackgroundColorModified
{
get
{
return IsModified(pattBgCol);
}
set
{
SetModified(value, pattBgCol);
}
}
private bool GetOptionFlag(BitField field) {
return field.IsSet(formatting_options);
}
private void SetOptionFlag(bool flag, BitField field) {
formatting_options = field.SetBoolean(formatting_options, flag);
}
protected int FormattingBlockSize
{
get
{
return 6 +
(ContainsFontFormattingBlock ? _fontFormatting.RawRecord.Length : 0) +
(ContainsBorderFormattingBlock ? 8 : 0) +
(ContainsPatternFormattingBlock ? 4 : 0);
}
}
protected void SerializeFormattingBlock(ILittleEndianOutput out1) {
out1.WriteInt(formatting_options);
out1.WriteShort(formatting_not_used);
if (ContainsFontFormattingBlock) {
byte[] fontFormattingRawRecord = _fontFormatting.RawRecord;
out1.Write(fontFormattingRawRecord);
}
if (ContainsBorderFormattingBlock) {
_borderFormatting.Serialize(out1);
}
if (ContainsPatternFormattingBlock) {
_patternFormatting.Serialize(out1);
}
}
/**
* Get the stack of the 1st expression as a list
*
* @return list of tokens (casts stack to a list and returns it!)
* this method can return null is we are unable to create Ptgs from
* existing excel file
* callers should check for null!
*/
public Ptg[] ParsedExpression1
{
get
{
return formula1.Tokens;
}
set
{
formula1 = Formula.Create(value);
}
}
protected Formula Formula1
{
get
{
return formula1;
}
set
{
this.formula1 = value;
}
}
/**
* Get the stack of the 2nd expression as a list
*
* @return array of {@link Ptg}s, possibly <code>null</code>
*/
public Ptg[] ParsedExpression2
{
get
{
return formula2.Tokens;
}
set
{
formula2 = Formula.Create(value);
}
}
protected Formula Formula2
{
get
{
return formula2;
}
set
{
this.formula2 = value;
}
}
/**
* @param formula must not be <code>null</code>
* @return encoded size of the formula tokens (does not include 2 bytes for ushort length)
*/
protected static int GetFormulaSize(Formula formula) {
return formula.EncodedTokenSize;
}
/**
* TODO - parse conditional format formulas properly i.e. produce tRefN and tAreaN instead of tRef and tArea
* this call will produce the wrong results if the formula Contains any cell references
* One approach might be to apply the inverse of SharedFormulaRecord.ConvertSharedFormulas(Stack, int, int)
* Note - two extra parameters (rowIx & colIx) will be required. They probably come from one of the Region objects.
*
* @return <code>null</code> if <tt>formula</tt> was null.
*/
public static Ptg[] ParseFormula(String formula, HSSFSheet sheet) {
if (formula == null) {
return null;
}
int sheetIndex = sheet.Workbook.GetSheetIndex(sheet);
return HSSFFormulaParser.Parse(formula, sheet.Workbook as HSSFWorkbook, FormulaType.Cell, sheetIndex);
}
protected void CopyTo(CFRuleBase rec) {
rec.condition_type = condition_type;
rec.comparison_operator = comparison_operator;
rec.formatting_options = formatting_options;
rec.formatting_not_used = formatting_not_used;
if (ContainsFontFormattingBlock) {
rec._fontFormatting = (FontFormatting)_fontFormatting.Clone();
}
if (ContainsBorderFormattingBlock) {
rec._borderFormatting = (BorderFormatting)_borderFormatting.Clone();
}
if (ContainsPatternFormattingBlock) {
rec._patternFormatting = (PatternFormatting)_patternFormatting.Clone();
}
rec.formula1 = (formula1.Copy());
rec.formula2 = (formula2.Copy());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Globbing;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using NuGet.Packaging.Core;
using OmniSharp.Utilities;
using MSB = Microsoft.Build;
namespace OmniSharp.MSBuild.ProjectFile
{
internal partial class ProjectFileInfo
{
private class ProjectData
{
public Guid Guid { get; }
public string Name { get; }
public string AssemblyName { get; }
public string TargetPath { get; }
public string OutputPath { get; }
public string IntermediateOutputPath { get; }
public string ProjectAssetsFile { get; }
public string Configuration { get; }
public string Platform { get; }
public string PlatformTarget { get; }
public FrameworkName TargetFramework { get; }
public ImmutableArray<string> TargetFrameworks { get; }
public OutputKind OutputKind { get; }
public LanguageVersion LanguageVersion { get; }
public NullableContextOptions NullableContextOptions { get; }
public bool AllowUnsafeCode { get; }
public bool CheckForOverflowUnderflow { get; }
public string DocumentationFile { get; }
public ImmutableArray<string> PreprocessorSymbolNames { get; }
public ImmutableArray<string> SuppressedDiagnosticIds { get; }
public bool SignAssembly { get; }
public string AssemblyOriginatorKeyFile { get; }
public ImmutableArray<IMSBuildGlob> FileInclusionGlobs { get; }
public ImmutableArray<string> SourceFiles { get; }
public ImmutableArray<string> ProjectReferences { get; }
public ImmutableArray<string> References { get; }
public ImmutableArray<PackageReference> PackageReferences { get; }
public ImmutableArray<string> Analyzers { get; }
public ImmutableArray<string> AdditionalFiles { get; }
public ImmutableArray<string> AnalyzerConfigFiles { get; }
public ImmutableArray<string> WarningsAsErrors { get; }
public ImmutableArray<string> WarningsNotAsErrors { get; }
public RuleSet RuleSet { get; }
public ImmutableDictionary<string, string> ReferenceAliases { get; }
public ImmutableDictionary<string, string> ProjectReferenceAliases { get; }
public bool TreatWarningsAsErrors { get; }
public bool RunAnalyzers { get; }
public bool RunAnalyzersDuringLiveAnalysis { get; }
public string DefaultNamespace { get; }
private ProjectData()
{
// Be sure to initialize all collection properties with ImmutableArray<T>.Empty.
// Otherwise, Json.net won't be able to serialize the values.
TargetFrameworks = ImmutableArray<string>.Empty;
PreprocessorSymbolNames = ImmutableArray<string>.Empty;
SuppressedDiagnosticIds = ImmutableArray<string>.Empty;
SourceFiles = ImmutableArray<string>.Empty;
ProjectReferences = ImmutableArray<string>.Empty;
References = ImmutableArray<string>.Empty;
PackageReferences = ImmutableArray<PackageReference>.Empty;
Analyzers = ImmutableArray<string>.Empty;
AdditionalFiles = ImmutableArray<string>.Empty;
AnalyzerConfigFiles = ImmutableArray<string>.Empty;
ReferenceAliases = ImmutableDictionary<string, string>.Empty;
ProjectReferenceAliases = ImmutableDictionary<string, string>.Empty;
WarningsAsErrors = ImmutableArray<string>.Empty;
FileInclusionGlobs = ImmutableArray<IMSBuildGlob>.Empty;
WarningsNotAsErrors = ImmutableArray<string>.Empty;
}
private ProjectData(
Guid guid, string name,
string assemblyName, string targetPath, string outputPath, string intermediateOutputPath,
string projectAssetsFile,
string configuration, string platform, string platformTarget,
FrameworkName targetFramework,
ImmutableArray<string> targetFrameworks,
OutputKind outputKind,
LanguageVersion languageVersion,
NullableContextOptions nullableContextOptions,
bool allowUnsafeCode,
bool checkForOverflowUnderflow,
string documentationFile,
ImmutableArray<string> preprocessorSymbolNames,
ImmutableArray<string> suppressedDiagnosticIds,
ImmutableArray<string> warningsAsErrors,
ImmutableArray<string> warningsNotAsErrors,
bool signAssembly,
string assemblyOriginatorKeyFile,
bool treatWarningsAsErrors,
string defaultNamespace,
bool runAnalyzers,
bool runAnalyzersDuringLiveAnalysis,
RuleSet ruleset)
: this()
{
Guid = guid;
Name = name;
AssemblyName = assemblyName;
TargetPath = targetPath;
OutputPath = outputPath;
IntermediateOutputPath = intermediateOutputPath;
ProjectAssetsFile = projectAssetsFile;
Configuration = configuration;
Platform = platform;
PlatformTarget = platformTarget;
TargetFramework = targetFramework;
TargetFrameworks = targetFrameworks.EmptyIfDefault();
OutputKind = outputKind;
LanguageVersion = languageVersion;
NullableContextOptions = nullableContextOptions;
AllowUnsafeCode = allowUnsafeCode;
CheckForOverflowUnderflow = checkForOverflowUnderflow;
DocumentationFile = documentationFile;
PreprocessorSymbolNames = preprocessorSymbolNames.EmptyIfDefault();
SuppressedDiagnosticIds = suppressedDiagnosticIds.EmptyIfDefault();
WarningsAsErrors = warningsAsErrors.EmptyIfDefault();
WarningsNotAsErrors = warningsNotAsErrors.EmptyIfDefault();
SignAssembly = signAssembly;
AssemblyOriginatorKeyFile = assemblyOriginatorKeyFile;
TreatWarningsAsErrors = treatWarningsAsErrors;
RuleSet = ruleset;
DefaultNamespace = defaultNamespace;
RunAnalyzers = runAnalyzers;
RunAnalyzersDuringLiveAnalysis = runAnalyzersDuringLiveAnalysis;
}
private ProjectData(
Guid guid, string name,
string assemblyName, string targetPath, string outputPath, string intermediateOutputPath,
string projectAssetsFile,
string configuration, string platform, string platformTarget,
FrameworkName targetFramework,
ImmutableArray<string> targetFrameworks,
OutputKind outputKind,
LanguageVersion languageVersion,
NullableContextOptions nullableContextOptions,
bool allowUnsafeCode,
bool checkForOverflowUnderflow,
string documentationFile,
ImmutableArray<string> preprocessorSymbolNames,
ImmutableArray<string> suppressedDiagnosticIds,
ImmutableArray<string> warningsAsErrors,
ImmutableArray<string> warningsNotAsErrors,
bool signAssembly,
string assemblyOriginatorKeyFile,
ImmutableArray<string> sourceFiles,
ImmutableArray<string> projectReferences,
ImmutableArray<string> references,
ImmutableArray<PackageReference> packageReferences,
ImmutableArray<string> analyzers,
ImmutableArray<string> additionalFiles,
ImmutableArray<string> analyzerConfigFiles,
bool treatWarningsAsErrors,
string defaultNamespace,
bool runAnalyzers,
bool runAnalyzersDuringLiveAnalysis,
RuleSet ruleset,
ImmutableDictionary<string, string> referenceAliases,
ImmutableDictionary<string, string> projectReferenceAliases,
ImmutableArray<IMSBuildGlob> fileInclusionGlobs)
: this(guid, name, assemblyName, targetPath, outputPath, intermediateOutputPath, projectAssetsFile,
configuration, platform, platformTarget, targetFramework, targetFrameworks, outputKind, languageVersion, nullableContextOptions, allowUnsafeCode, checkForOverflowUnderflow,
documentationFile, preprocessorSymbolNames, suppressedDiagnosticIds, warningsAsErrors, warningsNotAsErrors, signAssembly, assemblyOriginatorKeyFile, treatWarningsAsErrors, defaultNamespace, runAnalyzers, runAnalyzersDuringLiveAnalysis, ruleset)
{
SourceFiles = sourceFiles.EmptyIfDefault();
ProjectReferences = projectReferences.EmptyIfDefault();
References = references.EmptyIfDefault();
PackageReferences = packageReferences.EmptyIfDefault();
Analyzers = analyzers.EmptyIfDefault();
AdditionalFiles = additionalFiles.EmptyIfDefault();
AnalyzerConfigFiles = analyzerConfigFiles.EmptyIfDefault();
ReferenceAliases = referenceAliases;
ProjectReferenceAliases = projectReferenceAliases;
FileInclusionGlobs = fileInclusionGlobs;
}
public static ProjectData Create(MSB.Evaluation.Project project)
{
var guid = PropertyConverter.ToGuid(project.GetPropertyValue(PropertyNames.ProjectGuid));
var name = project.GetPropertyValue(PropertyNames.ProjectName);
var assemblyName = project.GetPropertyValue(PropertyNames.AssemblyName);
var targetPath = project.GetPropertyValue(PropertyNames.TargetPath);
var outputPath = project.GetPropertyValue(PropertyNames.OutputPath);
var intermediateOutputPath = project.GetPropertyValue(PropertyNames.IntermediateOutputPath);
var projectAssetsFile = project.GetPropertyValue(PropertyNames.ProjectAssetsFile);
var configuration = project.GetPropertyValue(PropertyNames.Configuration);
var platform = project.GetPropertyValue(PropertyNames.Platform);
var platformTarget = project.GetPropertyValue(PropertyNames.PlatformTarget);
var defaultNamespace = project.GetPropertyValue(PropertyNames.RootNamespace);
var targetFramework = new FrameworkName(project.GetPropertyValue(PropertyNames.TargetFrameworkMoniker));
var targetFrameworkValue = project.GetPropertyValue(PropertyNames.TargetFramework);
var targetFrameworks = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.TargetFrameworks), ';');
if (!string.IsNullOrWhiteSpace(targetFrameworkValue) && targetFrameworks.Length == 0)
{
targetFrameworks = ImmutableArray.Create(targetFrameworkValue);
}
var languageVersion = PropertyConverter.ToLanguageVersion(project.GetPropertyValue(PropertyNames.LangVersion));
var allowUnsafeCode = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.AllowUnsafeBlocks), defaultValue: false);
var checkForOverflowUnderflow = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.CheckForOverflowUnderflow), defaultValue: false);
var outputKind = PropertyConverter.ToOutputKind(project.GetPropertyValue(PropertyNames.OutputType));
var nullableContextOptions = PropertyConverter.ToNullableContextOptions(project.GetPropertyValue(PropertyNames.Nullable));
var documentationFile = project.GetPropertyValue(PropertyNames.DocumentationFile);
var preprocessorSymbolNames = PropertyConverter.ToPreprocessorSymbolNames(project.GetPropertyValue(PropertyNames.DefineConstants));
var suppressedDiagnosticIds = PropertyConverter.ToSuppressedDiagnosticIds(project.GetPropertyValue(PropertyNames.NoWarn));
var warningsAsErrors = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsAsErrors), ',');
var warningsNotAsErrors = PropertyConverter.SplitList(project.GetPropertyValue(PropertyNames.WarningsNotAsErrors), ',');
var signAssembly = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.SignAssembly), defaultValue: false);
var assemblyOriginatorKeyFile = project.GetPropertyValue(PropertyNames.AssemblyOriginatorKeyFile);
var treatWarningsAsErrors = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.TreatWarningsAsErrors), defaultValue: false);
var runAnalyzers = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzers), defaultValue: true);
var runAnalyzersDuringLiveAnalysis = PropertyConverter.ToBoolean(project.GetPropertyValue(PropertyNames.RunAnalyzersDuringLiveAnalysis), defaultValue: true);
return new ProjectData(
guid, name, assemblyName, targetPath, outputPath, intermediateOutputPath, projectAssetsFile,
configuration, platform, platformTarget, targetFramework, targetFrameworks, outputKind, languageVersion, nullableContextOptions, allowUnsafeCode, checkForOverflowUnderflow,
documentationFile, preprocessorSymbolNames, suppressedDiagnosticIds, warningsAsErrors, warningsNotAsErrors, signAssembly, assemblyOriginatorKeyFile, treatWarningsAsErrors, defaultNamespace, runAnalyzers, runAnalyzersDuringLiveAnalysis, ruleset: null);
}
public static ProjectData Create(string projectFilePath, MSB.Execution.ProjectInstance projectInstance, MSB.Evaluation.Project project)
{
var projectFolderPath = Path.GetDirectoryName(projectFilePath);
var guid = PropertyConverter.ToGuid(projectInstance.GetPropertyValue(PropertyNames.ProjectGuid));
var name = projectInstance.GetPropertyValue(PropertyNames.ProjectName);
var assemblyName = projectInstance.GetPropertyValue(PropertyNames.AssemblyName);
var targetPath = projectInstance.GetPropertyValue(PropertyNames.TargetPath);
var outputPath = projectInstance.GetPropertyValue(PropertyNames.OutputPath);
var intermediateOutputPath = projectInstance.GetPropertyValue(PropertyNames.IntermediateOutputPath);
var projectAssetsFile = projectInstance.GetPropertyValue(PropertyNames.ProjectAssetsFile);
var configuration = projectInstance.GetPropertyValue(PropertyNames.Configuration);
var platform = projectInstance.GetPropertyValue(PropertyNames.Platform);
var platformTarget = projectInstance.GetPropertyValue(PropertyNames.PlatformTarget);
var defaultNamespace = projectInstance.GetPropertyValue(PropertyNames.RootNamespace);
var targetFramework = new FrameworkName(projectInstance.GetPropertyValue(PropertyNames.TargetFrameworkMoniker));
var targetFrameworkValue = projectInstance.GetPropertyValue(PropertyNames.TargetFramework);
var targetFrameworks = PropertyConverter.SplitList(projectInstance.GetPropertyValue(PropertyNames.TargetFrameworks), ';');
if (!string.IsNullOrWhiteSpace(targetFrameworkValue) && targetFrameworks.Length == 0)
{
targetFrameworks = ImmutableArray.Create(targetFrameworkValue);
}
var languageVersion = PropertyConverter.ToLanguageVersion(projectInstance.GetPropertyValue(PropertyNames.LangVersion));
var allowUnsafeCode = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.AllowUnsafeBlocks), defaultValue: false);
var checkForOverflowUnderflow = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.CheckForOverflowUnderflow), defaultValue: false);
var outputKind = PropertyConverter.ToOutputKind(projectInstance.GetPropertyValue(PropertyNames.OutputType));
var nullableContextOptions = PropertyConverter.ToNullableContextOptions(projectInstance.GetPropertyValue(PropertyNames.Nullable));
var documentationFile = projectInstance.GetPropertyValue(PropertyNames.DocumentationFile);
var preprocessorSymbolNames = PropertyConverter.ToPreprocessorSymbolNames(projectInstance.GetPropertyValue(PropertyNames.DefineConstants));
var suppressedDiagnosticIds = PropertyConverter.ToSuppressedDiagnosticIds(projectInstance.GetPropertyValue(PropertyNames.NoWarn));
var warningsAsErrors = PropertyConverter.SplitList(projectInstance.GetPropertyValue(PropertyNames.WarningsAsErrors), ',');
var warningsNotAsErrors = PropertyConverter.SplitList(projectInstance.GetPropertyValue(PropertyNames.WarningsNotAsErrors), ',');
var signAssembly = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.SignAssembly), defaultValue: false);
var treatWarningsAsErrors = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.TreatWarningsAsErrors), defaultValue: false);
var runAnalyzers = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.RunAnalyzers), defaultValue: true);
var runAnalyzersDuringLiveAnalysis = PropertyConverter.ToBoolean(projectInstance.GetPropertyValue(PropertyNames.RunAnalyzersDuringLiveAnalysis), defaultValue: true);
var assemblyOriginatorKeyFile = projectInstance.GetPropertyValue(PropertyNames.AssemblyOriginatorKeyFile);
var ruleset = ResolveRulesetIfAny(projectInstance);
var sourceFiles = GetFullPaths(
projectInstance.GetItems(ItemNames.Compile), filter: FileNameIsNotGenerated);
var projectReferences = ImmutableArray.CreateBuilder<string>();
var projectReferenceAliases = ImmutableDictionary.CreateBuilder<string, string>();
var references = ImmutableArray.CreateBuilder<string>();
var referenceAliases = ImmutableDictionary.CreateBuilder<string, string>();
foreach (var referencePathItem in projectInstance.GetItems(ItemNames.ReferencePath))
{
var referenceSourceTarget = referencePathItem.GetMetadataValue(MetadataNames.ReferenceSourceTarget);
var aliases = referencePathItem.GetMetadataValue(MetadataNames.Aliases);
// If this reference came from a project reference, count it as such. We never want to directly look
// at the ProjectReference items in the project, as those don't always create project references
// if things like OutputItemType or ReferenceOutputAssembly are set. It's also possible that other
// MSBuild logic is adding or removing properties too.
if (StringComparer.OrdinalIgnoreCase.Equals(referenceSourceTarget, ItemNames.ProjectReference))
{
var projectReferenceOriginalItemSpec = referencePathItem.GetMetadataValue(MetadataNames.ProjectReferenceOriginalItemSpec);
if (projectReferenceOriginalItemSpec.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase))
{
var projectReferenceFilePath = Path.GetFullPath(Path.Combine(projectFolderPath, projectReferenceOriginalItemSpec));
projectReferences.Add(projectReferenceFilePath);
if (!string.IsNullOrEmpty(aliases))
{
projectReferenceAliases[projectReferenceFilePath] = aliases;
}
continue;
}
}
var fullPath = referencePathItem.GetMetadataValue(MetadataNames.FullPath);
if (!string.IsNullOrEmpty(fullPath))
{
references.Add(fullPath);
if (!string.IsNullOrEmpty(aliases))
{
referenceAliases[fullPath] = aliases;
}
}
}
var packageReferences = GetPackageReferences(projectInstance.GetItems(ItemNames.PackageReference));
var analyzers = GetFullPaths(projectInstance.GetItems(ItemNames.Analyzer));
var additionalFiles = GetFullPaths(projectInstance.GetItems(ItemNames.AdditionalFiles));
var editorConfigFiles = GetFullPaths(projectInstance.GetItems(ItemNames.EditorConfigFiles));
var includeGlobs = project.GetAllGlobs().Select(x => x.MsBuildGlob).ToImmutableArray();
return new ProjectData(
guid,
name,
assemblyName,
targetPath,
outputPath,
intermediateOutputPath,
projectAssetsFile,
configuration,
platform,
platformTarget,
targetFramework,
targetFrameworks,
outputKind,
languageVersion,
nullableContextOptions,
allowUnsafeCode,
checkForOverflowUnderflow,
documentationFile,
preprocessorSymbolNames,
suppressedDiagnosticIds,
warningsAsErrors,
warningsNotAsErrors,
signAssembly,
assemblyOriginatorKeyFile,
sourceFiles,
projectReferences.ToImmutable(),
references.ToImmutable(),
packageReferences,
analyzers,
additionalFiles,
editorConfigFiles,
treatWarningsAsErrors,
defaultNamespace,
runAnalyzers,
runAnalyzersDuringLiveAnalysis,
ruleset,
referenceAliases.ToImmutableDictionary(),
projectReferenceAliases.ToImmutable(),
includeGlobs);
}
private static RuleSet ResolveRulesetIfAny(MSB.Execution.ProjectInstance projectInstance)
{
var rulesetIfAny = projectInstance.Properties.FirstOrDefault(x => x.Name == "ResolvedCodeAnalysisRuleSet");
if (rulesetIfAny != null)
return RuleSet.LoadEffectiveRuleSetFromFile(Path.Combine(projectInstance.Directory, rulesetIfAny.EvaluatedValue));
return null;
}
private static bool FileNameIsNotGenerated(string filePath)
=> !Path.GetFileName(filePath).StartsWith("TemporaryGeneratedFile_", StringComparison.OrdinalIgnoreCase);
private static ImmutableArray<string> GetFullPaths(IEnumerable<MSB.Execution.ProjectItemInstance> items, Func<string, bool> filter = null)
{
var builder = ImmutableArray.CreateBuilder<string>();
var addedSet = new HashSet<string>();
filter = filter ?? (_ => true);
foreach (var item in items)
{
var fullPath = item.GetMetadataValue(MetadataNames.FullPath);
if (filter(fullPath) && addedSet.Add(fullPath))
{
builder.Add(fullPath);
}
}
return builder.ToImmutable();
}
private static ImmutableArray<PackageReference> GetPackageReferences(ICollection<MSB.Execution.ProjectItemInstance> items)
{
var builder = ImmutableArray.CreateBuilder<PackageReference>(items.Count);
var addedSet = new HashSet<PackageReference>();
foreach (var item in items)
{
var name = item.EvaluatedInclude;
var versionValue = item.GetMetadataValue(MetadataNames.Version);
var versionRange = PropertyConverter.ToVersionRange(versionValue);
var dependency = new PackageDependency(name, versionRange);
var isImplicitlyDefinedValue = item.GetMetadataValue(MetadataNames.IsImplicitlyDefined);
var isImplicitlyDefined = PropertyConverter.ToBoolean(isImplicitlyDefinedValue, defaultValue: false);
var packageReference = new PackageReference(dependency, isImplicitlyDefined);
if (addedSet.Add(packageReference))
{
builder.Add(packageReference);
}
}
return builder.ToImmutable();
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Project31.CoreServices;
namespace Project31.ApplicationFramework
{
/// <summary>
/// Provides a "vertical tracking indicator" for use in splitter bars.
/// </summary>
internal class VerticalTrackingIndicator
{
/// <summary>
/// SRCCOPY ROP.
/// </summary>
private const int SRCCOPY = 0x00cc0020;
/// <summary>
/// DCX_PARENTCLIP option for GetDCEx.
/// </summary>
private const int DCX_PARENTCLIP = 0x00000020;
/// <summary>
/// Valid indicator. Used to ensure that calls to Begin, Update and End are valid when
/// they are made.
/// </summary>
private bool valid = false;
/// <summary>
/// Control into which the tracking indicator will be drawn.
/// </summary>
private Control control;
/// <summary>
/// Graphics object for the control into which the tracking indicator will be drawn.
/// </summary>
private Graphics controlGraphics;
/// <summary>
/// DC for the control into which the tracking indicator will be drawn.
/// </summary>
private IntPtr controlDC;
/// <summary>
/// The capture bitmap. Used to capture the portion of the control that is being
/// overwritten by the tracking indicator so that it can be restored when the
/// tracking indicator is moved to a new location.
/// </summary>
private Bitmap captureBitmap;
/// <summary>
/// Last capture location where the tracking indicator was drawn.
/// </summary>
private Point lastCaptureLocation;
/// <summary>
/// The tracking indicator bitmap.
/// </summary>
private Bitmap trackingIndicatorBitmap;
/// <summary>
/// DllImport of Win32 GetDCEx.
/// </summary>
[DllImport("user32.dll")]
public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr region, System.Int32 dw);
/// <summary>
/// DllImport of GDI BitBlt.
/// </summary>
[DllImport("gdi32.dll")]
private static extern bool BitBlt( IntPtr hdcDest, // handle to destination DC (device context)
int nXDest, // x-coord of destination upper-left corner
int nYDest, // y-coord of destination upper-left corner
int nWidth, // width of destination rectangle
int nHeight, // height of destination rectangle
IntPtr hdcSrc, // handle to source DC
int nXSrc, // x-coordinate of source upper-left corner
int nYSrc, // y-coordinate of source upper-left corner
System.Int32 dwRop);// raster operation code
/// <summary>
/// DllImport of Win32 ReleaseDC.
/// </summary>
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
private static extern bool ReleaseDC(IntPtr hWnd, IntPtr dc);
/// <summary>
/// Initializes a new instance of the VerticalTrackingIndicator class.
/// </summary>
public VerticalTrackingIndicator()
{
}
/// <summary>
/// Begin a tracking indicator in the specified control using the specified rectangle.
/// </summary>
/// <param name="control">The control into which the tracking indicator will be drawn.</param>
/// <param name="rectangle">Rectangle structure that represents the tracking indicator rectangle, relative to the upper-left corner of the control into which it will be drawn.</param>
public void Begin(Control control, Rectangle rectangle)
{
// Can't Begin twice.
Debug.Assert(!valid, "Invalid nested Begin", "You must first call the End method of a VerticalTrackingIndicator before calling its Begin method again.");
if (valid)
End();
// Save away the control. We need this so we can call ReleaseDC later on.
this.control = control;
// Get a DC for the "visible region" the specified control. Children are not clipped
// for this DC, which allows us to draw the tracking indicator over them.
controlDC = GetDCEx(control.Handle, System.IntPtr.Zero, DCX_PARENTCLIP);
// Get a graphics object for the DC.
controlGraphics = Graphics.FromHdc(controlDC);
// Instantiate the capture bitmap.
captureBitmap = new Bitmap(rectangle.Width, rectangle.Height);
// Instantiate and paint the tracking indicator bitmap.
trackingIndicatorBitmap = new Bitmap(rectangle.Width, rectangle.Height);
Graphics trackingIndicatorBitmapGraphics = Graphics.FromImage(trackingIndicatorBitmap);
HatchBrush hatchBrush = new HatchBrush( HatchStyle.Percent50,
Color.FromArgb(128, Color.Black),
Color.FromArgb(128, Color.White));
trackingIndicatorBitmapGraphics.FillRectangle(hatchBrush, new Rectangle(0, 0, rectangle.Width, rectangle.Height));
hatchBrush.Dispose();
trackingIndicatorBitmapGraphics.Dispose();
// Draw the new tracking indicator.
DrawTrackingIndicator(rectangle.Location);
// Valid now.
valid = true;
}
/// <summary>
/// Update the location of the tracking indicator.
/// </summary>
/// <param name="location">The new location of the tracking indicator.</param>
public void Update(Point location)
{
// Can't Update without a Begin.
Debug.Assert(valid, "Invalid Update", "You must first call the Begin method of a VerticalTrackingIndicator before calling its Update method.");
if (!valid)
return;
// Undraw the last tracking indicator.
UndrawLastTrackingIndicator();
// Draw the new tracking indicator.
DrawTrackingIndicator(location);
}
/// <summary>
/// End the tracking indicator.
/// </summary>
public void End()
{
// Can't Update without a Begin.
Debug.Assert(valid, "Invalid End", "You must first call the Begin method of a VerticalTrackingIndicator before calling its End method.");
if (!valid)
return;
// Undraw the last tracking indicator.
UndrawLastTrackingIndicator();
// Cleanup the capture bitmap.
captureBitmap.Dispose();
// Dispose of the graphics context and DC for the control.
controlGraphics.Dispose();
ReleaseDC(control.Handle, controlDC);
// Not valid anymore.
valid = false;
}
/// <summary>
/// "Undraw" the last tracking indicator.
/// </summary>
private void UndrawLastTrackingIndicator()
{
controlGraphics.DrawImageUnscaled(captureBitmap, lastCaptureLocation);
}
/// <summary>
/// Draw the tracking indicator.
/// </summary>
private void DrawTrackingIndicator(Point location)
{
// BitBlt the contents of the specified rectangle of the control to the capture bitmap.
Graphics captureBitmapGraphics = Graphics.FromImage(captureBitmap);
System.IntPtr captureBitmapDC = captureBitmapGraphics.GetHdc();
BitBlt( captureBitmapDC, // handle to destination DC (device context)
0, // x-coord of destination upper-left corner
0, // y-coord of destination upper-left corner
captureBitmap.Width, // width of destination rectangle
captureBitmap.Height, // height of destination rectangle
controlDC, // handle to source DC
location.X, // x-coordinate of source upper-left corner
location.Y, // y-coordinate of source upper-left corner
SRCCOPY); // raster operation code
captureBitmapGraphics.ReleaseHdc(captureBitmapDC);
captureBitmapGraphics.Dispose();
// Draw the tracking indicator bitmap.
controlGraphics.DrawImageUnscaled(trackingIndicatorBitmap, location);
// Remember the last capture location. UndrawLastTrackingIndicator uses this value
// to undraw this tracking indicator at this location.
lastCaptureLocation = location;
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// A Email Service to serve History in Paderborn CMS System
/// </summary>
public partial class EmailClient : ServiceClient<EmailClient>, IEmailClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the EmailClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public EmailClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the EmailClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public EmailClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the EmailClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public EmailClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the EmailClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public EmailClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <param name='email'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> EmailPostWithHttpMessagesAsync(EmailModel email = default(EmailModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (email != null)
{
email.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("email", email);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "EmailPost", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Email").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(email != null)
{
_requestContent = SafeJsonConvert.SerializeObject(email, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='notificationModel'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> EmailNotificationPostWithHttpMessagesAsync(NotificationModel notificationModel = default(NotificationModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (notificationModel != null)
{
notificationModel.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("notificationModel", notificationModel);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "EmailNotificationPost", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Email/Notification").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(notificationModel != null)
{
_requestContent = SafeJsonConvert.SerializeObject(notificationModel, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <param name='invitation'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> EmailInvitationPostWithHttpMessagesAsync(InvitationModel invitation = default(InvitationModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (invitation != null)
{
invitation.Validate();
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("invitation", invitation);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "EmailInvitationPost", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Email/Invitation").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(invitation != null)
{
_requestContent = SafeJsonConvert.SerializeObject(invitation, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 202 && (int)_statusCode != 400 && (int)_statusCode != 503)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients
{
using System.Threading;
using System.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for EmailClient.
/// </summary>
public static partial class EmailClientExtensions
{
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='email'>
/// </param>
public static void EmailPost(this IEmailClient operations, EmailModel email = default(EmailModel))
{
Task.Factory.StartNew(s => ((IEmailClient)s).EmailPostAsync(email), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='email'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task EmailPostAsync(this IEmailClient operations, EmailModel email = default(EmailModel), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.EmailPostWithHttpMessagesAsync(email, null, cancellationToken).ConfigureAwait(false);
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='notificationModel'>
/// </param>
public static void EmailNotificationPost(this IEmailClient operations, NotificationModel notificationModel = default(NotificationModel))
{
Task.Factory.StartNew(s => ((IEmailClient)s).EmailNotificationPostAsync(notificationModel), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='notificationModel'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task EmailNotificationPostAsync(this IEmailClient operations, NotificationModel notificationModel = default(NotificationModel), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.EmailNotificationPostWithHttpMessagesAsync(notificationModel, null, cancellationToken).ConfigureAwait(false);
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='invitation'>
/// </param>
public static void EmailInvitationPost(this IEmailClient operations, InvitationModel invitation = default(InvitationModel))
{
Task.Factory.StartNew(s => ((IEmailClient)s).EmailInvitationPostAsync(invitation), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='invitation'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task EmailInvitationPostAsync(this IEmailClient operations, InvitationModel invitation = default(InvitationModel), CancellationToken cancellationToken = default(CancellationToken))
{
await operations.EmailInvitationPostWithHttpMessagesAsync(invitation, null, cancellationToken).ConfigureAwait(false);
}
}
}
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Rest;
using Models;
/// <summary>
/// A Email Service to serve History in Paderborn CMS System
/// </summary>
public partial interface IEmailClient : IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <param name='email'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> EmailPostWithHttpMessagesAsync(EmailModel email = default(EmailModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='notificationModel'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> EmailNotificationPostWithHttpMessagesAsync(NotificationModel notificationModel = default(NotificationModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <param name='invitation'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> EmailInvitationPostWithHttpMessagesAsync(InvitationModel invitation = default(InvitationModel), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients.Models
{
using Newtonsoft.Json;
using Microsoft.Rest;
public partial class EmailModel
{
/// <summary>
/// Initializes a new instance of the EmailModel class.
/// </summary>
public EmailModel() { }
/// <summary>
/// Initializes a new instance of the EmailModel class.
/// </summary>
public EmailModel(string recipient, string subject, string content)
{
Recipient = recipient;
Subject = subject;
Content = content;
}
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "recipient")]
public string Recipient { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "content")]
public string Content { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (Recipient == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Recipient");
}
if (Subject == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Subject");
}
if (Content == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Content");
}
}
}
}
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients.Models
{
using System;
using Newtonsoft.Json;
using Microsoft.Rest;
public partial class NotificationModel
{
/// <summary>
/// Initializes a new instance of the NotificationModel class.
/// </summary>
public NotificationModel() { }
/// <summary>
/// Initializes a new instance of the NotificationModel class.
/// </summary>
public NotificationModel(string recipient, string subject, string topic, string updater, DateTime date, string action)
{
Recipient = recipient;
Subject = subject;
Topic = topic;
Updater = updater;
Date = date;
Action = action;
}
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "recipient")]
public string Recipient { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "topic")]
public string Topic { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "updater")]
public string Updater { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "date")]
public DateTime Date { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "action")]
public string Action { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (Recipient == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Recipient");
}
if (Subject == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Subject");
}
if (Topic == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Topic");
}
if (Updater == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Updater");
}
if (Action == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Action");
}
}
}
}
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace PaderbornUniversity.SILab.Hip.CmsApi.Clients.Models
{
using Newtonsoft.Json;
using Microsoft.Rest;
public partial class InvitationModel
{
/// <summary>
/// Initializes a new instance of the InvitationModel class.
/// </summary>
public InvitationModel() { }
/// <summary>
/// Initializes a new instance of the InvitationModel class.
/// </summary>
public InvitationModel(string recipient, string subject)
{
Recipient = recipient;
Subject = subject;
}
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "recipient")]
public string Recipient { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "subject")]
public string Subject { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (Recipient == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Recipient");
}
if (Subject == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Subject");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MyGeneration
{
public partial class AboutBoxLogo : Control
{
private static Random rand = new Random();
private List<Ball> balls = new List<Ball>();
private List<Rectangle> pics = new List<Rectangle>();
private List<int> picindeces = new List<int>();
private List<Image> images = new List<Image>();
private Point ip;
private int countMoves = 0;
public AboutBoxLogo()
{
InitializeComponent();
this.DoubleBuffered = true;
}
public void Start()
{
// Add other developer pics here if desired.
images.Add(Properties.Resources.dev01tiny);
images.Add(Properties.Resources.dev02tiny);
for (int i = 0; i < 5; i++)
{
Ball b = new Ball(this);
b.MaxLifeInMoves = rand.Next(250) + 250;
balls.Add(b);
}
ip = new Point((this.ClientSize.Width - Properties.Resources.mygenlogo1.Width) / 2,
(this.ClientSize.Height - Properties.Resources.mygenlogo1.Height) / 2);
this.timerRepaint.Interval = 25;
this.timerRepaint.Enabled = true;
}
private void AboutBoxLogo_MouseUp(object sender, MouseEventArgs e)
{
pics.Add(new Rectangle(e.Location.X, 0, 4, 5));
picindeces.Add(rand.Next(images.Count));
}
protected override void OnPaint(PaintEventArgs pe)
{
this.timerRepaint.Enabled = false;
Graphics g = pe.Graphics;
for (int i = 0; i < pics.Count; i++)
{
g.DrawImage(images[picindeces[i]], pics[i]);
}
foreach (Ball b in balls)
{
b.Paint(g);
}
g.DrawImage(Properties.Resources.mygenlogo1, ip);
// Calling the base class OnPaint
base.OnPaint(pe);
this.timerRepaint.Enabled = true;
}
private void timerRepaint_Tick(object sender, EventArgs e)
{
countMoves++;
List<Ball> ballsToAdd = null;
List<Ball> ballsToRemove = null;
foreach (Ball b in balls)
{
if (b.IsExpired)
{
if (ballsToRemove == null) ballsToRemove = new List<Ball>();
ballsToRemove.Add(b);
if (!b.IsParticle)
{
if (ballsToAdd == null) ballsToAdd = new List<Ball>();
ballsToAdd.AddRange(b.Explode());
}
}
else
{
b.Move();
}
}
if (ballsToRemove != null)
{
foreach (Ball b in ballsToRemove) balls.Remove(b);
}
if (ballsToAdd != null)
{
foreach (Ball b in ballsToAdd) balls.Add(b);
}
if (countMoves == 50 && this.balls.Count < 300)
{
countMoves = 0;
Ball b = new Ball(this);
b.MaxLifeInMoves = rand.Next(500) + 100;
balls.Add(b);
}
List<int> picsToRemove = null;
for (int i=0; i < pics.Count; i++)
{
Rectangle r = pics[i];
if (r.Top > this.Height)
{
if (picsToRemove == null) picsToRemove = new List<int>();
picsToRemove.Add(i);
}
else
{
r.Y = r.Y + 1;
r.X = r.X - 1;
r.Width = r.Width + 2;
r.Height = r.Height + 2;
pics[i] = r;
}
}
if (picsToRemove != null)
{
foreach (int i in picsToRemove)
{
pics.RemoveAt(i);
picindeces.RemoveAt(i);
}
}
this.Invalidate();
}
/// <summary>
/// Inner class Ball.
/// </summary>
public class Ball
{
public Ball(Control c, Pen pen)
{
this.Control = c;
this.Brush = pen.Brush;
this.GenerateOffsets();
this.GenerateLocation();
}
public Ball(Control c)
{
this.Control = c;
this.GenerateOffsets();
this.GenerateLocation();
this.GenerateColor();
}
public Ball(Control c, Point location)
{
this.Control = c;
this.Location = location;
this.GenerateOffsets();
this.GenerateLocation();
this.GenerateColor();
}
public Ball(Control c, Point location, int offsetX, int offsetY, Pen pen)
{
this.Control = c;
this.Location = location;
this.Brush = pen.Brush;
this.OffsetX = offsetX;
this.OffsetY = offsetY;
}
private Ball(Control c, Point location, int radius, Brush brush, int maxLives)
{
this.Control = c;
this.Location = location;
this.Brush = brush;
this.Radius = radius;
this.MaxLifeInMoves = maxLives;
if (radius <= 2) this.IsParticle = true;
this.GenerateOffsets();
}
public Ball[] Explode()
{
int maxLives = 40;
if (this.MaxLifeInMoves <= maxLives && this.MaxLifeInMoves > 0) maxLives = MaxLifeInMoves / 2;
return new Ball[] {
new Ball(this.Control, this.Location, this.Radius/2, this.Brush, maxLives),
new Ball(this.Control, this.Location, this.Radius/2, this.Brush, maxLives),
new Ball(this.Control, this.Location, this.Radius/2, this.Brush, maxLives),
new Ball(this.Control, this.Location, this.Radius/2, this.Brush, maxLives)
};
}
public bool IsExpired
{
get
{
if (IsParticle)
{
return (hasHitWallSinceExpire && IsLifeExpired);
}
else
{
return IsLifeExpired;
}
}
}
private bool IsLifeExpired
{
get
{
if (this.MaxLifeInMoves == -1) return false;
else return (this.LifeInMoves > this.MaxLifeInMoves);
}
}
private void GenerateColor()
{
int r = rand.Next(255);
int b = rand.Next(255 - r) + r;
int a = rand.Next(128) + 127;
Pen p = new Pen(Color.FromArgb(a, r, r, b));
this.Brush = p.Brush;
}
private void GenerateLocation()
{
int x = rand.Next(Control.Width - (Radius * 2)) + Radius,
y = rand.Next(Control.Height - (Radius * 2)) + Radius;
this.Location = new Point(x, y);
}
private void GenerateOffsets()
{
int ox = 0, oy = 0;
while (ox == 0) ox = rand.Next(MaxSpeed * 2) - MaxSpeed;
while (oy == 0) oy = rand.Next(MaxSpeed * 2) - MaxSpeed;
this.OffsetX = ox;
this.OffsetY = oy;
}
public void Move()
{
LifeInMoves++;
int x = OffsetX + Location.X;
int y = OffsetY + Location.Y;
if ((x < 0 && OffsetX < 0) || (x > (this.Control.ClientSize.Width - Radius) && OffsetX > 0))
{
OffsetX = -1 * OffsetX;
x = OffsetX + Location.X;
if (this.IsParticle && this.IsLifeExpired) this.hasHitWallSinceExpire = true;
}
if ((y < 0 && OffsetY < 0) || (y > (this.Control.ClientSize.Height - Radius) && OffsetY > 0))
{
OffsetY = -1 * OffsetY;
y = OffsetY + Location.Y;
if (this.IsParticle && this.IsLifeExpired) this.hasHitWallSinceExpire = true;
}
Location.X = x;
Location.Y = y;
}
public void Paint(Graphics g)
{
if (IsExpired) return;
g.FillEllipse(this.Brush, new Rectangle(Location.X - Radius,
Location.Y - Radius,
Radius * 2,
Radius * 2));
}
private bool hasHitWallSinceExpire = false;
public static int MaxSpeed = 6;
public bool IsParticle = false;
public Point Location;
public int Radius = 8;
public Brush Brush;
public int OffsetX = 1;
public int OffsetY = 1;
public Control Control;
public int LifeInMoves = 0;
public int MaxLifeInMoves = -1;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.