context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.IO;
using System.Text;
namespace UrlHistoryLibrary
{
/// <summary>
/// Some Win32Api Pinvoke.
/// </summary>
public class Win32api
{
/// <summary>
/// Used by CannonializeURL method.
/// </summary>
[Flags]
public enum shlwapi_URL : uint
{
/// <summary>
/// Treat "/./" and "/../" in a URL string as literal characters, not as shorthand for navigation.
/// </summary>
URL_DONT_SIMPLIFY = 0x08000000,
/// <summary>
/// Convert any occurrence of "%" to its escape sequence.
/// </summary>
URL_ESCAPE_PERCENT = 0x00001000,
/// <summary>
/// Replace only spaces with escape sequences. This flag takes precedence over URL_ESCAPE_UNSAFE, but does not apply to opaque URLs.
/// </summary>
URL_ESCAPE_SPACES_ONLY = 0x04000000,
/// <summary>
/// Replace unsafe characters with their escape sequences. Unsafe characters are those characters that may be altered during transport across the Internet, and include the (<, >, ", #, {, }, |, \, ^, ~, [, ], and ') characters. This flag applies to all URLs, including opaque URLs.
/// </summary>
URL_ESCAPE_UNSAFE = 0x20000000,
/// <summary>
/// Combine URLs with client-defined pluggable protocols, according to the World Wide Web Consortium (W3C) specification. This flag does not apply to standard protocols such as ftp, http, gopher, and so on. If this flag is set, UrlCombine does not simplify URLs, so there is no need to also set URL_DONT_SIMPLIFY.
/// </summary>
URL_PLUGGABLE_PROTOCOL = 0x40000000,
/// <summary>
/// Un-escape any escape sequences that the URLs contain, with two exceptions. The escape sequences for "?" and "#" are not un-escaped. If one of the URL_ESCAPE_XXX flags is also set, the two URLs are first un-escaped, then combined, then escaped.
/// </summary>
URL_UNESCAPE = 0x10000000
}
[DllImport("shlwapi.dll")]
public static extern int UrlCanonicalize(
string pszUrl,
StringBuilder pszCanonicalized,
ref int pcchCanonicalized,
shlwapi_URL dwFlags
);
/// <summary>
/// Takes a URL string and converts it into canonical form
/// </summary>
/// <param name="pszUrl">URL string</param>
/// <param name="dwFlags">shlwapi_URL Enumeration. Flags that specify how the URL is converted to canonical form.</param>
/// <returns>The converted URL</returns>
public static string CannonializeURL(string pszUrl, shlwapi_URL dwFlags)
{
StringBuilder buff = new StringBuilder(260);
int s = buff.Capacity;
int c = UrlCanonicalize(pszUrl , buff,ref s, dwFlags);
if(c ==0)
return buff.ToString();
else
{
buff.Capacity = s;
c = UrlCanonicalize(pszUrl , buff,ref s, dwFlags);
return buff.ToString();
}
}
public struct SYSTEMTIME
{
public Int16 Year;
public Int16 Month;
public Int16 DayOfWeek;
public Int16 Day;
public Int16 Hour;
public Int16 Minute;
public Int16 Second;
public Int16 Milliseconds;
}
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
static extern bool FileTimeToSystemTime
(ref FILETIME FileTime, ref SYSTEMTIME SystemTime);
/// <summary>
/// Converts a file time to DateTime format.
/// </summary>
/// <param name="filetime">FILETIME structure</param>
/// <returns>DateTime structure</returns>
public static DateTime FileTimeToDateTime(FILETIME filetime)
{
SYSTEMTIME st = new SYSTEMTIME();
FileTimeToSystemTime(ref filetime, ref st);
return new DateTime(st.Year, st.Month, st.Day, st.Hour , st.Minute, st.Second, st.Milliseconds);
}
[DllImport("Kernel32.dll", CharSet=CharSet.Auto)]
static extern bool SystemTimeToFileTime([In] ref SYSTEMTIME lpSystemTime,
out FILETIME lpFileTime);
/// <summary>
/// Converts a DateTime to file time format.
/// </summary>
/// <param name="datetime">DateTime structure</param>
/// <returns>FILETIME structure</returns>
public static FILETIME DateTimeToFileTime(DateTime datetime)
{
SYSTEMTIME st = new SYSTEMTIME();
st.Year = (short)datetime.Year;
st.Month = (short)datetime.Month;
st.Day = (short)datetime.Day;
st.Hour = (short)datetime.Hour;
st.Minute = (short)datetime.Minute;
st.Second = (short)datetime.Second;
st.Milliseconds = (short)datetime.Millisecond;
FILETIME filetime;
SystemTimeToFileTime(ref st, out filetime);
return filetime;
}
//compares two file times.
[DllImport("Kernel32.dll")]
public static extern int CompareFileTime([In] ref FILETIME lpFileTime1,[In] ref FILETIME lpFileTime2);
//Retrieves information about an object in the file system.
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
public const uint SHGFI_ATTR_SPECIFIED =
0x20000;
public const uint SHGFI_ATTRIBUTES = 0x800;
public const uint SHGFI_PIDL = 0x8;
public const uint SHGFI_DISPLAYNAME =
0x200;
public const uint SHGFI_USEFILEATTRIBUTES
= 0x10;
public const uint FILE_ATTRIBUTRE_NORMAL =
0x4000;
public const uint SHGFI_EXETYPE = 0x2000;
public const uint SHGFI_SYSICONINDEX =
0x4000;
public const uint ILC_COLORDDB = 0x1;
public const uint ILC_MASK = 0x0;
public const uint ILD_TRANSPARENT = 0x1;
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0;
public const uint SHGFI_SHELLICONSIZE =
0x4;
public const uint SHGFI_SMALLICON = 0x1;
public const uint SHGFI_TYPENAME = 0x400;
public const uint SHGFI_ICONLOCATION =
0x1000;
}
/// <summary>
/// Contains information about a file object.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
/// <summary>
/// The helper class to sort in ascending order by FileTime(LastVisited).
/// </summary>
public class SortFileTimeAscendingHelper : IComparer
{
[DllImport("Kernel32.dll")]
static extern int CompareFileTime([In] ref FILETIME lpFileTime1,[In] ref FILETIME lpFileTime2);
int IComparer.Compare(object a, object b)
{
STATURL c1=(STATURL)a;
STATURL c2=(STATURL)b;
return (CompareFileTime(ref c1.ftLastVisited, ref c2.ftLastVisited));
}
public static IComparer SortFileTimeAscending()
{
return (IComparer) new SortFileTimeAscendingHelper();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#if UNITY_EDITOR
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;
namespace HoloToolkit.Sharing.Utilities
{
public class ExternalProcess : IDisposable
{
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_CreateProcess([MarshalAs(UnmanagedType.LPStr)] string cmdline);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern bool ExternalProcessAPI_IsRunning(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_SendLine(IntPtr handle, [MarshalAs(UnmanagedType.LPStr)] string line);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ExternalProcessAPI_GetLine(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
private static extern void ExternalProcessAPI_DestroyProcess(IntPtr handle);
[DllImport("ExternalProcessAPI", CallingConvention = CallingConvention.Cdecl)]
public static extern void ExternalProcessAPI_ConfirmOrBeginProcess([MarshalAs(UnmanagedType.LPStr)] string processName);
private IntPtr mHandle = IntPtr.Zero;
/*
* First some static utility functions, used by some other code as well.
* They are related to "external processes" so they appear here.
*/
private static string sAppDataPath;
static public void Launch(string appName)
{
// Full or relative paths only. Currently unused.
if (!appName.StartsWith(@"\"))
{
appName += @"\";
}
string appPath = AppDataPath + appName;
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.Start();
}
static private string AppDataPath
{
get
{
if (string.IsNullOrEmpty(sAppDataPath))
{
sAppDataPath = Application.dataPath.Replace("/", @"\");
}
return sAppDataPath;
}
}
static public bool FindAndLaunch(string appName)
{
return FindAndLaunch(appName, null);
}
static public bool FindAndLaunch(string appName, string args)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
string appPath = FindPathToExecutable(appName);
if (appPath == null)
{
return false;
}
string appDir = Path.GetDirectoryName(appPath);
Process pr = new Process();
pr.StartInfo.FileName = appPath;
pr.StartInfo.WorkingDirectory = appDir;
pr.StartInfo.Arguments = args;
return pr.Start();
}
static public string FindPathToExecutable(string appName)
{
// Start at working directory, append appName (should read "appRelativePath"), see if it exists.
// If not go up to parent and try again till drive level reached.
if (!appName.StartsWith(@"\"))
{
appName = @"\" + appName;
}
string searchDir = AppDataPath;
while (searchDir.Length > 3)
{
string appPath = searchDir + appName;
if (File.Exists(appPath))
{
return appPath;
}
searchDir = Path.GetDirectoryName(searchDir);
}
return null;
}
static public string MakeRelativePath(string path1, string path2)
{
// TBD- doesn't really belong in ExternalProcess.
// Launching standalone from BuildWalla does not like backslashes or double-quotes. Why?
path1 = path1.Replace('\\', '/');
path2 = path2.Replace('\\', '/');
path1 = path1.Replace("\"", "");
path2 = path2.Replace("\"", "");
Uri uri1 = new Uri(path1);
Uri uri2 = new Uri(path2);
Uri relativePath = uri1.MakeRelativeUri(uri2);
return relativePath.OriginalString;
}
/*
* The actual ExternalProcess class.
*/
static public ExternalProcess CreateExternalProcess(string appName)
{
return CreateExternalProcess(appName, null);
}
static public ExternalProcess CreateExternalProcess(string appName, string args)
{
// Seems like it would be safer and more informative to call this static method and test for null after.
try
{
return new ExternalProcess(appName, args);
}
catch (Exception ex)
{
UnityEngine.Debug.LogError("Unable to start process " + appName + ", " + ex.Message + ".");
}
return null;
}
private ExternalProcess(string appName, string args)
{
appName = appName.Replace("/", @"\");
string appPath = appName;
if (!File.Exists(appPath))
{
appPath = FindPathToExecutable(appName);
}
if (appPath == null)
{
throw new ArgumentException("Unable to find app " + appPath);
}
// This may throw, calling code should catch the exception.
string launchString = (args == null) ? appPath : appPath + " " + args;
mHandle = ExternalProcessAPI_CreateProcess(launchString);
}
~ExternalProcess()
{
this.Dispose(false);
}
public bool IsRunning()
{
try
{
if (mHandle != IntPtr.Zero)
{
return (ExternalProcessAPI_IsRunning(mHandle));
}
}
catch
{
this.Terminate();
}
return (false);
}
public bool WaitForStart(float seconds)
{
return WaitFor(seconds, () => { return ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitForShutdown(float seconds)
{
return WaitFor(seconds, () => { return !ExternalProcessAPI_IsRunning(mHandle); });
}
public bool WaitFor(float seconds, Func<bool> func)
{
if (seconds <= 0.0f)
seconds = 5.0f;
float end = Time.realtimeSinceStartup + seconds;
bool hasHappened = false;
while (Time.realtimeSinceStartup < end && !hasHappened)
{
hasHappened = func();
if (hasHappened)
{
break;
}
Thread.Sleep(Math.Min(500, (int)(seconds * 1000)));
}
return hasHappened;
}
public void SendLine(string line)
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_SendLine(mHandle, line);
}
}
catch
{
this.Terminate();
}
}
public string GetLine()
{
try
{
if (mHandle != IntPtr.Zero)
{
return (Marshal.PtrToStringAnsi(ExternalProcessAPI_GetLine(mHandle)));
}
}
catch
{
this.Terminate();
}
return (null);
}
public void Terminate()
{
try
{
if (mHandle != IntPtr.Zero)
{
ExternalProcessAPI_DestroyProcess(mHandle);
}
}
catch
{
}
mHandle = IntPtr.Zero;
}
// IDisposable
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
this.Terminate();
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Moq;
using Xunit;
namespace Tossit.Core.Tests
{
public class ReflectionHelperTests
{
private readonly Mock<IDependencyContextProxy> _dependencyContextProxy;
public ReflectionHelperTests()
{
_dependencyContextProxy = new Mock<IDependencyContextProxy>();
_dependencyContextProxy.Setup(x => x.GetDefaultAssemblyNames())
.Returns(new List<AssemblyName> { new AssemblyName("Tossit.Core.Tests") });
}
[Fact]
public void GetTypesThatImplementedByInterfaceShouldReturnTypes()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
// Act
var result = reflectionHelper.GetTypesThatImplementedByInterface(typeof(IBarInterface<>));
// Assert
Assert.True(result.All(x => false));
}
[Fact]
public void GetTypesThatImplementedByInterfaceByNonExistingInterfaceTypeShouldReturnEmptyList()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
// Act
var result = reflectionHelper.GetTypesThatImplementedByInterface(typeof(IFooInterface<>));
// Assert
Assert.True(result.ToList().Count == 0);
}
[Fact]
public void InvokeGenericMethodShouldCallGivenMethod()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
var parameter = new FooClass { Data = "test" };
// Act
reflectionHelper.InvokeGenericMethod("BarMethod", barClass, parameter, typeof(IBarInterface<>));
// Assert
Assert.True(barClass.Data == "test");
}
[Fact]
public void InvokeGenericMethodByNotExistingMethodShouldThrowInvalidOperationException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
var parameter = new FooClass { Data = "test" };
// Assert
Assert.Throws<InvalidOperationException>(() => reflectionHelper.InvokeGenericMethod("FailMethod", barClass, parameter, typeof(IBarInterface<>)));
}
[Fact]
public void InvokeGenericMethodByInvalidInterfaceTypeShouldThrowInvalidOperationException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
var parameter = new FooClass { Data = "test" };
// Assert
Assert.Throws<InvalidOperationException>(() => reflectionHelper.InvokeGenericMethod("BarMethod", barClass, parameter, typeof(IBarInterface<string>)));
}
[Fact]
public void InvokeGenericMethodByNullOrWhitespaceNameShouldThrowArgumentNullException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
var parameter = new FooClass { Data = "test" };
// Assert
Assert.Throws<ArgumentNullException>(() => reflectionHelper.InvokeGenericMethod(string.Empty, barClass, parameter, typeof(IBarInterface<>)));
}
[Fact]
public void InvokeGenericMethodByNullObjShouldThrowArgumentNullException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var parameter = new FooClass { Data = "test" };
// Assert
Assert.Throws<ArgumentNullException>(() => reflectionHelper.InvokeGenericMethod("BarMethod", null, parameter, typeof(IBarInterface<>)));
}
[Fact]
public void InvokeGenericMethodByNullParameterShouldThrowArgumentNullException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
// Assert
Assert.Throws<ArgumentNullException>(() => reflectionHelper.InvokeGenericMethod("BarMethod", barClass, null, typeof(IBarInterface<>)));
}
[Fact]
public void InvokeGenericMethodByNullGenericInterfaceTypeShouldThrowArgumentNullException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
var barClass = new BarClass();
var parameter = new FooClass { Data = "test" };
// Assert
Assert.Throws<ArgumentNullException>(() => reflectionHelper.InvokeGenericMethod("BarMethod", barClass, parameter, null));
}
[Fact]
public void FilterObjectsByInterfaceShouldReturnFilteredObjects()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
// Act
var result = reflectionHelper.FilterObjectsByInterface(new List<object>
{
new FooClass(),
new BarClass()
}, typeof(IBarInterface<string>));
// Assert
Assert.True(result.Count() == 1);
}
[Fact]
public void FilterObjectsByInterfaceWithNonExistingObjectsShouldReturnEmptyList()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
// Act
var result = reflectionHelper.FilterObjectsByInterface(new List<object>
{
new BarClass()
}, typeof(IBarInterface<string>));
// Assert
Assert.True(!result.Any());
}
[Fact]
public void FilterObjectsByInterfaceWithNullObjectsShouldThrowArgumentNullException()
{
// Arrange
var reflectionHelper = GetReflectionHelper();
// Assert
Assert.Throws<ArgumentNullException>(() => reflectionHelper.FilterObjectsByInterface<string>(null, typeof(void)));
}
[Fact]
public void LoadAssembliesWithExceptionalAssemblyNameShouldIgnoreException()
{
// Arrange
// Set any nonexisting assembly name for get exception when load that.
_dependencyContextProxy.Setup(x => x.GetDefaultAssemblyNames())
.Returns(new List<AssemblyName> { new AssemblyName("AnyNotExistingAssemblyName11") });
// Act
var reflectionHelper = GetReflectionHelper();
// Assert
Assert.True(reflectionHelper != null);
}
private ReflectionHelper GetReflectionHelper()
{
return new ReflectionHelper(_dependencyContextProxy.Object);
}
public class FooClass : IBarInterface<string>
{
public string Data { get; set; }
}
public class BarClass
{
public string Data { get; set; }
public void BarMethod<T>(IBarInterface<T> param)
{
this.Data = param.Data;
}
}
public interface IBarInterface<T>
{
string Data { get; set; }
}
public interface IFooInterface<T>
{
}
public class FooWorker : IBarInterface<string>
{
public string Data { get; set; }
}
}
}
| |
// Copyright 2017 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 Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Ogc;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
namespace ArcGISRuntime.Samples.WmsServiceCatalog
{
[Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "WMS service catalog",
category: "Layers",
description: "Connect to a WMS service and show the available layers and sublayers. ",
instructions: "",
tags: new[] { "OGC", "WMS", "catalog", "web map service" })]
public class WmsServiceCatalog : Activity
{
// Create and hold reference to the used MapView
private MapView _myMapView;
// Hold a reference to the ListView
private ListView _myDisplayList;
// Hold the URL to the WMS service providing the US NOAA National Weather Service forecast weather chart
private readonly Uri _wmsUrl = new Uri("https://idpgis.ncep.noaa.gov/arcgis/services/NWS_Forecasts_Guidance_Warnings/natl_fcst_wx_chart/MapServer/WMSServer?request=GetCapabilities&service=WMS");
// Hold a list of LayerDisplayVM; this is the ViewModel
private readonly List<LayerDisplayVM> _viewModelList = new List<LayerDisplayVM>();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
Title = "WMS service catalog";
// Create the UI, setup the control references
CreateLayout();
// Initialize the map
Initialize();
}
private void CreateLayout()
{
// Create a new vertical layout for the app
LinearLayout layout = new LinearLayout(this) { Orientation = Orientation.Vertical };
// Configuration for having the mapview and webview fill the screen.
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent,
1.0f
);
// Create the list view
_myDisplayList = new ListView(this) { LayoutParameters = layoutParams };
// Create two help labels
TextView promptLabel = new TextView(this) { Text = "Select a layer" };
// Create the mapview.
_myMapView = new MapView(this) { LayoutParameters = layoutParams };
// Add the views to the layout
layout.AddView(promptLabel);
layout.AddView(_myMapView);
layout.AddView(_myDisplayList);
// Show the layout in the app
SetContentView(layout);
}
private async void Initialize()
{
// Apply an imagery basemap to the map
_myMapView.Map = new Map(BasemapStyle.ArcGISDarkGray);
// Create the WMS Service
WmsService service = new WmsService(_wmsUrl);
try
{
// Load the WMS Service
await service.LoadAsync();
// Get the service info (metadata) from the service.
WmsServiceInfo info = service.ServiceInfo;
// Get the list of layer infos.
foreach (var layerInfo in info.LayerInfos)
{
LayerDisplayVM.BuildLayerInfoList(new LayerDisplayVM(layerInfo, null), _viewModelList);
}
// Create an array adapter for the layer display
ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem, _viewModelList);
// Apply the adapter
_myDisplayList.Adapter = adapter;
// Subscribe to selection change notifications
_myDisplayList.ItemClick += _myDisplayList_ItemClick;
// Update the map display based on the viewModel
UpdateMapDisplay(_viewModelList);
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
/// <summary>
/// Updates the map with the latest layer selection
/// </summary>
private async void UpdateMapDisplay(List<LayerDisplayVM> displayList)
{
// Remove all existing layers
_myMapView.Map.OperationalLayers.Clear();
// Get a list of selected LayerInfos
List<WmsLayerInfo> selectedLayers = displayList.Where(vm => vm.IsEnabled).Select(vm => vm.Info).ToList();
// Return if list is empty
if (!selectedLayers.Any())
{
return;
}
// Create a new WmsLayer from the selected layers
WmsLayer myLayer = new WmsLayer(selectedLayers);
try
{
// Load the layer
await myLayer.LoadAsync();
// Zoom to the extent of the layer
_myMapView.SetViewpoint(new Viewpoint(myLayer.FullExtent));
// Add the layer to the map
_myMapView.Map.OperationalLayers.Add(myLayer);
}
catch (Exception e)
{
new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show();
}
}
/// <summary>
/// Takes action once a new layer selection is made
/// </summary>
private void _myDisplayList_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
// Clear existing selection
foreach (LayerDisplayVM item in _viewModelList)
{
item.Select(false);
}
// Update the selection
_viewModelList[e.Position].Select();
// Update the map
UpdateMapDisplay(_viewModelList);
}
}
/// <summary>
/// This is a ViewModel class for maintaining the state of a layer selection.
/// Typically, this would go in a separate file, but it is included here for clarity.
/// </summary>
public class LayerDisplayVM
{
public WmsLayerInfo Info { get; }
// True if layer is selected for display.
public bool IsEnabled { get; private set; }
// Keeps track of how much indentation should be added (to simulate a tree view in a list).
private int NestLevel
{
get
{
if (Parent == null)
{
return 0;
}
return Parent.NestLevel + 1;
}
}
private List<LayerDisplayVM> Children { get; set; }
private LayerDisplayVM Parent { get; }
public LayerDisplayVM(WmsLayerInfo info, LayerDisplayVM parent)
{
Info = info;
Parent = parent;
}
// Select this layer and all child layers.
public void Select(bool isSelected = true)
{
IsEnabled = isSelected;
if (Children == null)
{
return;
}
foreach (var child in Children)
{
child.Select(isSelected);
}
}
// Format with indentation to simulate a treeview.
public override string ToString()
{
return $"{new String(' ', NestLevel * 8)} {Info.Title}";
}
public static void BuildLayerInfoList(LayerDisplayVM root, IList<LayerDisplayVM> result)
{
// Add the root node to the result list.
result.Add(root);
// Initialize the child collection for the root.
root.Children = new List<LayerDisplayVM>();
// Recursively add sublayers.
foreach (WmsLayerInfo layer in root.Info.LayerInfos)
{
// Create the view model for the sublayer.
LayerDisplayVM layerVM = new LayerDisplayVM(layer, root);
// Add the sublayer to the root's sublayer collection.
root.Children.Add(layerVM);
// Recursively add children.
BuildLayerInfoList(layerVM, result);
}
}
}
}
| |
using System;
using System.IO;
using System.Text;
namespace MatterHackers.Agg.Image
{
public static class ImageTgaIO
{
// Header of a TGA file
public struct STargaHeader
{
public byte PostHeaderSkip;
public byte ColorMapType; // 0 = RGB, 1 = Palette
public byte ImageType; // 1 = Palette, 2 = RGB, 3 = mono, 9 = RLE Palette, 10 = RLE RGB, 11 RLE mono
public ushort ColorMapStart;
public ushort ColorMapLength;
public byte ColorMapBits;
public ushort XStart; // offsets the image would like to have (ignored)
public ushort YStart; // offsets the image would like to have (ignored)
public ushort Width;
public ushort Height;
public byte BPP; // bit depth of the image
public byte Descriptor;
public void BinaryWrite(BinaryWriter writerToWriteTo)
{
writerToWriteTo.Write(PostHeaderSkip);
writerToWriteTo.Write(ColorMapType);
writerToWriteTo.Write(ImageType);
writerToWriteTo.Write(ColorMapStart);
writerToWriteTo.Write(ColorMapLength);
writerToWriteTo.Write(ColorMapBits);
writerToWriteTo.Write(XStart);
writerToWriteTo.Write(YStart);
writerToWriteTo.Write(Width);
writerToWriteTo.Write(Height);
writerToWriteTo.Write(BPP);
writerToWriteTo.Write(Descriptor);
}
};
private const int TargaHeaderSize = 18;
private const int RGB_BLUE = 2;
private const int RGB_GREEN = 1;
private const int RGB_RED = 0;
private const int RGBA_ALPHA = 3;
// these are used during loading (only valid during load)
private static int TGABytesPerLine;
private static void Do24To8Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
throw new System.NotImplementedException();
#if false
int i;
if (Width)
{
i = 0;
Dest = &Dest[Height*Width];
do
{
if(p[RGB_RED] == 0 && p[RGB_GREEN] == 0 && p[RGB_BLUE] == 0)
{
Dest[i] = 0;
}
else
{
// no other color can map to color 0
Dest[i] =(byte) pStaticRemap->GetColorIndex(p[RGB_RED], p[RGB_GREEN], p[RGB_BLUE], 1);
}
p += 3;
} while (++i<Width);
}
#endif
}
private static void Do32To8Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
throw new System.NotImplementedException();
#if false
int i;
if (Width)
{
i = 0;
Dest = &Dest[Height*Width];
do
{
if(p[RGB_RED] == 0 && p[RGB_GREEN] == 0 && p[RGB_BLUE] == 0)
{
Dest[i] = 0;
}
else
{
// no other color can map to color 0
Dest[i] = (byte)pStaticRemap->GetColorIndex(p[RGB_RED], p[RGB_GREEN], p[RGB_BLUE], 1);
}
p += 4;
} while (++i < Width);
}
#endif
}
private static unsafe void Do24To24Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
if (Width > 0)
{
int destOffset = Height * Width * 3;
for (int i = 0; i < Width * 3; i++)
{
Dest[destOffset + i] = Source[SourceOffset + i];
}
}
}
private static unsafe void Do32To24Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
if (Width > 0)
{
int i = 0;
int destOffest = Height * Width * 3;
do
{
Dest[destOffest + i * 3 + RGB_BLUE] = Source[SourceOffset + RGB_BLUE];
Dest[destOffest + i * 3 + RGB_GREEN] = Source[SourceOffset + RGB_GREEN];
Dest[destOffest + i * 3 + RGB_RED] = Source[SourceOffset + RGB_RED];
SourceOffset += 4;
} while (++i < Width);
}
}
private static unsafe void Do24To32Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
if (Width > 0)
{
int i = 0;
int destOffest = Height * Width * 4;
do
{
Dest[destOffest + i * 4 + RGB_BLUE] = Source[SourceOffset + RGB_BLUE];
Dest[destOffest + i * 4 + RGB_GREEN] = Source[SourceOffset + RGB_GREEN];
Dest[destOffest + i * 4 + RGB_RED] = Source[SourceOffset + RGB_RED];
Dest[destOffest + i * 4 + 3] = 255;
SourceOffset += 3;
} while (++i < Width);
}
}
private static unsafe void Do32To32Bit(byte[] Dest, byte[] Source, int SourceOffset, int Width, int Height)
{
if (Width > 0)
{
int i = 0;
int destOffest = Height * Width * 4;
do
{
Dest[destOffest + RGB_BLUE] = Source[SourceOffset + RGB_BLUE];
Dest[destOffest + RGB_GREEN] = Source[SourceOffset + RGB_GREEN];
Dest[destOffest + RGB_RED] = Source[SourceOffset + RGB_RED];
Dest[destOffest + RGBA_ALPHA] = Source[SourceOffset + RGBA_ALPHA];
SourceOffset += 4;
destOffest += 4;
} while (++i < Width);
}
}
private static bool ReadTGAInfo(byte[] WorkPtr, out STargaHeader TargaHeader)
{
TargaHeader.PostHeaderSkip = WorkPtr[0];
TargaHeader.ColorMapType = WorkPtr[1];
TargaHeader.ImageType = WorkPtr[2];
TargaHeader.ColorMapStart = BitConverter.ToUInt16(WorkPtr, 3);
TargaHeader.ColorMapLength = BitConverter.ToUInt16(WorkPtr, 5);
TargaHeader.ColorMapBits = WorkPtr[7];
TargaHeader.XStart = BitConverter.ToUInt16(WorkPtr, 8);
TargaHeader.YStart = BitConverter.ToUInt16(WorkPtr, 10);
TargaHeader.Width = BitConverter.ToUInt16(WorkPtr, 12);
TargaHeader.Height = BitConverter.ToUInt16(WorkPtr, 14);
TargaHeader.BPP = WorkPtr[16];
TargaHeader.Descriptor = WorkPtr[17];
// check the header
if (TargaHeader.ColorMapType != 0 || // 0 = RGB, 1 = Palette
// 1 = Palette, 2 = RGB, 3 = mono, 9 = RLE Palette, 10 = RLE RGB, 11 RLE mono
(TargaHeader.ImageType != 2 && TargaHeader.ImageType != 10 && TargaHeader.ImageType != 9) ||
(TargaHeader.BPP != 24 && TargaHeader.BPP != 32))
{
#if DEBUG
throw new NotImplementedException("Unsupported TGA mode");
#endif
#if ASSERTS_ENABLED
if ( ((byte*)pTargaHeader)[0] == 'B' && ((byte*)pTargaHeader)[1] == 'M' )
{
assert(!"This TGA's header looks like a BMP!"); // look at the first two bytes and see if they are 'BM'
// if so it's a BMP not a TGA
}
else
{
byte * pColorMapType = NULL;
switch (TargaHeader.ColorMapType)
{
case 0:
pColorMapType = "RGB Color Map";
break;
case 1:
pColorMapType = "Palette Color Map";
break;
default:
pColorMapType = "<Illegal Color Map>";
break;
}
byte * pImageType = NULL;
switch (TargaHeader.ImageType)
{
case 1:
pImageType = "Palette Image Type";
break;
case 2:
pImageType = "RGB Image Type";
break;
case 3:
pImageType = "mono Image Type";
break;
case 9:
pImageType = "RLE Palette Image Type";
break;
case 10:
pImageType = "RLE RGB Image Type";
break;
case 11:
pImageType = "RLE mono Image Type";
break;
default:
pImageType = "<Illegal Image Type>";
break;
}
int ColorDepth = TargaHeader.BPP;
CJString ErrorString;
ErrorString.Format( "Image type %s %s (%u bpp) not supported!", pColorMapType, pImageType, ColorDepth);
ShowSystemMessage("TGA File IO Error", ErrorString.GetBytePtr(), "TGA Error");
}
#endif // ASSERTS_ENABLED
return false;
}
return true;
}
private const int IS_PIXLE_RUN = 0x80;
private const int RUN_LENGTH_MASK = 0x7f;
private static unsafe int Decompress(byte[] pDecompressBits, byte[] pBitsToPars, int ParsOffset, int Width, int Depth, int LineBeingRead)
{
int decompressOffset = 0;
int total = 0;
do
{
int i;
int numPixels = (pBitsToPars[ParsOffset] & RUN_LENGTH_MASK) + 1;
total += numPixels;
if ((pBitsToPars[ParsOffset++] & IS_PIXLE_RUN) != 0)
{
// decompress the run for NumPixels
byte r, g, b, a;
b = pBitsToPars[ParsOffset++];
g = pBitsToPars[ParsOffset++];
r = pBitsToPars[ParsOffset++];
switch (Depth)
{
case 24:
for (i = 0; i < numPixels; i++)
{
pDecompressBits[decompressOffset++] = b;
pDecompressBits[decompressOffset++] = g;
pDecompressBits[decompressOffset++] = r;
}
break;
case 32:
a = pBitsToPars[ParsOffset++];
for (i = 0; i < numPixels; i++)
{
pDecompressBits[decompressOffset++] = b;
pDecompressBits[decompressOffset++] = g;
pDecompressBits[decompressOffset++] = r;
pDecompressBits[decompressOffset++] = a;
}
break;
default:
throw new System.Exception("Bad bit depth.");
}
}
else // store NumPixels normally
{
switch (Depth)
{
case 24:
for (i = 0; i < numPixels * 3; i++)
{
pDecompressBits[decompressOffset++] = pBitsToPars[ParsOffset++];
}
break;
case 32:
for (i = 0; i < numPixels * 4; i++)
{
pDecompressBits[decompressOffset++] = pBitsToPars[ParsOffset++];
}
break;
default:
throw new System.Exception("Bad bit depth.");
}
}
} while (total < Width);
if (total > Width)
{
throw new System.Exception("The TGA you loaded is corrupt (line " + LineBeingRead.ToString() + ").");
}
return ParsOffset;
}
private static unsafe int LowLevelReadTGABitsFromBuffer(ImageBuffer imageToReadTo, byte[] wholeFileBuffer, int DestBitDepth)
{
STargaHeader targaHeader = new STargaHeader();
int fileReadOffset;
if (!ReadTGAInfo(wholeFileBuffer, out targaHeader))
{
return 0;
}
// if the frame we are loading is different then the one we have allocated
// or we don't have any bits allocated
if ((imageToReadTo.Width * imageToReadTo.Height) != (targaHeader.Width * targaHeader.Height))
{
imageToReadTo.Allocate(targaHeader.Width, targaHeader.Height, targaHeader.Width * DestBitDepth / 8, DestBitDepth);
}
// work out the line width
switch (imageToReadTo.BitDepth)
{
case 24:
TGABytesPerLine = imageToReadTo.Width * 3;
if (imageToReadTo.GetRecieveBlender() == null)
{
imageToReadTo.SetRecieveBlender(new BlenderBGR());
}
break;
case 32:
TGABytesPerLine = imageToReadTo.Width * 4;
if (imageToReadTo.GetRecieveBlender() == null)
{
imageToReadTo.SetRecieveBlender(new BlenderBGRA());
}
break;
default:
throw new System.Exception("Bad bit depth.");
}
if (TGABytesPerLine > 0)
{
byte[] bufferToDecompressTo = null;
fileReadOffset = TargaHeaderSize + targaHeader.PostHeaderSkip;
if (targaHeader.ImageType == 10) // 10 is RLE compressed
{
bufferToDecompressTo = new byte[TGABytesPerLine * 2];
}
// read all the lines *
for (int i = 0; i < imageToReadTo.Height; i++)
{
byte[] bufferToCopyFrom;
int copyOffset = 0;
int curReadLine;
// bit 5 tells us if the image is stored top to bottom or bottom to top
if ((targaHeader.Descriptor & 0x20) != 0)
{
// bottom to top
curReadLine = imageToReadTo.Height - i - 1;
}
else
{
// top to bottom
curReadLine = i;
}
if (targaHeader.ImageType == 10) // 10 is RLE compressed
{
fileReadOffset = Decompress(bufferToDecompressTo, wholeFileBuffer, fileReadOffset, imageToReadTo.Width, targaHeader.BPP, curReadLine);
bufferToCopyFrom = bufferToDecompressTo;
}
else
{
bufferToCopyFrom = wholeFileBuffer;
copyOffset = fileReadOffset;
}
int bufferOffset;
byte[] imageBuffer = imageToReadTo.GetBuffer(out bufferOffset);
switch (imageToReadTo.BitDepth)
{
case 8:
switch (targaHeader.BPP)
{
case 24:
Do24To8Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
case 32:
Do32To8Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
}
break;
case 24:
switch (targaHeader.BPP)
{
case 24:
Do24To24Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
case 32:
Do32To24Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
}
break;
case 32:
switch (targaHeader.BPP)
{
case 24:
Do24To32Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
case 32:
Do32To32Bit(imageBuffer, bufferToCopyFrom, copyOffset, imageToReadTo.Width, curReadLine);
break;
}
break;
default:
throw new System.Exception("Bad bit depth");
}
if (targaHeader.ImageType != 10) // 10 is RLE compressed
{
fileReadOffset += TGABytesPerLine;
}
}
}
return targaHeader.Width;
}
private const int MAX_RUN_LENGTH = 127;
private static int memcmp(byte[] pCheck, int CheckOffset, byte[] pSource, int SourceOffset, int Width)
{
for (int i = 0; i < Width; i++)
{
if (pCheck[CheckOffset + i] < pSource[SourceOffset + i])
{
return -1;
}
if (pCheck[CheckOffset + i] > pSource[SourceOffset + i])
{
return 1;
}
}
return 0;
}
private static int GetSameLength(byte[] checkBufer, int checkOffset, byte[] sourceBuffer, int sourceOffsetToNextPixel, int numBytesInPixel, int maxSameLengthWidth)
{
int count = 0;
while (memcmp(checkBufer, checkOffset, sourceBuffer, sourceOffsetToNextPixel, numBytesInPixel) == 0 && count < maxSameLengthWidth)
{
count++;
sourceOffsetToNextPixel += numBytesInPixel;
}
return count;
}
private static int GetDifLength(byte[] pCheck, byte[] pSource, int SourceOffset, int numBytesInPixel, int Max)
{
int count = 0;
while (memcmp(pCheck, 0, pSource, SourceOffset, numBytesInPixel) != 0 && count < Max)
{
count++;
for (int i = 0; i < numBytesInPixel; i++)
{
pCheck[i] = pSource[SourceOffset + i];
}
SourceOffset += numBytesInPixel;
}
return count;
}
private const int MIN_RUN_LENGTH = 2;
private static int CompressLine8(byte[] destBuffer, byte[] sourceBuffer, int sourceOffset, int Width)
{
int writePos = 0;
int pixelsProcessed = 0;
while (pixelsProcessed < Width)
{
// always get as many as you can that are the same first
int max = System.Math.Min(MAX_RUN_LENGTH, (Width - 1) - pixelsProcessed);
int sameLength = GetSameLength(sourceBuffer, sourceOffset, sourceBuffer, sourceOffset + 1, 1, max);
if (sameLength >= MIN_RUN_LENGTH)
//if(SameLength)
{
// write in the count
if (sameLength > MAX_RUN_LENGTH)
{
throw new System.Exception("Bad Length");
}
destBuffer[writePos++] = (byte)((sameLength) | IS_PIXLE_RUN);
// write in the same length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset];
pixelsProcessed += sameLength + 1;
}
else
{
byte checkPixel = sourceBuffer[sourceOffset];
int difLength = max;
if (difLength == 0)
{
difLength = 1;
}
// write in the count (if there is only one the count is 0)
if (difLength > MAX_RUN_LENGTH)
{
throw new System.Exception("Bad Length");
}
destBuffer[writePos++] = (byte)(difLength - 1);
while (difLength-- != 0)
{
// write in the same length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset++];
pixelsProcessed++;
}
}
}
return writePos;
}
private static byte[] differenceHold = new byte[4];
private static int CompressLine24(byte[] destBuffer, byte[] sourceBuffer, int sourceOffset, int Width)
{
int writePos = 0;
int pixelsProcessed = 0;
while (pixelsProcessed < Width)
{
// always get as many as you can that are the same first
int max = System.Math.Min(MAX_RUN_LENGTH, (Width - 1) - pixelsProcessed);
int sameLength = GetSameLength(sourceBuffer, sourceOffset, sourceBuffer, sourceOffset + 3, 3, max);
if (sameLength > 0)
{
// write in the count
if (sameLength > MAX_RUN_LENGTH)
{
throw new Exception();
}
destBuffer[writePos++] = (byte)((sameLength) | IS_PIXLE_RUN);
// write in the same length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset + 0];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 1];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 2];
sourceOffset += (sameLength) * 3;
pixelsProcessed += sameLength + 1;
}
else
{
differenceHold[0] = sourceBuffer[sourceOffset + 0];
differenceHold[1] = sourceBuffer[sourceOffset + 1];
differenceHold[2] = sourceBuffer[sourceOffset + 2];
int difLength = GetDifLength(differenceHold, sourceBuffer, sourceOffset + 3, 3, max);
if (difLength == 0)
{
difLength = 1;
}
// write in the count (if there is only one the count is 0)
if (sameLength > MAX_RUN_LENGTH)
{
throw new Exception();
}
destBuffer[writePos++] = (byte)(difLength - 1);
while (difLength-- > 0)
{
// write in the same length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset + 0];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 1];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 2];
sourceOffset += 3;
pixelsProcessed++;
}
}
}
return writePos;
}
private static int CompressLine32(byte[] destBuffer, byte[] sourceBuffer, int sourceOffset, int Width)
{
int writePos = 0;
int pixelsProcessed = 0;
while (pixelsProcessed < Width)
{
// always get as many as you can that are the same first
int max = System.Math.Min(MAX_RUN_LENGTH, (Width - 1) - pixelsProcessed);
int sameLength = GetSameLength(sourceBuffer, sourceOffset, sourceBuffer, sourceOffset + 4, 4, max);
if (sameLength > 0)
{
// write in the count
if (sameLength > MAX_RUN_LENGTH)
{
throw new Exception();
}
destBuffer[writePos++] = (byte)((sameLength) | IS_PIXLE_RUN);
// write in the same length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset + 0];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 1];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 2];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 3];
sourceOffset += (sameLength) * 4;
pixelsProcessed += sameLength + 1;
}
else
{
differenceHold[0] = sourceBuffer[sourceOffset + 0];
differenceHold[1] = sourceBuffer[sourceOffset + 1];
differenceHold[2] = sourceBuffer[sourceOffset + 2];
differenceHold[3] = sourceBuffer[sourceOffset + 3];
int difLength = GetDifLength(differenceHold, sourceBuffer, sourceOffset + 4, 4, max);
if (difLength == 0)
{
difLength = 1;
}
// write in the count (if there is only one the count is 0)
if (sameLength > MAX_RUN_LENGTH)
{
throw new Exception();
}
destBuffer[writePos++] = (byte)(difLength - 1);
while (difLength-- > 0)
{
// write in the dif length pixel value
destBuffer[writePos++] = sourceBuffer[sourceOffset + 0];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 1];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 2];
destBuffer[writePos++] = sourceBuffer[sourceOffset + 3];
sourceOffset += 4;
pixelsProcessed++;
}
}
}
return writePos;
/*
while(SourcePos < Width)
{
// always get as many as you can that are the same first
int Max = System.Math.Min(MAX_RUN_LENGTH, (Width - 1) - SourcePos);
int SameLength = GetSameLength((byte*)&pSource[SourcePos], (byte*)&pSource[SourcePos + 1], 4, Max);
if(SameLength)
{
// write in the count
assert(SameLength<= MAX_RUN_LENGTH);
pDest[WritePos++] = (byte)((SameLength) | IS_PIXLE_RUN);
// write in the same length pixel value
pDest[WritePos++] = pSource[SourcePos].Blue;
pDest[WritePos++] = pSource[SourcePos].Green;
pDest[WritePos++] = pSource[SourcePos].Red;
pDest[WritePos++] = pSource[SourcePos].Alpha;
SourcePos += SameLength + 1;
}
else
{
Pixel32 CheckPixel = pSource[SourcePos];
int DifLength = GetDifLength((byte*)&CheckPixel, (byte*)&pSource[SourcePos+1], 4, Max);
if(!DifLength)
{
DifLength = 1;
}
// write in the count (if there is only one the count is 0)
assert(DifLength <= MAX_RUN_LENGTH);
pDest[WritePos++] = (byte)(DifLength-1);
while(DifLength--)
{
// write in the same length pixel value
pDest[WritePos++] = pSource[SourcePos].Blue;
pDest[WritePos++] = pSource[SourcePos].Green;
pDest[WritePos++] = pSource[SourcePos].Red;
pDest[WritePos++] = pSource[SourcePos].Alpha;
SourcePos++;
}
}
}
return WritePos;
*/
}
static public bool SaveImageData(String fileNameToSaveTo, ImageBuffer image)
{
return Save(image, fileNameToSaveTo);
}
static public bool Save(ImageBuffer image, String fileNameToSaveTo)
{
using (Stream file = File.Open(fileNameToSaveTo, FileMode.Create))
{
return Save(image, file);
}
}
static public bool Save(ImageBuffer image, Stream streamToSaveImageDataTo)
{
STargaHeader targaHeader;
using (BinaryWriter writerToSaveTo = new BinaryWriter(streamToSaveImageDataTo, new ASCIIEncoding(), true))
{
int sourceDepth = image.BitDepth;
// make sure there is something to save before opening the file
if (image.Width <= 0 || image.Height <= 0)
{
return false;
}
// set up the header
targaHeader.PostHeaderSkip = 0; // no skip after the header
if (sourceDepth == 8)
{
targaHeader.ColorMapType = 1; // Color type is Palette
targaHeader.ImageType = 9; // 1 = Palette, 9 = RLE Palette
targaHeader.ColorMapStart = 0;
targaHeader.ColorMapLength = 256;
targaHeader.ColorMapBits = 24;
}
else
{
targaHeader.ColorMapType = 0; // Color type is RGB
#if WRITE_RLE_COMPRESSED
TargaHeader.ImageType = 10; // RLE RGB
#else
targaHeader.ImageType = 2; // RGB
#endif
targaHeader.ColorMapStart = 0;
targaHeader.ColorMapLength = 0;
targaHeader.ColorMapBits = 0;
}
targaHeader.XStart = 0;
targaHeader.YStart = 0;
targaHeader.Width = (ushort)image.Width;
targaHeader.Height = (ushort)image.Height;
targaHeader.BPP = (byte)sourceDepth;
targaHeader.Descriptor = 0; // all 8 bits are used for alpha
targaHeader.BinaryWrite(writerToSaveTo);
byte[] pLineBuffer = new byte[image.StrideInBytesAbs() * 2];
// int BytesToSave;
switch (sourceDepth)
{
case 8:
/*
if (image.HasPalette())
{
for(int i=0; i<256; i++)
{
TGAFile.Write(image.GetPaletteIfAllocated()->pPalette[i * RGB_SIZE + RGB_BLUE]);
TGAFile.Write(image.GetPaletteIfAllocated()->pPalette[i * RGB_SIZE + RGB_GREEN]);
TGAFile.Write(image.GetPaletteIfAllocated()->pPalette[i * RGB_SIZE + RGB_RED]);
}
}
else
*/
{
// there is no palette for this DIB but we should write something
for (int i = 0; i < 256; i++)
{
writerToSaveTo.Write((byte)i);
writerToSaveTo.Write((byte)i);
writerToSaveTo.Write((byte)i);
}
}
for (int i = 0; i < image.Height; i++)
{
int bufferOffset;
byte[] buffer = image.GetPixelPointerY(i, out bufferOffset);
#if WRITE_RLE_COMPRESSED
BytesToSave = CompressLine8(pLineBuffer, buffer, bufferOffset, image.Width());
writerToSaveTo.Write(pLineBuffer, 0, BytesToSave);
#else
writerToSaveTo.Write(buffer, bufferOffset, image.Width);
#endif
}
break;
case 24:
for (int i = 0; i < image.Height; i++)
{
int bufferOffset;
byte[] buffer = image.GetPixelPointerY(i, out bufferOffset);
#if WRITE_RLE_COMPRESSED
BytesToSave = CompressLine24(pLineBuffer, buffer, bufferOffset, image.Width());
writerToSaveTo.Write(pLineBuffer, 0, BytesToSave);
#else
writerToSaveTo.Write(buffer, bufferOffset, image.Width * 3);
#endif
}
break;
case 32:
for (int i = 0; i < image.Height; i++)
{
int bufferOffset;
byte[] buffer = image.GetPixelPointerY(i, out bufferOffset);
#if WRITE_RLE_COMPRESSED
BytesToSave = CompressLine32(pLineBuffer, buffer, bufferOffset, image.Width);
writerToSaveTo.Write(pLineBuffer, 0, BytesToSave);
#else
writerToSaveTo.Write(buffer, bufferOffset, image.Width * 4);
#endif
}
break;
default:
throw new NotSupportedException();
}
writerToSaveTo.Flush();
}
return true;
}
/*
bool SourceNeedsToBeResaved(String pFileName)
{
CFile TGAFile;
if(TGAFile.Open(pFileName, CFile::modeRead))
{
STargaHeader TargaHeader;
byte[] pWorkPtr = new byte[sizeof(STargaHeader)];
TGAFile.Read(pWorkPtr, sizeof(STargaHeader));
TGAFile.Close();
if(ReadTGAInfo(pWorkPtr, &TargaHeader))
{
ArrayDeleteAndSetNull(pWorkPtr);
return TargaHeader.ImageType != 10;
}
ArrayDeleteAndSetNull(pWorkPtr);
}
return true;
}
*/
static public int ReadBitsFromBuffer(ImageBuffer image, byte[] WorkPtr, int destBitDepth)
{
return LowLevelReadTGABitsFromBuffer(image, WorkPtr, destBitDepth);
}
static public bool LoadImageData(ImageBuffer image, string fileName)
{
if (System.IO.File.Exists(fileName))
{
using (var stream = File.OpenRead(fileName))
{
return LoadImageData(image, stream, 32);
}
}
return false;
}
static public bool LoadImageData(ImageBuffer image, Stream streamToLoadImageDataFrom, int destBitDepth)
{
byte[] imageData = new byte[streamToLoadImageDataFrom.Length];
streamToLoadImageDataFrom.Read(imageData, 0, (int)streamToLoadImageDataFrom.Length);
return ReadBitsFromBuffer(image, imageData, destBitDepth) > 0;
}
static public int GetBitDepth(Stream streamToReadFrom)
{
STargaHeader targaHeader;
byte[] imageData = new byte[streamToReadFrom.Length];
streamToReadFrom.Read(imageData, 0, (int)streamToReadFrom.Length);
if (ReadTGAInfo(imageData, out targaHeader))
{
return targaHeader.BPP;
}
return 0;
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// 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 -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
#if !NETFX_35 && !UNITY && !WINDOWS_PHONE
using System.Collections.Concurrent;
#endif // !NETFX_35 && !UNITY && !WINDOWS_PHONE
using System.Collections.Generic;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
namespace MsgPack.Serialization
{
/// <summary>
/// Holds debugging support information.
/// </summary>
internal static class SerializerDebugging
{
#if !XAMIOS && !XAMDROID && !UNITY
[ThreadStatic]
private static bool _traceEnabled;
/// <summary>
/// Gets or sets a value indicating whether instruction/expression tracing is enabled or not.
/// </summary>
/// <value>
/// <c>true</c> if instruction/expression tracing is enabled; otherwise, <c>false</c>.
/// </value>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static bool TraceEnabled
{
get { return _traceEnabled; }
set { _traceEnabled = value; }
}
[ThreadStatic]
private static bool _dumpEnabled;
/// <summary>
/// Gets or sets a value indicating whether IL dump is enabled or not.
/// </summary>
/// <value>
/// <c>true</c> if IL dump is enabled; otherwise, <c>false</c>.
/// </value>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static bool DumpEnabled
{
get { return _dumpEnabled; }
set { _dumpEnabled = value; }
}
#endif // !XAMIOS && !XAMDROID && !UNITY
[ThreadStatic]
private static bool _avoidsGenericSerializer;
/// <summary>
/// Gets or sets a value indicating whether generic serializer for array, <see cref="List{T}"/>, <see cref="Dictionary{TKey,TValue}"/>,
/// or <see cref="Nullable{T}"/> is not used.
/// </summary>
/// <value>
/// <c>true</c> if generic serializer is not used; otherwise, <c>false</c>.
/// </value>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static bool AvoidsGenericSerializer
{
get { return _avoidsGenericSerializer; }
set { _avoidsGenericSerializer = value; }
}
#if !XAMIOS && !XAMDROID && !UNITY
#if !NETFX_CORE
[ThreadStatic]
private static StringWriter _ilTraceWriter;
#endif // !NETFX_CORE
/// <summary>
/// Gets the <see cref="TextWriter"/> for IL tracing.
/// </summary>
/// <value>
/// The <see cref="TextWriter"/> for IL tracing.
/// This value will not be <c>null</c>.
/// </value>
public static TextWriter ILTraceWriter
{
get
{
#if !NETFX_CORE
if ( !_traceEnabled )
{
return TextWriter.Null;
}
if ( _ilTraceWriter == null )
{
_ilTraceWriter = new StringWriter( CultureInfo.InvariantCulture );
}
return _ilTraceWriter;
#else
return TextWriter.Null;
#endif // !NETFX_CORE
}
}
/// <summary>
/// Traces the specific event.
/// </summary>
/// <param name="format">The format string.</param>
/// <param name="args">The args for formatting.</param>
#if NETFX_CORE || WINDOWS_PHONE
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "format", Justification = "Used in other platforms" )]
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args", Justification = "Used in other platforms" )]
#endif // NETFX_CORE || WINDOWS_PHONE
public static void TraceEvent( string format, params object[] args )
{
#if !NETFX_CORE && !WINDOWS_PHONE
if ( !_traceEnabled )
{
return;
}
Tracer.Emit.TraceEvent( Tracer.EventType.DefineType, Tracer.EventId.DefineType, format, args );
#endif // !NETFX_CORE && !WINDOWS_PHONE
}
/// <summary>
/// Flushes the trace data.
/// </summary>
public static void FlushTraceData()
{
#if !NETFX_CORE && !WINDOWS_PHONE
if ( !_traceEnabled )
{
return;
}
Tracer.Emit.TraceData( Tracer.EventType.DefineType, Tracer.EventId.DefineType, _ilTraceWriter.ToString() );
#endif // !NETFX_CORE && !WINDOWS_PHONE
}
#if !NETFX_CORE && !SILVERLIGHT && !NETFX_35
[ThreadStatic]
private static AssemblyBuilder _assemblyBuilder;
[ThreadStatic]
private static ModuleBuilder _moduleBuilder;
/// <summary>
/// Prepares instruction dump with specified <see cref="AssemblyBuilder"/>.
/// </summary>
/// <param name="assemblyBuilder">The assembly builder to hold instructions.</param>
public static void PrepareDump( AssemblyBuilder assemblyBuilder )
{
if ( _dumpEnabled )
{
#if DEBUG
Contract.Assert( assemblyBuilder != null );
#endif // DEBUG
_assemblyBuilder = assemblyBuilder;
}
}
/// <summary>
/// Prepares the dump with dedicated internal <see cref="AssemblyBuilder"/>.
/// </summary>
public static void PrepareDump()
{
_assemblyBuilder =
AppDomain.CurrentDomain.DefineDynamicAssembly(
new AssemblyName( "ExpressionTreeSerializerLogics" ),
AssemblyBuilderAccess.Save,
default( IEnumerable<CustomAttributeBuilder> )
);
_moduleBuilder =
_assemblyBuilder.DefineDynamicModule( "ExpressionTreeSerializerLogics", "ExpressionTreeSerializerLogics.dll", true );
}
#endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35
// TODO: Cleanup %Temp% to delete temp assemblies generated for on the fly code DOM.
#if !NETFX_CORE && !SILVERLIGHT
[ThreadStatic]
private static IList<string> _runtimeAssemblies;
[ThreadStatic]
private static IList<string> _compiledCodeDomSerializerAssemblies;
public static IEnumerable<string> CodeDomSerializerDependentAssemblies
{
get
{
EnsureDependentAssembliesListsInitialized();
#if DEBUG
Contract.Assert( _compiledCodeDomSerializerAssemblies != null );
#endif // DEBUG
// FCL dependencies and msgpack core libs
foreach ( var runtimeAssembly in _runtimeAssemblies )
{
yield return runtimeAssembly;
}
// dependents
foreach ( var compiledAssembly in _compiledCodeDomSerializerAssemblies )
{
yield return compiledAssembly;
}
}
}
#endif // !NETFX_CORE && !SILVERLIGHT
#if NETFX_CORE || SILVERLIGHT
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )]
#endif // NETFX_CORE || SILVERLIGHT
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static void AddRuntimeAssembly( string pathToAssembly )
{
#if !NETFX_CORE && !SILVERLIGHT
EnsureDependentAssembliesListsInitialized();
_runtimeAssemblies.Add( pathToAssembly );
#endif // !NETFX_CORE && !SILVERLIGHT
}
#if NETFX_CORE || SILVERLIGHT
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "pathToAssembly", Justification = "For API compatibility" )]
#endif // NETFX_CORE || SILVERLIGHT
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static void AddCompiledCodeDomAssembly( string pathToAssembly )
{
#if !NETFX_CORE && !SILVERLIGHT
EnsureDependentAssembliesListsInitialized();
_compiledCodeDomSerializerAssemblies.Add( pathToAssembly );
#endif // !NETFX_CORE && !SILVERLIGHT
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static void ResetDependentAssemblies()
{
#if !NETFX_CORE && !SILVERLIGHT
EnsureDependentAssembliesListsInitialized();
#if !NETFX_35
File.AppendAllLines( GetHistoryFilePath(), _compiledCodeDomSerializerAssemblies );
#else
File.AppendAllText( GetHistoryFilePath(), String.Join( Environment.NewLine, _compiledCodeDomSerializerAssemblies.ToArray() ) + Environment.NewLine );
#endif // !NETFX_35
_compiledCodeDomSerializerAssemblies.Clear();
ResetRuntimeAssemblies();
#endif // !NETFX_CORE && !SILVERLIGHT
}
#if !NETFX_CORE && !SILVERLIGHT
private static int _wasDeleted;
private const string HistoryFile = "MsgPack.Serialization.SerializationGenerationDebugging.CodeDOM.History.txt";
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")]
public static void DeletePastTemporaries()
{
if ( Interlocked.CompareExchange( ref _wasDeleted, 1, 0 ) != 0 )
{
return;
}
try
{
var historyFilePath = GetHistoryFilePath();
if ( !File.Exists( historyFilePath ) )
{
return;
}
foreach ( var pastAssembly in File.ReadAllLines( historyFilePath ) )
{
if ( !String.IsNullOrEmpty( pastAssembly ) )
{
File.Delete( pastAssembly );
}
}
new FileStream( historyFilePath, FileMode.Truncate ).Close();
}
catch ( IOException ) { }
}
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")]
private static string GetHistoryFilePath()
{
return Path.Combine( Path.GetTempPath(), HistoryFile );
}
private static void EnsureDependentAssembliesListsInitialized()
{
if ( _runtimeAssemblies == null )
{
_runtimeAssemblies = new List<string>();
ResetRuntimeAssemblies();
}
if ( _compiledCodeDomSerializerAssemblies == null )
{
_compiledCodeDomSerializerAssemblies = new List<string>();
}
}
private static void ResetRuntimeAssemblies()
{
_runtimeAssemblies.Add( "System.dll" );
#if NETFX_35
_runtimeAssemblies.Add( typeof( Enumerable ).Assembly.Location );
#else
_runtimeAssemblies.Add( "System.Core.dll" );
_runtimeAssemblies.Add( "System.Numerics.dll" );
#endif // NETFX_35
_runtimeAssemblies.Add( typeof( SerializerDebugging ).Assembly.Location );
}
#endif // !NETFX_CORE && !SILVERLIGHT
[ThreadStatic]
private static bool _onTheFlyCodeDomEnabled;
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static bool OnTheFlyCodeDomEnabled
{
get { return _onTheFlyCodeDomEnabled; }
set { _onTheFlyCodeDomEnabled = value; }
}
#if !NETFX_CORE && !SILVERLIGHT && !NETFX_35
/// <summary>
/// Creates the new type builder for the serializer.
/// </summary>
/// <param name="targetType">The serialization target type.</param>
/// <returns></returns>
/// <exception cref="System.InvalidOperationException">PrepareDump() was not called.</exception>
public static TypeBuilder NewTypeBuilder( Type targetType )
{
if ( _moduleBuilder == null )
{
throw new InvalidOperationException( "PrepareDump() was not called." );
}
return
_moduleBuilder.DefineType( IdentifierUtility.EscapeTypeName( targetType ) + "SerializerLogics" );
}
#endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35
#if !NETFX_CORE && !SILVERLIGHT
/// <summary>
/// Takes dump of instructions.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode" , Justification = "For unit testing")]
public static void Dump()
{
#if !NETFX_35
if ( _assemblyBuilder != null )
{
_assemblyBuilder.Save( _assemblyBuilder.GetName().Name + ".dll" );
}
#endif // !NETFX_35
}
#endif // !NETFX_CORE && !SILVERLIGHT
/// <summary>
/// Resets debugging states.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "For unit testing" )]
public static void Reset()
{
#if !NETFX_CORE && !SILVERLIGHT && !NETFX_35
_assemblyBuilder = null;
_moduleBuilder = null;
if ( _ilTraceWriter != null )
{
_ilTraceWriter.Dispose();
_ilTraceWriter = null;
}
#endif // !NETFX_CORE && !SILVERLIGHT && !NETFX_35
_dumpEnabled = false;
_traceEnabled = false;
ResetDependentAssemblies();
}
#endif // !XAMIOS && !XAMDROID && !UNITY
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UnsafeNativeMethods.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.Data.Odbc;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
namespace System.Data.Common {
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods {
//
// ODBC32
//
[DllImport(ExternDll.Odbc32)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/IntPtr InputHandle,
/*SQLHANDLE* */out IntPtr OutputHandle);
[DllImport(ExternDll.Odbc32)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLAllocHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/OdbcHandle InputHandle,
/*SQLHANDLE* */out IntPtr OutputHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/HandleRef TargetValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */IntPtr StrLen_or_Ind);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLBindCol(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/IntPtr TargetValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */IntPtr StrLen_or_Ind);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLBindParameter(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ParameterNumber,
/*SQLSMALLINT*/Int16 ParamDirection,
/*SQLSMALLINT*/ODBC32.SQL_C SQLCType,
/*SQLSMALLINT*/Int16 SQLType,
/*SQLULEN*/IntPtr cbColDef,
/*SQLSMALLINT*/IntPtr ibScale,
/*SQLPOINTER*/HandleRef rgbValue,
/*SQLLEN*/IntPtr BufferLength,
/*SQLLEN* */HandleRef StrLen_or_Ind);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLCancel(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLCloseCursor(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLColAttributeW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/Int16 ColumnNumber,
/*SQLUSMALLINT*/Int16 FieldIdentifier,
/*SQLPOINTER*/CNativeBuffer CharacterAttribute,
/*SQLSMALLINT*/Int16 BufferLength,
/*SQLSMALLINT* */out Int16 StringLength,
/*SQLPOINTER*/out IntPtr NumericAttribute);
// note: in sql.h this is defined differently for the 64Bit platform.
// However, for us the code is not different for SQLPOINTER or SQLLEN ...
// frome sql.h:
// #ifdef _WIN64
// SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,
// SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier,
// SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength,
// SQLSMALLINT *StringLength, SQLLEN *NumericAttribute);
// #else
// SQLRETURN SQL_API SQLColAttribute (SQLHSTMT StatementHandle,
// SQLUSMALLINT ColumnNumber, SQLUSMALLINT FieldIdentifier,
// SQLPOINTER CharacterAttribute, SQLSMALLINT BufferLength,
// SQLSMALLINT *StringLength, SQLPOINTER NumericAttribute);
// #endif
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLColumnsW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string ColumnName,
/*SQLSMALLINT*/Int16 NameLen4);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLDisconnect(
/*SQLHDBC*/IntPtr ConnectionHandle);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLDriverConnectW(
/*SQLHDBC*/OdbcConnectionHandle hdbc,
/*SQLHWND*/IntPtr hwnd,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string connectionstring,
/*SQLSMALLINT*/Int16 cbConnectionstring,
/*SQLCHAR* */IntPtr connectionstringout,
/*SQLSMALLINT*/Int16 cbConnectionstringoutMax,
/*SQLSMALLINT* */out Int16 cbConnectionstringout,
/*SQLUSMALLINT*/Int16 fDriverCompletion);
[DllImport(ExternDll.Odbc32)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLEndTran(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/IntPtr Handle,
/*SQLSMALLINT*/Int16 CompletionType);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLExecDirectW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string StatementText,
/*SQLINTEGER*/Int32 TextLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLExecute(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLFetch(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLFreeHandle(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHSTMT*/IntPtr StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLFreeStmt(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/ODBC32.STMT Option);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/byte[] Value,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER* */out Int32 StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetData(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/UInt16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_C TargetType,
/*SQLPOINTER*/CNativeBuffer TargetValue,
/*SQLLEN*/IntPtr BufferLength, // sql.h differs from MSDN
/*SQLLEN* */out IntPtr StrLen_or_Ind);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetDescFieldW (
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLUSMALLINT*/Int16 RecNumber,
/*SQLUSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/CNativeBuffer ValuePointer,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER* */out Int32 StringLength);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagRecW(
/*SQLSMALLINT*/ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/OdbcHandle Handle,
/*SQLSMALLINT*/Int16 RecNumber,
/*SQLCHAR* */ StringBuilder rchState,
/*SQLINTEGER* */out Int32 NativeError,
/*SQLCHAR* */StringBuilder MessageText,
/*SQLSMALLINT*/Int16 BufferLength,
/*SQLSMALLINT* */out Int16 TextLength);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetDiagFieldW(
/*SQLSMALLINT*/ ODBC32.SQL_HANDLE HandleType,
/*SQLHANDLE*/ OdbcHandle Handle,
/*SQLSMALLINT*/ Int16 RecNumber,
/*SQLSMALLINT*/ Int16 DiagIdentifier,
[MarshalAs(UnmanagedType.LPWStr)]
/*SQLPOINTER*/ StringBuilder rchState,
/*SQLSMALLINT*/ Int16 BufferLength,
/*SQLSMALLINT* */ out Int16 StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetFunctions(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_API fFunction,
/*SQLUSMALLINT* */out Int16 pfExists);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType,
/*SQLPOINTER*/byte[] rgbInfoValue,
/*SQLSMALLINT*/Int16 cbInfoValueMax,
/*SQLSMALLINT* */out Int16 pcbInfoValue);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetInfoW(
/*SQLHBDC*/OdbcConnectionHandle hdbc,
/*SQLUSMALLINT*/ODBC32.SQL_INFO fInfoType,
/*SQLPOINTER*/byte[] rgbInfoValue,
/*SQLSMALLINT*/Int16 cbInfoValueMax,
/*SQLSMALLINT* */IntPtr pcbInfoValue);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetStmtAttrW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/out IntPtr Value,
/*SQLINTEGER*/Int32 BufferLength,
/*SQLINTEGER*/out Int32 StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLGetTypeInfo(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLSMALLINT*/Int16 fSqlType);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLMoreResults(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLNumResultCols(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLSMALLINT* */out Int16 ColumnCount);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLPrepareW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string StatementText,
/*SQLINTEGER*/Int32 TextLength);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLPrimaryKeysW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLProcedureColumnsW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ProcName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ColumnName,
/*SQLSMALLINT*/Int16 NameLen4);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLProceduresW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)] /*SQLCHAR* */ string ProcName,
/*SQLSMALLINT*/Int16 NameLen3);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLRowCount(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLLEN* */out IntPtr RowCount);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/System.Transactions.IDtcTransaction Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/string Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW(
/*SQLHBDC*/OdbcConnectionHandle ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(ExternDll.Odbc32)]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetConnectAttrW( // used only for AutoCommitOn
/*SQLHBDC*/IntPtr ConnectionHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW (
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLSMALLINT*/Int16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/HandleRef CharacterAttribute,
/*SQLINTEGER*/Int32 BufferLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetDescFieldW (
/*SQLHSTMT*/OdbcDescriptorHandle StatementHandle,
/*SQLSMALLINT*/Int16 ColumnNumber,
/*SQLSMALLINT*/ODBC32.SQL_DESC FieldIdentifier,
/*SQLPOINTER*/IntPtr CharacterAttribute,
/*SQLINTEGER*/Int32 BufferLength);
[DllImport(ExternDll.Odbc32)]
// user can set SQL_ATTR_CONNECTION_POOLING attribute with envHandle = null, this attribute is process-level attribute
[ResourceExposure(ResourceScope.Process)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetEnvAttr(
/*SQLHENV*/OdbcEnvironmentHandle EnvironmentHandle,
/*SQLINTEGER*/ODBC32.SQL_ATTR Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/ODBC32.SQL_IS StringLength);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSetStmtAttrW(
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLINTEGER*/Int32 Attribute,
/*SQLPOINTER*/IntPtr Value,
/*SQLINTEGER*/Int32 StringLength);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLSpecialColumnsW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
/*SQLUSMALLINT*/ODBC32.SQL_SPECIALCOLS IdentifierType,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
/*SQLUSMALLINT*/ODBC32.SQL_SCOPE Scope,
/*SQLUSMALLINT*/ ODBC32.SQL_NULLABILITY Nullable);
[DllImport(ExternDll.Odbc32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLStatisticsW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
/*SQLUSMALLINT*/Int16 Unique,
/*SQLUSMALLINT*/Int16 Reserved);
[DllImport(ExternDll.Odbc32)]
[ResourceExposure(ResourceScope.None)]
static internal extern /*SQLRETURN*/ODBC32.RetCode SQLTablesW (
/*SQLHSTMT*/OdbcStatementHandle StatementHandle,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string CatalogName,
/*SQLSMALLINT*/Int16 NameLen1,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string SchemaName,
/*SQLSMALLINT*/Int16 NameLen2,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableName,
/*SQLSMALLINT*/Int16 NameLen3,
[In, MarshalAs(UnmanagedType.LPWStr)]
/*SQLCHAR* */string TableType,
/*SQLSMALLINT*/Int16 NameLen4);
//
// Oleaut32
//
[DllImport(ExternDll.Oleaut32, CharSet=CharSet.Unicode, PreserveSig=true)]
[ResourceExposure(ResourceScope.None)]
static internal extern System.Data.OleDb.OleDbHResult GetErrorInfo(
[In] Int32 dwReserved,
[Out, MarshalAs(UnmanagedType.Interface)] out IErrorInfo ppIErrorInfo);
[Guid("00000567-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ADORecordConstruction {
[return:MarshalAs(UnmanagedType.Interface)] object get_Row ();
//void put_Row(
// [In, MarshalAs(UnmanagedType.Interface)] object pRow);
//void put_ParentRow(
// [In, MarshalAs(UnmanagedType.Interface)]object pRow);
}
[Guid("00000283-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ADORecordsetConstruction {
[return:MarshalAs(UnmanagedType.Interface)] object get_Rowset();
[ Obsolete("not used", true)] void put_Rowset (/*deleted parameters signature*/);
/*[return:MarshalAs(UnmanagedType.SysInt)]*/ IntPtr get_Chapter();
//[[PreserveSig]
//iint put_Chapter (
// [In]
// IntPtr pcRefCount);
//[[PreserveSig]
//iint get_RowPosition (
// [Out, MarshalAs(UnmanagedType.Interface)]
// out object ppRowPos);
//[[PreserveSig]
//iint put_RowPosition (
// [In, MarshalAs(UnmanagedType.Interface)]
// object pRowPos);
}
[Guid("0000050E-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
internal interface Recordset15 {
[ Obsolete("not used", true)] void get_Properties(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_AbsolutePosition(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_AbsolutePosition(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void putref_ActiveConnection(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_ActiveConnection(/*deleted parameters signature*/);
/*[return:MarshalAs(UnmanagedType.Variant)]*/object get_ActiveConnection();
[ Obsolete("not used", true)] void get_BOF(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Bookmark(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Bookmark(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_CacheSize(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_CacheSize(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_CursorType(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_CursorType(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_EOF(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Fields(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_LockType(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_LockType(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_MaxRecords(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_MaxRecords(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_RecordCount(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void putref_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void AddNew(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void CancelUpdate(/*deleted parameters signature*/);
[PreserveSig] System.Data.OleDb.OleDbHResult Close();
[ Obsolete("not used", true)] void Delete(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void GetRows(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void Move(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void MoveNext();
[ Obsolete("not used", true)] void MovePrevious();
[ Obsolete("not used", true)] void MoveFirst();
[ Obsolete("not used", true)] void MoveLast();
[ Obsolete("not used", true)] void Open(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void Requery(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void _xResync(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void Update(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_AbsolutePage(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_AbsolutePage(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_EditMode(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Filter(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Filter(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_PageCount(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_PageSize(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_PageSize(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Sort(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Sort(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Status(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_State(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void _xClone(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void UpdateBatch(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void CancelBatch(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_CursorLocation(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_CursorLocation(/*deleted parameters signature*/);
[PreserveSig] System.Data.OleDb.OleDbHResult NextRecordset(
[Out]out object RecordsAffected,
[Out, MarshalAs(UnmanagedType.Interface)] out object ppiRs);
//[ Obsolete("not used", true)] void Supports(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void get_Collect(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void put_Collect(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void get_MarshalOptions(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void put_MarshalOptions(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void Find(/*deleted parameters signature*/);
}
[Guid("00000562-0000-0010-8000-00AA006D2EA4"), InterfaceType(ComInterfaceType.InterfaceIsDual), ComImport, SuppressUnmanagedCodeSecurity]
internal interface _ADORecord {
[ Obsolete("not used", true)] void get_Properties(/*deleted parameters signature*/);
/*[return:MarshalAs(UnmanagedType.Variant)]*/object get_ActiveConnection();
[ Obsolete("not used", true)] void put_ActiveConnection(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void putref_ActiveConnection(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_State(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void putref_Source(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_Mode(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void put_Mode(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void get_ParentURL(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void MoveRecord(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void CopyRecord(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void DeleteRecord(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void Open(/*deleted parameters signature*/);
[PreserveSig] System.Data.OleDb.OleDbHResult Close();
//[ Obsolete("not used", true)] void get_Fields(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void get_RecordType(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void GetChildren(/*deleted parameters signature*/);
//[ Obsolete("not used", true)] void Cancel();
}
/*
typedef ULONGLONG DBLENGTH;
// Offset within a rowset
typedef LONGLONG DBROWOFFSET;
// Number of rows
typedef LONGLONG DBROWCOUNT;
typedef ULONGLONG DBCOUNTITEM;
// Ordinal (column number, etc.)
typedef ULONGLONG DBORDINAL;
typedef LONGLONG DB_LORDINAL;
// Bookmarks
typedef ULONGLONG DBBKMARK;
// Offset in the buffer
typedef ULONGLONG DBBYTEOFFSET;
// Reference count of each row/accessor handle
typedef ULONG DBREFCOUNT;
// Parameters
typedef ULONGLONG DB_UPARAMS;
typedef LONGLONG DB_LPARAMS;
// hash values corresponding to the elements (bookmarks)
typedef DWORDLONG DBHASHVALUE;
// For reserve
typedef DWORDLONG DB_DWRESERVE;
typedef LONGLONG DB_LRESERVE;
typedef ULONGLONG DB_URESERVE;
*/
[ComImport, Guid("0C733A8C-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), SuppressUnmanagedCodeSecurity]
internal interface IAccessor {
[ Obsolete("not used", true)] void AddRefAccessor(/*deleted parameters signature*/);
/*[local]
HRESULT CreateAccessor(
[in] DBACCESSORFLAGS dwAccessorFlags,
[in] DBCOUNTITEM cBindings,
[in, size_is(cBindings)] const DBBINDING rgBindings[],
[in] DBLENGTH cbRowSize,
[out] HACCESSOR * phAccessor,
[out, size_is(cBindings)] DBBINDSTATUS rgStatus[]
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult CreateAccessor(
[In] int dwAccessorFlags,
[In] IntPtr cBindings,
[In] /*tagDBBINDING[]*/SafeHandle rgBindings,
[In] IntPtr cbRowSize,
[Out] out IntPtr phAccessor,
[In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I4)] int[] rgStatus);
[ Obsolete("not used", true)] void GetBindings(/*deleted parameters signature*/);
/*[local]
HRESULT ReleaseAccessor(
[in] HACCESSOR hAccessor,
[in, out, unique] DBREFCOUNT * pcRefCount
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult ReleaseAccessor(
[In] IntPtr hAccessor,
[Out] out int pcRefCount);
}
[Guid("0C733A93-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IChapteredRowset {
[ Obsolete("not used", true)] void AddRefChapter(/*deleted parameters signature*/);
/*[local]
HRESULT ReleaseChapter(
[in] HCHAPTER hChapter,
[out] DBREFCOUNT * pcRefCount
);*/
[PreserveSig, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] System.Data.OleDb.OleDbHResult ReleaseChapter(
[In] IntPtr hChapter,
[Out] out int pcRefCount);
}
[Guid("0C733A11-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IColumnsInfo {
/*[local]
HRESULT GetColumnInfo(
[in, out] DBORDINAL * pcColumns,
[out, size_is(,(ULONG)*pcColumns)] DBCOLUMNINFO ** prgInfo,
[out] OLECHAR ** ppStringsBuffer
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetColumnInfo(
[Out] out IntPtr pcColumns,
[Out] out IntPtr prgInfo,
[Out] out IntPtr ppStringsBuffer);
//[PreserveSig]
//int MapColumnIDs(/* deleted parameters*/);
}
[Guid("0C733A10-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IColumnsRowset {
/*[local]
HRESULT GetAvailableColumns(
[in, out] DBORDINAL * pcOptColumns,
[out, size_is(,(ULONG)*pcOptColumns)] DBID ** prgOptColumns
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetAvailableColumns(
[Out] out IntPtr pcOptColumns,
[Out] out IntPtr prgOptColumns);
/*[local]
HRESULT GetColumnsRowset(
[in] IUnknown * pUnkOuter,
[in] DBORDINAL cOptColumns,
[in, size_is((ULONG)cOptColumns)] const DBID rgOptColumns[],
[in] REFIID riid,
[in] ULONG cPropertySets,
[in, out, size_is((ULONG)cPropertySets)] DBPROPSET rgPropertySets[],
[out, iid_is(riid)] IUnknown ** ppColRowset
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetColumnsRowset(
[In] IntPtr pUnkOuter,
[In] IntPtr cOptColumns,
[In] SafeHandle rgOptColumns,
[In] ref Guid riid,
[In] int cPropertySets,
[In] IntPtr rgPropertySets,
[Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppColRowset);
}
[Guid("0C733A26-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ICommandPrepare {
/*[local]
HRESULT Prepare(
[in] ULONG cExpectedRuns
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult Prepare(
[In] int cExpectedRuns);
//[PreserveSig]
//int Unprepare();
}
[Guid("0C733A79-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ICommandProperties {
/*[local]
HRESULT GetProperties(
[in] const ULONG cPropertyIDSets,
[in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[],
[in, out] ULONG * pcPropertySets,
[out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
[In] SafeHandle rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
/*[local]
HRESULT SetProperties(
[in] ULONG cPropertySets,
[in, out, unique, size_is(cPropertySets)] DBPROPSET rgPropertySets[]
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult SetProperties(
[In] int cPropertySets,
[In] SafeHandle rgPropertySets);
}
[Guid("0C733A27-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ICommandText {
/*[local]
HRESULT Cancel(
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult Cancel();
/*[local]
HRESULT Execute(
[in] IUnknown * pUnkOuter,
[in] REFIID riid,
[in, out] DBPARAMS * pParams,
[out] DBROWCOUNT * pcRowsAffected,
[out, iid_is(riid)] IUnknown ** ppRowset
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult Execute(
[In] IntPtr pUnkOuter,
[In] ref Guid riid,
[In] System.Data.OleDb.tagDBPARAMS pDBParams,
[Out] out IntPtr pcRowsAffected,
[Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset);
[ Obsolete("not used", true)] void GetDBSession(/*deleted parameter signature*/);
[ Obsolete("not used", true)] void GetCommandText(/*deleted parameter signature*/);
/*[local]
HRESULT SetCommandText(
[in] REFGUID rguidDialect,
[in, unique] LPCOLESTR pwszCommand
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult SetCommandText(
[In] ref Guid rguidDialect,
[In, MarshalAs(UnmanagedType.LPWStr)] string pwszCommand);
}
[Guid("0C733A64-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ICommandWithParameters {
[ Obsolete("not used", true)] void GetParameterInfo(/*deleted parameters signature*/);
[ Obsolete("not used", true)] void MapParameterNames(/*deleted parameter signature*/);
/*[local]
HRESULT SetParameterInfo(
[in] DB_UPARAMS cParams,
[in, unique, size_is((ULONG)cParams)] const DB_UPARAMS rgParamOrdinals[],
[in, unique, size_is((ULONG)cParams)] const DBPARAMBINDINFO rgParamBindInfo[]
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult SetParameterInfo(
[In] IntPtr cParams,
[In, MarshalAs(UnmanagedType.LPArray)] IntPtr[] rgParamOrdinals,
[In, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct)] System.Data.OleDb.tagDBPARAMBINDINFO[] rgParamBindInfo);
}
[Guid("2206CCB1-19C1-11D1-89E0-00C04FD7A829"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IDataInitialize {
}
[Guid("0C733A89-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IDBInfo {
/*[local]
HRESULT GetKeywords(
[out] LPOLESTR * ppwszKeywords
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetKeywords(
[Out, MarshalAs(UnmanagedType.LPWStr)] out string ppwszKeywords);
/*[local]
HRESULT GetLiteralInfo(
[in] ULONG cLiterals,
[in, size_is(cLiterals)] const DBLITERAL rgLiterals[],
[in, out] ULONG * pcLiteralInfo,
[out, size_is(,*pcLiteralInfo)] DBLITERALINFO ** prgLiteralInfo,
[out] OLECHAR ** ppCharBuffer
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetLiteralInfo(
[In] int cLiterals,
[In, MarshalAs(UnmanagedType.LPArray)] int[] rgLiterals,
[Out] out int pcLiteralInfo,
[Out] out IntPtr prgLiteralInfo,
[Out] out IntPtr ppCharBuffer);
}
[Guid("0C733A8A-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IDBProperties {
/*[local]
HRESULT GetProperties(
[in] const ULONG cPropertyIDSets,
[in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[],
[in, out] ULONG * pcPropertySets,
[out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
[In] SafeHandle rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
[PreserveSig] System.Data.OleDb.OleDbHResult GetPropertyInfo(
[In] int cPropertyIDSets,
[In] SafeHandle rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertyInfoSets,
[Out] out IntPtr ppDescBuffer);
[PreserveSig] System.Data.OleDb.OleDbHResult SetProperties(
[In] int cPropertySets,
[In] SafeHandle rgPropertySets);
}
[Guid("0C733A7B-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IDBSchemaRowset {
/*[local]
HRESULT GetRowset(
[in] IUnknown * pUnkOuter,
[in] REFGUID rguidSchema,
[in] ULONG cRestrictions,
[in, size_is(cRestrictions)] const VARIANT rgRestrictions[],
[in] REFIID riid,
[in] ULONG cPropertySets,
[in, out, unique, size_is(cPropertySets)] DBPROPSET rgPropertySets[],
[out, iid_is(riid)] IUnknown ** ppRowset
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetRowset(
[In] IntPtr pUnkOuter,
[In] ref Guid rguidSchema,
[In] int cRestrictions,
[In, MarshalAs(UnmanagedType.LPArray)] object[] rgRestrictions,
[In] ref Guid riid,
[In] int cPropertySets,
[In] IntPtr rgPropertySets,
[Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppRowset);
/*[local]
HRESULT GetSchemas(
[in, out] ULONG * pcSchemas,
[out, size_is(,*pcSchemas)] GUID ** prgSchemas,
[out, size_is(,*pcSchemas)] ULONG ** prgRestrictionSupport
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetSchemas(
[Out] out int pcSchemas,
[Out] out IntPtr rguidSchema,
[Out] out IntPtr prgRestrictionSupport);
}
[Guid("1CF2B120-547D-101B-8E65-08002B2BD119"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IErrorInfo {
[ Obsolete("not used", true)] void GetGUID(/*deleted parameter signature*/);
[PreserveSig] System.Data.OleDb.OleDbHResult GetSource(
[Out, MarshalAs(UnmanagedType.BStr)] out string pBstrSource);
[PreserveSig] System.Data.OleDb.OleDbHResult GetDescription(
[Out, MarshalAs(UnmanagedType.BStr)] out string pBstrDescription);
//[ Obsolete("not used", true)] void GetHelpFile(/*deleted parameter signature*/);
//[ Obsolete("not used", true)] void GetHelpContext(/*deleted parameter signature*/);
}
#if false
MIDL_INTERFACE("1CF2B120-547D-101B-8E65-08002B2BD119")
IErrorInfo : public IUnknown
virtual HRESULT STDMETHODCALLTYPE GetGUID(
/* [out] */ GUID *pGUID) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSource(
/* [out] */ BSTR *pBstrSource) = 0;
virtual HRESULT STDMETHODCALLTYPE GetDescription(
/* [out] */ BSTR *pBstrDescription) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHelpFile(
/* [out] */ BSTR *pBstrHelpFile) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHelpContext(
/* [out] */ DWORD *pdwHelpContext) = 0;
#endif
[Guid("0C733A67-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IErrorRecords {
[ Obsolete("not used", true)] void AddErrorRecord(/*deleted parameter signature*/);
[ Obsolete("not used", true)] void GetBasicErrorInfo(/*deleted parameter signature*/);
[PreserveSig] System.Data.OleDb.OleDbHResult GetCustomErrorObject( // may return E_NOINTERFACE when asking for IID_ISQLErrorInfo
[In] Int32 ulRecordNum,
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.Interface)] out ISQLErrorInfo ppObject);
[return:MarshalAs(UnmanagedType.Interface)] IErrorInfo GetErrorInfo(
[In] Int32 ulRecordNum,
[In] Int32 lcid);
[ Obsolete("not used", true)] void GetErrorParameters(/*deleted parameter signature*/);
Int32 GetRecordCount();
}
#if false
MIDL_INTERFACE("0c733a67-2a1c-11ce-ade5-00aa0044773d")
IErrorRecords : public IUnknown
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddErrorRecord(
/* [in] */ ERRORINFO *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS *pdispparams,
/* [in] */ IUnknown *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBasicErrorInfo(
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO *pErrorInfo) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetCustomErrorObject(
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown **ppObject) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorInfo(
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo **ppErrorInfo) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorParameters(
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS *pdispparams) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRecordCount(
/* [out] */ ULONG *pcRecords) = 0;
#endif
[Guid("0C733A90-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IMultipleResults {
/*[local]
HRESULT GetResult(
[in] IUnknown * pUnkOuter,
[in] DBRESULTFLAG lResultFlag,
[in] REFIID riid,
[out] DBROWCOUNT * pcRowsAffected,
[out, iid_is(riid)] IUnknown ** ppRowset
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetResult(
[In] IntPtr pUnkOuter,
[In] IntPtr lResultFlag,
[In] ref Guid riid,
[Out] out IntPtr pcRowsAffected,
[Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset);
}
#if false
enum DBRESULTFLAGENUM {
DBRESULTFLAG_DEFAULT = 0,
DBRESULTFLAG_ROWSET = 1,
DBRESULTFLAG_ROW = 2
}
MIDL_INTERFACE("0c733a90-2a1c-11ce-ade5-00aa0044773d")
IMultipleResults : public IUnknown
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetResult(
/* [in] */ IUnknown *pUnkOuter,
/* [in] */ DBRESULTFLAG lResultFlag,
/* [in] */ REFIID riid,
/* [out] */ DBROWCOUNT *pcRowsAffected,
/* [iid_is][out] */ IUnknown **ppRowset) = 0;
#endif
[Guid("0C733A69-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IOpenRowset {
[PreserveSig] System.Data.OleDb.OleDbHResult OpenRowset(
[In] IntPtr pUnkOuter,
[In] System.Data.OleDb.tagDBID pTableID,
[In] IntPtr pIndexID,
[In] ref Guid riid,
[In] int cPropertySets,
[In] IntPtr rgPropertySets,
[Out, MarshalAs(UnmanagedType.Interface)] out object ppRowset);
}
[Guid("0C733AB4-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IRow {
[PreserveSig] System.Data.OleDb.OleDbHResult GetColumns(
[In] IntPtr cColumns,
[In, Out, MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.Struct)] System.Data.OleDb.tagDBCOLUMNACCESS[] rgColumns);
//[ Obsolete("not used", true)] void GetSourceRowset(/*deleted parameter signature*/);
//[ Obsolete("not used", true)] void Open(/*deleted parameter signature*/);
}
[Guid("0C733A7C-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IRowset {
[ Obsolete("not used", true)] void AddRefRows(/*deleted parameter signature*/);
/*HRESULT GetData(
[in] HROW hRow,
[in] HACCESSOR hAccessor,
[out] void * pData
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetData(
[In] IntPtr hRow,
[In] IntPtr hAccessor,
[In] IntPtr pData);
/*HRESULT GetNextRows(
[in] HCHAPTER hReserved,
[in] DBROWOFFSET lRowsOffset,
[in] DBROWCOUNT cRows,
[out] DBCOUNTITEM * pcRowsObtained,
[out, size_is(,cRows)] HROW ** prghRows
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetNextRows(
[In] IntPtr hChapter,
[In] IntPtr lRowsOffset,
[In] IntPtr cRows,
[Out] out IntPtr pcRowsObtained,
[In] ref IntPtr pprghRows);
/*HRESULT ReleaseRows(
[in] DBCOUNTITEM cRows,
[in, size_is(cRows)] const HROW rghRows[],
[in, size_is(cRows)] DBROWOPTIONS rgRowOptions[],
[out, size_is(cRows)] DBREFCOUNT rgRefCounts[],
[out, size_is(cRows)] DBROWSTATUS rgRowStatus[]
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult ReleaseRows(
[In] IntPtr cRows,
[In] SafeHandle rghRows,
[In/*, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRowOptions,
[In/*, Out, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRefCounts,
[In/*, Out, MarshalAs(UnmanagedType.LPArray)*/] IntPtr/*int[]*/ rgRowStatus);
[ Obsolete("not used", true)] void RestartPosition(/*deleted parameter signature*/);
}
[Guid("0C733A55-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface IRowsetInfo {
/*[local]
HRESULT GetProperties(
[in] const ULONG cPropertyIDSets,
[in, size_is(cPropertyIDSets)] const DBPROPIDSET rgPropertyIDSets[],
[in, out] ULONG * pcPropertySets,
[out, size_is(,*pcPropertySets)] DBPROPSET ** prgPropertySets
);*/
[PreserveSig] System.Data.OleDb.OleDbHResult GetProperties(
[In] int cPropertyIDSets,
[In] SafeHandle rgPropertyIDSets,
[Out] out int pcPropertySets,
[Out] out IntPtr prgPropertySets);
[PreserveSig] System.Data.OleDb.OleDbHResult GetReferencedRowset(
[In] IntPtr iOrdinal,
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.Interface)] out IRowset ppRowset);
//[PreserveSig]
//int GetSpecification(/*deleted parameter signature*/);
}
[Guid("0C733A74-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ISQLErrorInfo {
[return:MarshalAs(UnmanagedType.I4)] Int32 GetSQLInfo(
[Out, MarshalAs(UnmanagedType.BStr)] out String pbstrSQLState);
}
[Guid("0C733A5F-2A1C-11CE-ADE5-00AA0044773D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), ComImport, SuppressUnmanagedCodeSecurity]
internal interface ITransactionLocal {
[ Obsolete("not used", true)] void Commit(/*deleted parameter signature*/);
[ Obsolete("not used", true)] void Abort(/*deleted parameter signature*/);
[ Obsolete("not used", true)] void GetTransactionInfo(/*deleted parameter signature*/);
[ Obsolete("not used", true)] void GetOptionsObject(/*deleted parameter signature*/);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
[PreserveSig] System.Data.OleDb.OleDbHResult StartTransaction(
[In] int isoLevel,
[In] int isoFlags,
[In] IntPtr pOtherOptions,
[Out] out int pulTransactionLevel);
}
// we wrap the vtable entry which is just a function pointer as a delegate
// since code (unlike data) doesn't move around within the process, it is safe to cache the delegate
// we do not expect native to change its vtable entry at run-time (especially since these are free-threaded objects)
// however to be extra safe double check the function pointer is the same as the cached delegate
// whenever we encounter a new instance of the data
// dangerous delegate around IUnknown::QueryInterface (0th vtable entry)
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal delegate int IUnknownQueryInterface(
IntPtr pThis,
ref Guid riid,
ref IntPtr ppInterface);
// dangerous delegate around IDataInitialize::GetDataSource (4th vtable entry)
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal delegate System.Data.OleDb.OleDbHResult IDataInitializeGetDataSource(
IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI
IntPtr pUnkOuter,
int dwClsCtx,
[MarshalAs(UnmanagedType.LPWStr)] string pwszInitializationString,
ref Guid riid,
ref System.Data.OleDb.DataSourceWrapper ppDataSource);
// dangerous wrapper around IDBInitialize::Initialize (4th vtable entry)
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal delegate System.Data.OleDb.OleDbHResult IDBInitializeInitialize(
IntPtr pThis); // first parameter is always the 'this' value, must use use result from QI
// dangerous wrapper around IDBCreateSession::CreateSession (4th vtable entry)
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal delegate System.Data.OleDb.OleDbHResult IDBCreateSessionCreateSession(
IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI
IntPtr pUnkOuter,
ref Guid riid,
ref System.Data.OleDb.SessionWrapper ppDBSession);
// dangerous wrapper around IDBCreateCommand::CreateCommand (4th vtable entry)
[System.Security.SuppressUnmanagedCodeSecurityAttribute()]
internal delegate System.Data.OleDb.OleDbHResult IDBCreateCommandCreateCommand(
IntPtr pThis, // first parameter is always the 'this' value, must use use result from QI
IntPtr pUnkOuter,
ref Guid riid,
[MarshalAs(UnmanagedType.Interface)] ref object ppCommand);
//
// Advapi32.dll Integrated security functions
//
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct Trustee {
internal IntPtr _pMultipleTrustee; // PTRUSTEE
internal int _MultipleTrusteeOperation; // MULTIPLE_TRUSTEE_OPERATION
internal int _TrusteeForm; // TRUSTEE_FORM
internal int _TrusteeType; // TRUSTEE_TYPE
[MarshalAs(UnmanagedType.LPTStr)]
internal string _name;
internal Trustee(string name) {
_pMultipleTrustee = IntPtr.Zero;
_MultipleTrusteeOperation = 0; // NO_MULTIPLE_TRUSTEE
_TrusteeForm = 1; // TRUSTEE_IS_NAME
_TrusteeType = 1; // TRUSTEE_IS_USER
_name = name;
}
}
[DllImport(ExternDll.Advapi32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern uint GetEffectiveRightsFromAclW (byte[] pAcl, ref Trustee pTrustee, out uint pAccessMask);
[DllImport(ExternDll.Advapi32, SetLastError=true)]
[ResourceExposure(ResourceScope.None)]
[return:MarshalAs(UnmanagedType.Bool)]
static internal extern bool CheckTokenMembership (IntPtr tokenHandle, byte[] sidToCheck, out bool isMember);
[DllImport(ExternDll.Advapi32, SetLastError=true)]
[ResourceExposure(ResourceScope.None)]
[return:MarshalAs(UnmanagedType.Bool)]
static internal extern bool ConvertSidToStringSidW(IntPtr sid, out IntPtr stringSid);
[DllImport(ExternDll.Advapi32, EntryPoint="CreateWellKnownSid", SetLastError=true, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
static internal extern int CreateWellKnownSid(
int sidType,
byte[] domainSid,
[Out] byte[] resultSid,
ref uint resultSidLength );
[DllImport(ExternDll.Advapi32, SetLastError=true)]
[ResourceExposure(ResourceScope.None)]
[return:MarshalAs(UnmanagedType.Bool)]
static internal extern bool GetTokenInformation(IntPtr tokenHandle, uint token_class, IntPtr tokenStruct, uint tokenInformationLength, ref uint tokenString);
[DllImport(ExternDll.Kernel32, CharSet=CharSet.Unicode)]
[ResourceExposure(ResourceScope.None)]
internal static extern int lstrlenW(IntPtr ptr);
/* For debugging purposes...
[DllImport(ExternDll.Advapi32)]
[return:MarshalAs(UnmanagedType.I4)]
static internal extern int GetLengthSid(IntPtr sid1);
*/
}
}
| |
#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;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
namespace PdfSharp.Drawing
{
/// <summary>
/// Represents a so called 'PDF form external object', which is typically an imported page of an external
/// PDF document. XPdfForm objects are used like images to draw an existing PDF page of an external
/// document in the current document. XPdfForm objects can only be placed in PDF documents. If you try
/// to draw them using a XGraphics based on an GDI+ context no action is taken if no placeholder image
/// is specified. Otherwise the place holder is drawn.
/// </summary>
public class XPdfForm : XForm
{
/// <summary>
/// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document.
/// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects
/// in your code and change the PageNumber property if more than one page is needed form the external
/// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to
/// dispose XPdfForm objects if not needed anymore.
/// </summary>
internal XPdfForm(string path)
{
int pageNumber;
path = ExtractPageNumber(path, out pageNumber);
#if !NETFX_CORE
path = Path.GetFullPath(path);
if (!File.Exists(path))
throw new FileNotFoundException(PSSR.FileNotFound(path));
#endif
if (PdfReader.TestPdfFile(path) == 0)
throw new ArgumentException("The specified file has no valid PDF file header.", "path");
_path = path;
if (pageNumber != 0)
PageNumber = pageNumber;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfForm"/> class from a stream.
/// </summary>
/// <param name="stream">The stream.</param>
internal XPdfForm(Stream stream)
{
// Create a dummy unique path
_path = "*" + Guid.NewGuid().ToString("B");
if (PdfReader.TestPdfFile(stream) == 0)
throw new ArgumentException("The specified stream has no valid PDF file header.", "stream");
_externalDocument = PdfReader.Open(stream);
}
/// <summary>
/// Creates an XPdfForm from a file.
/// </summary>
public static new XPdfForm FromFile(string path)
{
// TODO: Same file should return same object (that's why the function is static).
return new XPdfForm(path);
}
/// <summary>
/// Creates an XPdfForm from a stream.
/// </summary>
public static new XPdfForm FromStream(Stream stream)
{
return new XPdfForm(stream);
}
/*
void Initialize()
{
// ImageFormat has no overridden Equals...
}
*/
/// <summary>
/// Sets the form in the state FormState.Finished.
/// </summary>
internal override void Finish()
{
if (_formState == FormState.NotATemplate || _formState == FormState.Finished)
return;
base.Finish();
//if (Gfx.metafile != null)
// image = Gfx.metafile;
//Debug.Assert(_fromState == FormState.Created || _fromState == FormState.UnderConstruction);
//_fromState = FormState.Finished;
//Gfx.Dispose();
//Gfx = null;
//if (_pdfRenderer != null)
//{
// _pdfForm.Stream = new PdfDictionary.PdfStream(PdfEncoders.RawEncoding.GetBytes(pdfRenderer.GetContent()), this.pdfForm);
// if (_document.Options.CompressContentStreams)
// {
// _pdfForm.Stream.Value = Filtering.FlateDecode.Encode(pdfForm.Stream.Value);
// _pdfForm.Elements["/Filter"] = new PdfName("/FlateDecode");
// }
// int length = _pdfForm.Stream.Length;
// _pdfForm.Elements.SetInteger("/Length", length);
//}
}
/// <summary>
/// Frees the memory occupied by the underlying imported PDF document, even if other XPdfForm objects
/// refer to this document. A reuse of this object doesn't fail, because the underlying PDF document
/// is re-imported if necessary.
/// </summary>
// TODO: NYI: Dispose
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
try
{
if (disposing)
{
//...
}
if (_externalDocument != null)
PdfDocument.Tls.DetachDocument(_externalDocument.Handle);
//...
}
finally
{
base.Dispose(disposing);
}
}
}
bool _disposed;
/// <summary>
/// Gets or sets an image that is used for drawing if the current XGraphics object cannot handle
/// PDF forms. A place holder is useful for showing a preview of a page on the display, because
/// PDFsharp cannot render native PDF objects.
/// </summary>
public XImage PlaceHolder
{
get { return _placeHolder; }
set { _placeHolder = value; }
}
XImage _placeHolder;
/// <summary>
/// Gets the underlying PdfPage (if one exists).
/// </summary>
public PdfPage Page
{
get
{
if (IsTemplate)
return null;
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return page;
}
}
/// <summary>
/// Gets the number of pages in the PDF form.
/// </summary>
public int PageCount
{
get
{
if (IsTemplate)
return 1;
if (_pageCount == -1)
_pageCount = ExternalDocument.Pages.Count;
return _pageCount;
}
}
int _pageCount = -1;
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF.")]
public override double Width
{
get
{
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return page.Width;
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF.")]
public override double Height
{
get
{
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return page.Height;
}
}
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
public override double PointWidth
{
get
{
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return page.Width;
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
public override double PointHeight
{
get
{
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return page.Height;
}
}
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
public override int PixelWidth
{
get
{
//PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
//return (int)page.Width;
return DoubleUtil.DoubleToInt(PointWidth);
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
public override int PixelHeight
{
get
{
//PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
//return (int)page.Height;
return DoubleUtil.DoubleToInt(PointHeight);
}
}
/// <summary>
/// Get the size of the page identified by the property PageNumber.
/// </summary>
public override XSize Size
{
get
{
PdfPage page = ExternalDocument.Pages[_pageNumber - 1];
return new XSize(page.Width, page.Height);
}
}
/// <summary>
/// Gets or sets the transformation matrix.
/// </summary>
public override XMatrix Transform
{
get { return _transform; }
set
{
if (_transform != value)
{
// discard PdfFromXObject when Transform changed
_pdfForm = null;
_transform = value;
}
}
}
/// <summary>
/// Gets or sets the page number in the external PDF document this object refers to. The page number
/// is one-based, i.e. it is in the range from 1 to PageCount. The default value is 1.
/// </summary>
public int PageNumber
{
get { return _pageNumber; }
set
{
if (IsTemplate)
throw new InvalidOperationException("The page number of an XPdfForm template cannot be modified.");
if (_pageNumber != value)
{
_pageNumber = value;
// dispose PdfFromXObject when number has changed
_pdfForm = null;
}
}
}
int _pageNumber = 1;
/// <summary>
/// Gets or sets the page index in the external PDF document this object refers to. The page index
/// is zero-based, i.e. it is in the range from 0 to PageCount - 1. The default value is 0.
/// </summary>
public int PageIndex
{
get { return PageNumber - 1; }
set { PageNumber = value + 1; }
}
/// <summary>
/// Gets the underlying document from which pages are imported.
/// </summary>
internal PdfDocument ExternalDocument
{
// The problem is that you can ask an XPdfForm about the number of its pages before it was
// drawn the first time. At this moment the XPdfForm doesn't know the document where it will
// be later draw on one of its pages. To prevent the import of the same document more than
// once, all imported documents of a thread are cached. The cache is local to the current
// thread and not to the appdomain, because I won't get problems in a multi-thread environment
// that I don't understand.
get
{
if (IsTemplate)
throw new InvalidOperationException("This XPdfForm is a template and not an imported PDF page; therefore it has no external document.");
if (_externalDocument == null)
_externalDocument = PdfDocument.Tls.GetDocument(_path);
return _externalDocument;
}
}
internal PdfDocument _externalDocument;
/// <summary>
/// Extracts the page number if the path has the form 'MyFile.pdf#123' and returns
/// the actual path without the number sign and the following digits.
/// </summary>
public static string ExtractPageNumber(string path, out int pageNumber)
{
if (path == null)
throw new ArgumentNullException("path");
pageNumber = 0;
int length = path.Length;
if (length != 0)
{
length--;
if (char.IsDigit(path, length))
{
while (char.IsDigit(path, length) && length >= 0)
length--;
if (length > 0 && path[length] == '#')
{
// Must have at least one dot left of colon to distinguish from e.g. '#123'
if (path.IndexOf('.') != -1)
{
pageNumber = int.Parse(path.Substring(length + 1));
path = path.Substring(0, length);
}
}
}
}
return path;
}
}
}
| |
#if NET452
namespace Microsoft.ApplicationInsights.DependencyCollector.Implementation
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using Microsoft.ApplicationInsights.Common;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.Extensibility.Implementation.Tracing;
/// <summary>
/// Concrete class with all processing logic to generate RDD data from the callbacks
/// received from Profiler instrumentation for HTTP or HTTP EventSource/DiagnosticSource events.
/// </summary>
internal abstract class HttpProcessing
{
protected TelemetryClient telemetryClient;
private readonly ApplicationInsightsUrlFilter applicationInsightsUrlFilter;
private readonly TelemetryConfiguration configuration;
private readonly ICollection<string> correlationDomainExclusionList;
private readonly bool setCorrelationHeaders;
private readonly bool injectLegacyHeaders;
private readonly bool injectRequestIdInW3CMode;
/// <summary>
/// Initializes a new instance of the <see cref="HttpProcessing"/> class.
/// </summary>
protected HttpProcessing(TelemetryConfiguration configuration,
string sdkVersion,
string agentVersion,
bool setCorrelationHeaders,
ICollection<string> correlationDomainExclusionList,
bool injectLegacyHeaders,
bool injectRequestIdInW3CMode)
{
this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
this.applicationInsightsUrlFilter = new ApplicationInsightsUrlFilter(configuration);
this.telemetryClient = new TelemetryClient(configuration);
this.correlationDomainExclusionList = correlationDomainExclusionList ?? throw new ArgumentNullException(nameof(correlationDomainExclusionList));
this.setCorrelationHeaders = setCorrelationHeaders;
this.telemetryClient.Context.GetInternalContext().SdkVersion = sdkVersion;
if (!string.IsNullOrEmpty(agentVersion))
{
this.telemetryClient.Context.GetInternalContext().AgentVersion = agentVersion;
}
this.injectLegacyHeaders = injectLegacyHeaders;
this.injectRequestIdInW3CMode = injectRequestIdInW3CMode;
}
/// <summary>
/// Gets HTTP request url.
/// </summary>
/// <param name="webRequest">Represents web request.</param>
/// <returns>The url if possible otherwise empty string.</returns>
internal static Uri GetUrl(WebRequest webRequest)
{
Uri resource = null;
if (webRequest != null && webRequest.RequestUri != null)
{
resource = webRequest.RequestUri;
}
return resource;
}
/// <summary>
/// Common helper for all Begin Callbacks.
/// </summary>
/// <param name="thisObj">This object.</param>
/// <param name="injectCorrelationHeaders">Flag that enables Request-Id and Correlation-Context headers injection.
/// Should be set to true only for profiler and old versions of DiagnosticSource Http hook events.</param>
/// <returns>Null object as all context is maintained in this class via weak tables.</returns>
internal object OnBegin(object thisObj, bool injectCorrelationHeaders = true)
{
try
{
if (thisObj == null)
{
DependencyCollectorEventSource.Log.NotExpectedCallback(0, "OnBeginHttp", "thisObj == null");
return null;
}
WebRequest webRequest = thisObj as WebRequest;
if (webRequest == null)
{
DependencyCollectorEventSource.Log.UnexpectedCallbackParameter("WebRequest");
}
var url = GetUrl(webRequest);
if (url == null)
{
DependencyCollectorEventSource.Log.NotExpectedCallback(thisObj.GetHashCode(), "OnBeginHttp",
"resourceName is empty");
return null;
}
string httpMethod = webRequest.Method;
string resourceName = url.AbsolutePath;
if (!string.IsNullOrEmpty(httpMethod))
{
resourceName = httpMethod + " " + resourceName;
}
DependencyCollectorEventSource.Log.BeginCallbackCalled(thisObj.GetHashCode(), resourceName);
if (this.applicationInsightsUrlFilter.IsApplicationInsightsUrl(url))
{
// Not logging as we will be logging for all outbound AI calls
return null;
}
if (webRequest.Headers[W3C.W3CConstants.TraceParentHeader] != null && Activity.DefaultIdFormat == ActivityIdFormat.W3C)
{
DependencyCollectorEventSource.Log.HttpRequestAlreadyInstrumented();
return null;
}
// If the object already exists, don't add again. This happens because either GetResponse or GetRequestStream could
// be the starting point for the outbound call.
DependencyTelemetry telemetry = null;
var telemetryTuple = this.GetTupleForWebDependencies(webRequest);
if (telemetryTuple?.Item1 != null)
{
DependencyCollectorEventSource.Log.TrackingAnExistingTelemetryItemVerbose();
return null;
}
// Create and initialize a new telemetry object
telemetry = ClientServerDependencyTracker.BeginTracking(this.telemetryClient);
this.AddTupleForWebDependencies(webRequest, telemetry, false);
if (string.IsNullOrEmpty(telemetry.Context.InstrumentationKey))
{
// Instrumentation key is probably empty, because the context has not yet had a chance to associate the requestTelemetry to the telemetry client yet.
// and get they instrumentation key from all possible sources in the process. Let's do that now.
this.telemetryClient.InitializeInstrumentationKey(telemetry);
}
telemetry.Name = resourceName;
telemetry.Target = DependencyTargetNameHelper.GetDependencyTargetName(url);
telemetry.Type = RemoteDependencyConstants.HTTP;
telemetry.Data = url.OriginalString;
telemetry.SetOperationDetail(RemoteDependencyConstants.HttpRequestOperationDetailName, webRequest);
Activity currentActivity = Activity.Current;
// Add the source instrumentation key header if collection is enabled, the request host is not in the excluded list and the same header doesn't already exist
if (this.setCorrelationHeaders && !this.correlationDomainExclusionList.Contains(url.Host))
{
string applicationId = null;
try
{
if (!string.IsNullOrEmpty(telemetry.Context.InstrumentationKey)
&& webRequest.Headers.GetNameValueHeaderValue(RequestResponseHeaders.RequestContextHeader,
RequestResponseHeaders.RequestContextCorrelationSourceKey) == null
&& (this.configuration.ApplicationIdProvider?.TryGetApplicationId(
telemetry.Context.InstrumentationKey, out applicationId) ?? false))
{
webRequest.Headers.SetNameValueHeaderValue(RequestResponseHeaders.RequestContextHeader,
RequestResponseHeaders.RequestContextCorrelationSourceKey, applicationId);
}
}
catch (Exception ex)
{
AppMapCorrelationEventSource.Log.SetCrossComponentCorrelationHeaderFailed(
ex.ToInvariantString());
}
if (this.injectLegacyHeaders)
{
// Add the root ID
var rootId = telemetry.Context.Operation.Id;
if (!string.IsNullOrEmpty(rootId) &&
webRequest.Headers[RequestResponseHeaders.StandardRootIdHeader] == null)
{
webRequest.Headers.Add(RequestResponseHeaders.StandardRootIdHeader, rootId);
}
// Add the parent ID
var parentId = telemetry.Id;
if (!string.IsNullOrEmpty(parentId))
{
if (webRequest.Headers[RequestResponseHeaders.StandardParentIdHeader] == null)
{
webRequest.Headers.Add(RequestResponseHeaders.StandardParentIdHeader, parentId);
}
}
}
if (currentActivity != null)
{
// ApplicationInsights only needs to inject W3C, potentially Request-Id and Correlation-Context
// headers for profiler instrumentation.
// in case of Http Desktop DiagnosticSourceListener they are injected in
// DiagnosticSource (with the System.Net.Http.Desktop.HttpRequestOut.Start event)
if (injectCorrelationHeaders)
{
if (currentActivity.IdFormat == ActivityIdFormat.W3C)
{
if (webRequest.Headers[W3C.W3CConstants.TraceParentHeader] == null)
{
webRequest.Headers.Add(W3C.W3CConstants.TraceParentHeader, currentActivity.Id);
}
if (webRequest.Headers[W3C.W3CConstants.TraceStateHeader] == null &&
!string.IsNullOrEmpty(currentActivity.TraceStateString))
{
webRequest.Headers.Add(W3C.W3CConstants.TraceStateHeader,
currentActivity.TraceStateString);
}
}
else
{
// Request-Id format
if (webRequest.Headers[RequestResponseHeaders.RequestIdHeader] == null)
{
webRequest.Headers.Add(RequestResponseHeaders.RequestIdHeader, telemetry.Id);
}
}
InjectCorrelationContext(webRequest.Headers, currentActivity);
}
}
}
// Active bug in .NET Fx diagnostics hook: https://github.com/dotnet/corefx/pull/40777
// Application Insights has to inject Request-Id to work it around
if (currentActivity?.IdFormat == ActivityIdFormat.W3C)
{
// if (this.injectRequestIdInW3CMode)
{
if (webRequest.Headers[RequestResponseHeaders.RequestIdHeader] == null)
{
webRequest.Headers.Add(RequestResponseHeaders.RequestIdHeader, string.Concat('|', telemetry.Context.Operation.Id, '.', telemetry.Id, '.'));
}
}
}
}
catch (Exception exception)
{
DependencyCollectorEventSource.Log.CallbackError(thisObj == null ? 0 : thisObj.GetHashCode(),
"OnBeginHttp", exception);
}
finally
{
Activity current = Activity.Current;
if (current?.OperationName == ClientServerDependencyTracker.DependencyActivityName)
{
current.Stop();
}
}
return null;
}
/// <summary>
/// Common helper for all End Callbacks.
/// </summary>
/// <param name="request">The HttpWebRequest instance.</param>
/// <param name="response">The HttpWebResponse instance.</param>
internal void OnEndResponse(object request, object response)
{
try
{
if (this.TryGetPendingTelemetry(request, out DependencyTelemetry telemetry))
{
if (response is HttpWebResponse responseObj)
{
int statusCode = -1;
try
{
statusCode = (int)responseObj.StatusCode;
this.SetTarget(telemetry, responseObj.Headers);
// Set the operation details for the response
telemetry.SetOperationDetail(RemoteDependencyConstants.HttpResponseOperationDetailName, responseObj);
}
catch (ObjectDisposedException)
{
// ObjectDisposedException is expected here in the following sequence: httpWebRequest.GetResponse().Dispose() -> httpWebRequest.GetResponse()
// on the second call to GetResponse() we cannot determine the statusCode.
}
SetStatusCode(telemetry, statusCode);
}
ClientServerDependencyTracker.EndTracking(this.telemetryClient, telemetry);
}
}
catch (Exception ex)
{
DependencyCollectorEventSource.Log.CallbackError(request == null ? 0 : request.GetHashCode(), "OnEndResponse", ex);
}
}
/// <summary>
/// Common helper for all End Callbacks.
/// </summary>
/// <param name="exception">The exception object if any.</param>
/// <param name="request">HttpWebRequest instance.</param>
internal void OnEndException(object exception, object request)
{
try
{
if (this.TryGetPendingTelemetry(request, out DependencyTelemetry telemetry))
{
var webException = exception as WebException;
if (webException?.Response is HttpWebResponse responseObj)
{
int statusCode = -1;
try
{
statusCode = (int)responseObj.StatusCode;
this.SetTarget(telemetry, responseObj.Headers);
// Set the operation details for the response
telemetry.SetOperationDetail(RemoteDependencyConstants.HttpResponseOperationDetailName, responseObj);
}
catch (ObjectDisposedException)
{
// ObjectDisposedException is expected here in the following sequence: httpWebRequest.GetResponse().Dispose() -> httpWebRequest.GetResponse()
// on the second call to GetResponse() we cannot determine the statusCode.
}
SetStatusCode(telemetry, statusCode);
}
else if (exception != null)
{
if (webException != null)
{
telemetry.ResultCode = webException.Status.ToString();
}
telemetry.Success = false;
}
ClientServerDependencyTracker.EndTracking(this.telemetryClient, telemetry);
}
}
catch (Exception ex)
{
DependencyCollectorEventSource.Log.CallbackError(request == null ? 0 : request.GetHashCode(), "OnEndException", ex);
}
}
/// <summary>
/// Common helper for all End Callbacks.
/// </summary>
/// <param name="request">WebRequest object.</param>
/// <param name="statusCode">HttpStatusCode from response.</param>
/// <param name="responseHeaders">Response headers.</param>
internal void OnEndResponse(object request, object statusCode, object responseHeaders)
{
try
{
if (this.TryGetPendingTelemetry(request, out DependencyTelemetry telemetry))
{
if (statusCode != null)
{
SetStatusCode(telemetry, (int)statusCode);
}
this.SetTarget(telemetry, (WebHeaderCollection)responseHeaders);
telemetry.SetOperationDetail(RemoteDependencyConstants.HttpResponseHeadersOperationDetailName, responseHeaders);
ClientServerDependencyTracker.EndTracking(this.telemetryClient, telemetry);
}
}
catch (Exception ex)
{
DependencyCollectorEventSource.Log.CallbackError(request == null ? 0 : request.GetHashCode(), "OnEndResponse", ex);
}
}
/// <summary>
/// Implemented by the derived class for adding the tuple to its specific cache.
/// </summary>
/// <param name="webRequest">The request which acts the key.</param>
/// <param name="telemetry">The dependency telemetry for the tuple.</param>
/// <param name="isCustomCreated">Boolean value that tells if the current telemetry item is being added by the customer or not.</param>
protected abstract void AddTupleForWebDependencies(WebRequest webRequest, DependencyTelemetry telemetry, bool isCustomCreated);
/// <summary>
/// Implemented by the derived class for getting the tuple from its specific cache.
/// </summary>
/// <param name="webRequest">The request which acts as the key.</param>
/// <returns>The tuple for the given request.</returns>
protected abstract Tuple<DependencyTelemetry, bool> GetTupleForWebDependencies(WebRequest webRequest);
/// <summary>
/// Implemented by the derived class for removing the tuple from its specific cache.
/// </summary>
/// <param name="webRequest">The request which acts as the key.</param>
protected abstract void RemoveTupleForWebDependencies(WebRequest webRequest);
private static void InjectCorrelationContext(WebHeaderCollection requestHeaders, Activity activity)
{
if (requestHeaders[RequestResponseHeaders.CorrelationContextHeader] == null && activity.Baggage.Any())
{
requestHeaders.SetHeaderFromNameValueCollection(RequestResponseHeaders.CorrelationContextHeader, activity.Baggage);
}
}
private static void SetStatusCode(DependencyTelemetry telemetry, int statusCode)
{
telemetry.ResultCode = statusCode > 0 ? statusCode.ToString(CultureInfo.InvariantCulture) : string.Empty;
telemetry.Success = (statusCode > 0) && (statusCode < 400);
}
private bool TryGetPendingTelemetry(object request, out DependencyTelemetry telemetry)
{
telemetry = null;
if (request == null)
{
DependencyCollectorEventSource.Log.NotExpectedCallback(0, "OnBeginHttp", "request == null");
return false;
}
DependencyCollectorEventSource.Log.EndCallbackCalled(request.GetHashCode()
.ToString(CultureInfo.InvariantCulture));
WebRequest webRequest = request as WebRequest;
if (webRequest == null)
{
DependencyCollectorEventSource.Log.UnexpectedCallbackParameter("WebRequest");
return false;
}
var telemetryTuple = this.GetTupleForWebDependencies(webRequest);
if (telemetryTuple == null)
{
DependencyCollectorEventSource.Log.EndCallbackWithNoBegin(request.GetHashCode()
.ToString(CultureInfo.InvariantCulture));
return false;
}
if (telemetryTuple.Item1 == null)
{
DependencyCollectorEventSource.Log.EndCallbackWithNoBegin(request.GetHashCode()
.ToString(CultureInfo.InvariantCulture));
return false;
}
// Not custom created
if (!telemetryTuple.Item2)
{
telemetry = telemetryTuple.Item1;
this.RemoveTupleForWebDependencies(webRequest);
return true;
}
return false;
}
private void SetTarget(DependencyTelemetry telemetry, WebHeaderCollection responseHeaders)
{
if (responseHeaders != null)
{
string targetAppId = null;
try
{
targetAppId = responseHeaders.GetNameValueHeaderValue(
RequestResponseHeaders.RequestContextHeader,
RequestResponseHeaders.RequestContextCorrelationTargetKey);
}
catch (Exception ex)
{
AppMapCorrelationEventSource.Log.GetCrossComponentCorrelationHeaderFailed(ex.ToInvariantString());
}
string currentComponentAppId = null;
if (this.configuration.ApplicationIdProvider?.TryGetApplicationId(telemetry.Context.InstrumentationKey, out currentComponentAppId) ?? false)
{
// We only add the cross component correlation key if the key does not remain the current component.
if (!string.IsNullOrEmpty(targetAppId) && targetAppId != currentComponentAppId)
{
telemetry.Type = RemoteDependencyConstants.AI;
telemetry.Target += " | " + targetAppId;
}
}
}
}
}
}
#endif
| |
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using CsvHelper;
using DataBoss.Data;
namespace DataBoss.DataPackage
{
public class CsvDataReader : DbDataReader, IDataRecordReader
{
class CsvDataRecord : IDataRecord
{
static readonly Func<int, bool> NoData = InvalidGetAttempt;
static bool InvalidGetAttempt(int i) => throw new InvalidOperationException("Invalid attempt to read when no data is present, call Read()");
readonly string[] fieldValue;
readonly BitArray isNull;
readonly CsvDataReader parent;
Func<int, bool> checkedIsNull;
int rowNumber;
public CsvDataRecord(CsvDataReader parent, BitArray isNull, string[] fieldValue) : this(parent, -1, isNull, fieldValue)
{ }
CsvDataRecord(CsvDataReader parent, int rowNumber, BitArray isNull, string[] fieldValue) {
this.isNull = isNull;
this.fieldValue = fieldValue;
this.parent = parent;
this.rowNumber = rowNumber;
this.checkedIsNull = rowNumber == -1 ? NoData : CheckedIsNullUnsafe;
}
public CsvDataRecord Clone() => new(parent, rowNumber, new BitArray(isNull), (string[])fieldValue.Clone());
public void Fill(int rowNumber, CsvParser csv) {
this.rowNumber = rowNumber;
if(checkedIsNull == NoData)
checkedIsNull = CheckedIsNullUnsafe;
for (var i = 0; i != FieldCount; ++i) {
var value = fieldValue[i] = csv[i];
isNull[i] = IsNull(value);
}
}
public object this[int i] => GetValue(i);
public object this[string name] => GetValue(GetOrdinal(name));
public int FieldCount => fieldValue.Length;
public object GetValue(int i) {
if (checkedIsNull(i))
return DBNull.Value;
try {
return ChangeType(fieldValue[i], GetFieldType(i), GetFieldFormat(i));
} catch (FormatException ex) {
var given = isNull[i] ? "null" : $"'{fieldValue[i]}'";
throw new InvalidOperationException($"Failed to parse {GetName(i)} of type {GetFieldType(i)} given {given} on line {rowNumber}", ex);
}
}
bool CheckedIsNullUnsafe(int i) {
if (!isNull[i])
return false;
return parent.IsNullable(i) || UnexpectedNull(i);
}
bool UnexpectedNull(int i) =>
throw new InvalidOperationException($"Unexpected null value for {GetName(i)} on line {rowNumber}.");
public bool IsDBNull(int i) => isNull[i];
public bool GetBoolean(int i) => GetFieldValue<bool>(i);
public byte GetByte(int i) => GetFieldValue<byte>(i);
public char GetChar(int i) => GetFieldValue<char>(i);
public Guid GetGuid(int i) => GetFieldValue<Guid>(i);
public short GetInt16(int i) => GetFieldValue<short>(i);
public int GetInt32(int i) => GetFieldValue<int>(i);
public long GetInt64(int i) => GetFieldValue<long>(i);
public float GetFloat(int i) => GetFieldValue<float>(i);
public double GetDouble(int i) => GetFieldValue<double>(i);
public decimal GetDecimal(int i) => GetFieldValue<decimal>(i);
public string GetString(int i) => checkedIsNull(i) ? default : fieldValue[i];
public DateTime GetDateTime(int i) => (DateTime)GetValue(i);
public TimeSpan GetTimeSpan(int i) => GetFieldValue<TimeSpan>(i);
public CsvInteger GetCsvInteger(int i) => GetFieldValue<CsvInteger>(i);
public CsvNumber GetCsvNumber(int i) => GetFieldValue<CsvNumber>(i);
public T GetFieldValue<T>(int i) {
if (checkedIsNull(i))
return default;
var value = fieldValue[i];
if (typeof(T) == typeof(bool))
return (T)(object)bool.Parse(value);
if (typeof(T) == typeof(byte))
return (T)(object)byte.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(char))
return (T)(object)char.Parse(value);
if (typeof(T) == typeof(short))
return (T)(object)short.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(int))
return (T)(object)int.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(long))
return (T)(object)long.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(float))
return (T)(object)float.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(double))
return (T)(object)double.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(decimal))
return (T)(object)decimal.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(TimeSpan))
return (T)(object)TimeSpan.Parse(value, GetFieldFormat(i));
if (typeof(T) == typeof(Guid))
return (T)(object)Guid.Parse(value);
if (typeof(T) == typeof(CsvInteger))
return (T)(object)new CsvInteger(value, GetFieldFormat(i));
if (typeof(T) == typeof(CsvNumber))
return (T)(object)new CsvNumber(value, GetFieldFormat(i));
return (T)GetValue(i);
}
public int GetValues(object[] values) {
var n = Math.Min(FieldCount, values.Length);
for (var i = 0; i != n; ++i)
values[i] = GetValue(i);
return n;
}
public IDataReader GetData(int i) => throw new NotSupportedException();
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public string GetDataTypeName(int i) => parent.GetDataTypeName(i);
public Type GetFieldType(int i) => parent.GetFieldType(i);
IFormatProvider GetFieldFormat(int i) => parent.fieldFormat[i];
public string GetName(int i) => parent.GetName(i);
public int GetOrdinal(string name) => parent.GetOrdinal(name);
}
class FieldToDbTypeConverter
{
readonly Type Nullable = typeof(Nullable<>);
readonly Func<string, bool> IsPrimaryKey;
public FieldToDbTypeConverter(Func<string, bool> isPrimaryKey) {
this.IsPrimaryKey = isPrimaryKey;
}
public (TableSchemaType TableType, DataBossDbType DbType) ToDbType(TabularDataSchemaFieldDescription field) {
var isRequired = field.Constraints?.IsRequired ?? IsPrimaryKey(field.Name);
var tableType = TableSchemaType.From(field.Type, field.Format);
return (tableType, GetDbType(isRequired, tableType.Type));
}
DataBossDbType GetDbType(bool isRequired, Type type) {
if (isRequired)
return DataBossDbType.From(type, RequiredAttributeProvider.Instance);
if (type.IsValueType)
return DataBossDbType.From(Nullable.MakeGenericType(type));
return DataBossDbType.From(type);
}
}
readonly CsvDataRecord current;
readonly IFormatProvider[] fieldFormat;
readonly CsvTypeCode[] csvFieldType;
readonly DataReaderSchemaTable schema;
CsvParser csv;
int rowNumber;
public event EventHandler Disposed;
public CsvDataReader(TextReader csv, CultureInfo cultureInfo, TabularDataSchema tabularSchema, bool hasHeaderRow = true) :
this(new CsvParser(csv, cultureInfo), tabularSchema, hasHeaderRow)
{ }
public CsvDataReader(CsvParser csv, TabularDataSchema tabularSchema, bool hasHeaderRow = true) {
var fieldCount = tabularSchema.Fields.Count;
this.csv = csv;
this.schema = new DataReaderSchemaTable();
this.fieldFormat = new IFormatProvider[fieldCount];
this.csvFieldType = new CsvTypeCode[fieldCount];
this.current = new CsvDataRecord(this, new BitArray(fieldCount), new string[fieldCount]);
TranslateSchema(tabularSchema);
if (hasHeaderRow)
ValidateHeaderRow();
}
void TranslateSchema(TabularDataSchema tabularSchema) {
var fieldTypeConverter = new FieldToDbTypeConverter(tabularSchema.PrimaryKey == null ? _ => false : tabularSchema.PrimaryKey.Contains);
for (var i = 0; i != tabularSchema.Fields.Count; ++i) {
var field = tabularSchema.Fields[i];
var (tableType, dbType) = fieldTypeConverter.ToDbType(field);
csvFieldType[i] = tableType.CsvTypeCode;
schema.Add(
field.Name,
i,
tableType.Type,
dbType.IsNullable,
field.Constraints?.MaxLength ?? dbType.ColumnSize,
dbType.TypeName,
tableType.CsvType);
if (field.IsNumber())
fieldFormat[i] = field.GetNumberFormat();
}
}
void ValidateHeaderRow() {
if(!ReadRow())
throw new InvalidOperationException("Missing header row.");
for (var i = 0; i != schema.Count; ++i) {
var expected = schema[i].ColumnName;
var actual = csv[i];
if (actual != expected)
throw new InvalidOperationException($"Header mismatch, expected '{expected}' got {actual}");
}
}
bool ReadRow() => UpdateRowNumber(csv.Read());
async Task<bool> ReadRowAsync() => UpdateRowNumber(await csv.ReadAsync());
bool UpdateRowNumber(bool ok) {
if (!ok)
return false;
++rowNumber;
return true;
}
public override int FieldCount => schema.Count;
public override bool IsClosed => csv == null;
public override int Depth => throw new NotSupportedException();
public override int RecordsAffected => throw new NotSupportedException();
public override bool HasRows => throw new NotSupportedException();
public override DataTable GetSchemaTable() => schema.ToDataTable();
public override bool Read() => FillOnRead(ReadRow());
public override async Task<bool> ReadAsync(CancellationToken cancellationToken) => FillOnRead(await ReadRowAsync());
bool FillOnRead(bool rowRead) {
if (!rowRead)
return false;
current.Fill(rowNumber, csv);
return true;
}
public override bool NextResult() => false;
static bool IsNull(string input) => string.IsNullOrEmpty(input);
bool IsNullable(int i) => schema[i].AllowDBNull;
static object ChangeType(string input, Type type, IFormatProvider format) =>
Type.GetTypeCode(type) switch {
TypeCode.DateTime => DateTime.Parse(input, format),
TypeCode.Object when type == typeof(TimeSpan) => TimeSpan.Parse(input, format),
TypeCode.Object when type == typeof(byte[]) => Convert.FromBase64String(input),
_ => Convert.ChangeType(input, type, format),
};
public override Type GetFieldType(int i) => schema[i].DataType;
public override Type GetProviderSpecificFieldType(int i) => schema[i].ProviderSpecificDataType;
public override string GetDataTypeName(int i) => schema[i].DataTypeName;
public override string GetName(int i) => schema[i].ColumnName;
public override int GetOrdinal(string name) => schema.GetOrdinal(name);
public override object this[int i] => GetValue(i);
public override object this[string name] => GetValue(GetOrdinal(name));
public override void Close() {
csv.Dispose();
csv = null;
}
protected override void Dispose(bool disposing) {
if(!disposing)
return;
csv?.Dispose();
Disposed?.Invoke(this, EventArgs.Empty);
}
public override object GetValue(int i) => current.GetValue(i);
public override bool IsDBNull(int i) => current.IsDBNull(i);
public override bool GetBoolean(int i) => current.GetBoolean(i);
public override byte GetByte(int i) => current.GetByte(i);
public override char GetChar(int i) => current.GetChar(i);
public override Guid GetGuid(int i) => current.GetGuid(i);
public override short GetInt16(int i) => current.GetInt16(i);
public override int GetInt32(int i) => current.GetInt32(i);
public override long GetInt64(int i) => current.GetInt64(i);
public override float GetFloat(int i) => current.GetFloat(i);
public override double GetDouble(int i) => current.GetDouble(i);
public override string GetString(int i) => current.GetString(i);
public override decimal GetDecimal(int i) => current.GetDecimal(i);
public override DateTime GetDateTime(int i) => current.GetDateTime(i);
public TimeSpan GetTimeSpan(int i) => current.GetTimeSpan(i);
public CsvInteger GetCsvInteger(int i) => current.GetCsvInteger(i);
public CsvNumber GetCsvNumber(int i) => current.GetCsvNumber(i);
public override T GetFieldValue<T>(int ordinal) => current.GetFieldValue<T>(ordinal);
public override object GetProviderSpecificValue(int i) =>
csvFieldType[i] switch {
CsvTypeCode.None => throw new InvalidCastException(),
CsvTypeCode.CsvInteger => GetCsvInteger(i),
CsvTypeCode.CsvNumber => GetCsvNumber(i),
_ => throw new InvalidOperationException(),
};
public override int GetValues(object[] values) {
var n = Math.Min(FieldCount, values.Length);
for(var i = 0; i != n; ++i)
values[i] = GetValue(i);
return n;
}
public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public override long GetChars(int i, long fieldOffset, char[] buffer, int bufferOffset, int length) => this.GetArray(i, fieldOffset, buffer, bufferOffset, length);
public IDataRecord GetRecord() => current.Clone();
public override IEnumerator GetEnumerator() => new DataReaderEnumerator(this);
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public sealed class BuildingsScene : IDemoScene
{
Demo demo;
PhysicsScene scene;
string name;
string instanceIndexName;
string info;
public PhysicsScene PhysicsScene { get { return scene; } }
public string SceneName { get { return name; } }
public string SceneInfo { get { return info; } }
// Declare objects in the scene
Sky skyInstance1;
Quad quadInstance1;
Cursor cursorInstance;
Shot shotInstance;
Building1 building1Instance1;
Building2 building2Instance1;
Bridge2 bridge2Instance1;
Camera2 camera2Instance1;
Lights lightInstance;
// Declare controllers in the scene
SkyDraw1 skyDraw1Instance1;
CursorDraw1 cursorDraw1Instance;
Camera2Animation1 camera2Animation1Instance1;
Camera2Draw1 camera2Draw1Instance1;
PointLightAnimation1 pointLightAnimation1Instance1;
Vector3 startPosition;
Vector3 endPosition;
Vector3 startScale;
Vector3 endScale;
public BuildingsScene(Demo demo, string name, int instanceIndex, string info)
{
this.demo = demo;
this.name = name;
this.instanceIndexName = " " + instanceIndex.ToString();
this.info = info;
// Create a new objects in the scene
skyInstance1 = new Sky(demo, 1);
quadInstance1 = new Quad(demo, 1);
cursorInstance = new Cursor(demo);
shotInstance = new Shot(demo);
building1Instance1 = new Building1(demo, 1);
building2Instance1 = new Building2(demo, 1);
bridge2Instance1 = new Bridge2(demo, 1);
camera2Instance1 = new Camera2(demo, 1);
lightInstance = new Lights(demo);
// Create a new controllers in the scene
skyDraw1Instance1 = new SkyDraw1(demo, 1);
cursorDraw1Instance = new CursorDraw1(demo);
camera2Animation1Instance1 = new Camera2Animation1(demo, 1);
camera2Draw1Instance1 = new Camera2Draw1(demo, 1);
pointLightAnimation1Instance1 = new PointLightAnimation1(demo, 12);
}
public void Create()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null) return;
scene = demo.Engine.Factory.PhysicsSceneManager.Create(sceneInstanceIndexName);
// Initialize maximum number of solver iterations for the scene
scene.MaxIterationCount = 10;
// Initialize time of simulation for the scene
scene.TimeOfSimulation = 1.0f / 15.0f;
Initialize();
// Initialize objects in the scene
skyInstance1.Initialize(scene);
quadInstance1.Initialize(scene);
cursorInstance.Initialize(scene);
shotInstance.Initialize(scene);
building1Instance1.Initialize(scene);
building2Instance1.Initialize(scene);
bridge2Instance1.Initialize(scene);
camera2Instance1.Initialize(scene);
lightInstance.Initialize(scene);
// Initialize controllers in the scene
skyDraw1Instance1.Initialize(scene);
cursorDraw1Instance.Initialize(scene);
camera2Animation1Instance1.Initialize(scene);
camera2Draw1Instance1.Initialize(scene);
pointLightAnimation1Instance1.Initialize(scene);
// Create shapes shared for all physics objects in the scene
// These shapes are used by all objects in the scene
Demo.CreateSharedShapes(demo, scene);
// Create shapes for objects in the scene
Sky.CreateShapes(demo, scene);
Quad.CreateShapes(demo, scene);
Cursor.CreateShapes(demo, scene);
Shot.CreateShapes(demo, scene);
Building1.CreateShapes(demo, scene);
Building2.CreateShapes(demo, scene);
Bridge2.CreateShapes(demo, scene);
Camera2.CreateShapes(demo, scene);
Lights.CreateShapes(demo, scene);
// Create physics objects for objects in the scene
skyInstance1.Create(new Vector3(0.0f, 0.0f, 0.0f));
quadInstance1.Create(new Vector3(0.0f, -40.0f, 20.0f), new Vector3(1000.0f, 31.0f, 1000.0f), Quaternion.Identity);
cursorInstance.Create();
shotInstance.Create();
building1Instance1.Create(new Vector3(0.0f, 0.0f, 100.0f), Vector3.One, Quaternion.Identity);
building2Instance1.Create(new Vector3(0.0f, 0.0f, -100.0f), Vector3.One, Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(180.0f)));
PhysicsObject startObject = PhysicsScene.Factory.PhysicsObjectManager.Find("Building 2 Level 2 Wall 42 1");
PhysicsObject endObject = PhysicsScene.Factory.PhysicsObjectManager.Find("Building 1 Level 3 Wall 43 1");
startObject.MainWorldTransform.GetPosition(ref startPosition);
startObject.MainWorldTransform.GetScale(ref startScale);
endObject.MainWorldTransform.GetPosition(ref endPosition);
endObject.MainWorldTransform.GetScale(ref endScale);
startPosition += new Vector3(0.0f, startScale.Z, startScale.Y);
endPosition += new Vector3(0.0f, endScale.Y, -endScale.Z);
bridge2Instance1.Create(startObject, endObject, startPosition, endPosition, 20, new Vector2(15.0f, 0.4f));
camera2Instance1.Create(new Vector3(0.0f, 120.0f, -22.0f), Quaternion.Identity, Quaternion.Identity, Quaternion.Identity, true);
lightInstance.CreateLightPoint(0, "Glass", new Vector3(60.0f, 115.0f, -200.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(1, "Glass", new Vector3(40.0f, 102.0f, -180.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(2, "Glass", new Vector3(40.0f, 102.0f, -220.0f), new Vector3(1.0f, 0.2f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(3, "Glass", new Vector3(-40.0f, 46.0f, -298.0f), new Vector3(0.3f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(4, "Glass", new Vector3(-15.0f, 28.0f, -298.0f), new Vector3(0.0f, 0.7f, 0.8f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(5, "Glass", new Vector3(10.0f, 5.0f, -298.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(6, "Glass", new Vector3(-30.0f, -3.0f, -90.0f), new Vector3(1.0f, 0.9f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(7, "Glass", new Vector3(0.0f, -3.0f, -90.0f), new Vector3(0.5f, 0.7f, 0.1f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(8, "Glass", new Vector3(30.0f, -3.0f, -90.0f), new Vector3(1.0f, 0.7f, 0.0f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(9, "Glass", new Vector3(-30.0f, -3.0f, 90.0f), new Vector3(1.0f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(10, "Glass", new Vector3(0.0f, -3.0f, 90.0f), new Vector3(0.3f, 0.7f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(11, "Glass", new Vector3(30.0f, -3.0f, 90.0f), new Vector3(1.0f, 1.0f, 0.5f), 20.0f, 1.0f);
lightInstance.CreateLightPoint(12, "Field", new Vector3(0.0f, -3.0f, 0.0f), new Vector3(0.2f, 1.0f, 0.0f), 20.0f, 0.0001f);
lightInstance.CreateLightSpot(0, "Glass", new Vector3(-30.0f, 117.0f, 180.0f), new Vector3(0.1f, 0.7f, 1.0f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(1, "Glass", new Vector3(0.0f, 117.0f, 150.0f), new Vector3(1.0f, 0.5f, 0.2f), 20.0f, 1.0f);
lightInstance.CreateLightSpot(2, "Glass", new Vector3(30.0f, 117.0f, 180.0f), new Vector3(0.5f, 1.0f, 0.2f), 20.0f, 1.0f);
// Set controllers for objects in the scene
SetControllers();
}
public void Initialize()
{
scene.UserControllers.PostDrawMethods += demo.DrawInfo;
if (scene.Light == null)
{
scene.CreateLight(true);
scene.Light.Type = PhysicsLightType.Directional;
scene.Light.SetDirection(-0.4f, -0.8f, 0.4f, 0.0f);
}
}
public void SetControllers()
{
skyDraw1Instance1.SetControllers();
cursorDraw1Instance.SetControllers();
camera2Animation1Instance1.SetControllers(true);
camera2Draw1Instance1.SetControllers(false, false, false, false, false, false);
pointLightAnimation1Instance1.SetControllers(0.0f, 1.0f, 0.05f);
}
public void Refresh(double time)
{
camera2Animation1Instance1.RefreshControllers();
camera2Draw1Instance1.RefreshControllers();
GL.Clear(ClearBufferMask.DepthBufferBit);
scene.Simulate(time);
scene.Draw(time);
if (demo.EnableMenu)
{
GL.Clear(ClearBufferMask.DepthBufferBit);
demo.MenuScene.PhysicsScene.Draw(time);
}
demo.SwapBuffers();
}
public void Remove()
{
string sceneInstanceIndexName = name + instanceIndexName;
if (demo.Engine.Factory.PhysicsSceneManager.Find(sceneInstanceIndexName) != null)
demo.Engine.Factory.PhysicsSceneManager.Remove(sceneInstanceIndexName);
}
public void CreateResources()
{
}
public void DisposeResources()
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;
using MyCompany.Visitors.Client.DocumentResponse;
using MyCompany.Visitors.Client.Model;
using MyCompany.Visitors.Client.ViewModel.Base;
#if __IOS__
using MyCompany.Visitors.Client.DocumentResponse;
#endif
namespace MyCompany.Visitors.Client.ViewModels
{
public class VMMainPage : VMBase
{
public static VMMainPage MainPage;
const int ITEMS_TO_RETRIEVE_PAGEZERO = 0;
const int ITEMS_TO_RETRIEVE_TODAY = 1000;
const int ITEMS_TO_RETRIEVE_OTHER = 12;
const int ITEMS_TO_RETRIEVE_LIVETILE = 5;
const int TODAY_GROUP_ID = 1;
const int OTHER_GROUP_ID = 2;
IMyCompanyClient clientService
{
get {
#if __IOS__
return MyCompany.Visitors.Client.iOS.AppDelegate.CompanyClient;
#else
return MyCompany.Visitors.Client.Droid.Activity1.CompanyClient;
#endif
}
}
HubConnection hubConnection;
VMVisit nextVisit;
int numberOfLoads;
int otherVisitsCount;
string otherVisitsHeader;
ObservableCollection<VMVisit> othersVisits;
bool showOtherVisits = true;
bool showSplashLoading = false;
bool showTodayVisits = true;
ObservableCollection<VMVisit> todayVisits;
int todayVisitsCount;
string todayVisitsHeader;
ObservableCollection<VisitsGroup> visits;
ObservableCollection<VMEmployee> employees;
ObservableCollection<VMVisitor> visitors;
/// <summary>
/// Default constructor.
/// </summary>
public VMMainPage()
{
MainPage = this;
InitializeNotifications();
}
/// <summary>
/// Visits List.
/// </summary>
public ObservableCollection<VisitsGroup> VisitsList
{
get { return visits; }
set
{
visits = value;
RaisePropertyChanged(() => VisitsList);
}
}
public ObservableCollection<VMEmployee> Employees
{
get { return employees; }
set
{
employees = value;
RaisePropertyChanged(() => Employees);
}
}
public ObservableCollection<VMVisitor> Visitors
{
get { return visitors; }
set
{
visitors = value;
RaisePropertyChanged(() => Visitors);
}
}
/// <summary>
/// Today next visit
/// </summary>
public VMVisit NextVisit
{
get { return nextVisit; }
set
{
if (nextVisit == value)
return;
nextVisit = value;
base.RaisePropertyChanged(() => NextVisit);
}
}
/// <summary>
/// Today visits
/// </summary>
public ObservableCollection<VMVisit> TodayVisits
{
get { return todayVisits; }
set
{
if (todayVisits == value)
return;
todayVisits = value;
base.RaisePropertyChanged(() => TodayVisits);
}
}
/// <summary>
/// Today visits
/// </summary>
public ObservableCollection<VMVisit> OtherVisits
{
get { return othersVisits; }
set
{
othersVisits = value;
base.RaisePropertyChanged(() => OtherVisits);
}
}
/// <summary>
/// This property is true if there are no visits the other days, false otherwise.
/// </summary>
public bool ShowOtherVisits
{
get { return showOtherVisits; }
set
{
showOtherVisits = value;
base.RaisePropertyChanged(() => ShowOtherVisits);
}
}
/// <summary>
/// This property is true if there are no visits today, false otherwise.
/// </summary>
public bool ShowTodayVisits
{
get { return showTodayVisits; }
set
{
showTodayVisits = value;
base.RaisePropertyChanged(() => ShowTodayVisits);
}
}
/// <summary>
/// This property is true if there isn't any visit to show.
/// </summary>
public bool ShowNextVisit
{
get { return !(!showTodayVisits && !showOtherVisits); }
}
/// <summary>
/// Today visits count.
/// </summary>
public int TodayVisitsCount
{
get { return todayVisitsCount; }
set
{
todayVisitsCount = value;
base.RaisePropertyChanged(() => TodayVisitsCount);
base.RaisePropertyChanged(() => TodayVisitsHeader);
}
}
/// <summary>
/// Other visits count
/// </summary>
public int OtherVisitsCount
{
get { return otherVisitsCount; }
set
{
otherVisitsCount = value;
base.RaisePropertyChanged(() => OtherVisitsCount);
base.RaisePropertyChanged(() => OtherVisitsHeader);
}
}
/// <summary>
/// Hub today visits header
/// </summary>
public string TodayVisitsHeader
{
get
{
todayVisitsHeader = string.Format("Today visits ({0})", TodayVisitsCount);
return todayVisitsHeader;
}
}
/// <summary>
/// Hub other visits header
/// </summary>
public string OtherVisitsHeader
{
get
{
otherVisitsHeader = "Other Visits";
return otherVisitsHeader;
}
}
/// <summary>
/// Hub next visit header
/// </summary>
public string NextVisitHeader
{
get { return "Next Visit"; }
}
/// <summary>
/// Initialize Data method.
/// </summary>
/// <returns></returns>
public async Task InitializeData()
{
try
{
if (numberOfLoads >= 0)
IsBusy = true;
VisitsList = new ObservableCollection<VisitsGroup>();
TodayVisits = new ObservableCollection<VMVisit>();
OtherVisits = new ObservableCollection<VMVisit>();
Employees = new ObservableCollection<VMEmployee>();
Visitors = new ObservableCollection<VMVisitor>();
// Today visits.
int todayItems = await GetTodayVisits();
// Other visits.
int otherItems = await GetOtherVisits();
int visitors = await GetVisitors();
int employeItems = await GetEmployees();
// Update next visit visibility.
RaisePropertyChanged(() => ShowNextVisit);
// Update the Tiles.
await UpdateLiveTileData();
CreateVisitsGroup(todayItems, otherItems);
numberOfLoads++;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
IsBusy = false;
}
}
/// <summary>
/// Dispose method.
/// </summary>
/// <param name="dispose"></param>
protected override void Dispose(bool dispose)
{
MessengerInstance.Unregister(this);
}
void CreateVisitsGroup(int todayItems, int otherItems)
{
if (todayItems > 0)
{
VisitsList.Add(new VisitsGroup
{
GroupId = TODAY_GROUP_ID,
GroupName = "Todays Visits",
Items = new ObservableCollection<VMVisit>(TodayVisits)
});
}
if (otherItems > 0)
{
VisitsList.Add(new VisitsGroup
{
GroupId = OTHER_GROUP_ID,
GroupName = "Other Visits",
Items = new ObservableCollection<VMVisit>(OtherVisits)
});
}
RaisePropertyChanged(() => VisitsList);
}
/// <summary>
/// Get the three next today's visits.
/// </summary>
/// <returns></returns>
async Task<int> GetTodayVisits()
{
DateTime fromDate = DateTime.Now.AddHours(-1).ToUniversalTime();
DateTime toDate = DateTime.Today.AddDays(1).ToUniversalTime();
IList<Visit> todayResults =
await
clientService.VisitService.GetVisits(string.Empty, PictureType.All, ITEMS_TO_RETRIEVE_TODAY,
ITEMS_TO_RETRIEVE_PAGEZERO, fromDate, toDate);
//int todayItems = await this.clientService.VisitService.GetCount(string.Empty, fromDate, toDate);
TodayVisits = new ObservableCollection<VMVisit>(todayResults.Select(v => new VMVisit(v, TODAY_GROUP_ID)));
int todayItems = 3;
var nextVisit = TodayVisits.FirstOrDefault(v => v.VisitDate >= fromDate);
NextVisit = nextVisit ?? null;
ShowTodayVisits = todayResults.Any();
TodayVisitsCount = todayItems;
return todayItems;
}
/// <summary>
/// This method get the 9 first visits others than today visits.
/// </summary>
/// <returns></returns>
async Task<int> GetOtherVisits()
{
IList<Visit> otherResults =
await
clientService.VisitService.GetVisitsFromDate(string.Empty, PictureType.Small, ITEMS_TO_RETRIEVE_OTHER,
ITEMS_TO_RETRIEVE_PAGEZERO, DateTime.Today.AddDays(1).ToUniversalTime());
//int otherItems = await this.clientService.VisitService.GetCountFromDate(string.Empty, DateTime.Today.AddDays(1).ToUniversalTime());
int otherItems = 35;
ShowOtherVisits = otherResults.Any();
OtherVisits = new ObservableCollection<VMVisit>(otherResults.Select(v => new VMVisit(v, OTHER_GROUP_ID)));
if (otherResults.Any() && NextVisit == null)
{
// Set the next visit of another day.
int id = otherResults.First().VisitId;
Visit nextVisit = await clientService.VisitService.Get(id, PictureType.Big);
NextVisit = new VMVisit(nextVisit, TODAY_GROUP_ID);
}
OtherVisitsCount = otherItems;
return otherItems;
}
async Task<int> GetEmployees()
{
try
{
IList<Employee> results = await this.clientService.EmployeeService.GetEmployees("", PictureType.Small, 30, 0);
if (results != null)
Employees = new ObservableCollection<VMEmployee>(results.Select(x => new VMEmployee{Employee = x}));
return employees.Count;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return 0;
}
}
async Task<int> GetVisitors()
{
IList<Visitor> results = await this.clientService.VisitorService.GetVisitors("", PictureType.Small, 100, 0);
if (results != null)
Visitors = new ObservableCollection<VMVisitor>(results.Select(x => new VMVisitor {Visitor = x}));
return Visitors.Count;
}
public async Task<bool> Save(VMVisit vmVisit)
{
try
{
var visit = new Visit
{
VisitId = vmVisit.VisitId,
EmployeeId = vmVisit.Employee.EmployeeId,
VisitorId = vmVisit.VisitorId,
VisitDateTime = vmVisit.VisitDate,
Comments = vmVisit.Comment,
HasCar = vmVisit.HasCar,
Plate = vmVisit.Plate,
};
if (visit.VisitId > 0)
{
await this.clientService.VisitService.Update(visit);
return true;
}
var result = await this.clientService.VisitService.Add(visit);
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception);
return false;
}
}
bool isConnected;
void InitializeNotifications()
{
try
{
//signalr notifications
hubConnection = new HubConnection(AppSettings.ApiUri.ToString(), new Dictionary<string, string>
{
{"isNoAuth", AppSettings.TestMode.ToString()}
});
if (!AppSettings.TestMode)
hubConnection.Headers.Add("Authorization", AppSettings.SecurityToken);
IHubProxy hubProxy = hubConnection.CreateHubProxy("VisitorsNotificationHub");
hubProxy.On<Visit>("notifyVisitAdded", OnVisitAdded);
hubProxy.On<Visit>("notifyVisitArrived", OnVisitArrived);
hubProxy.On<ICollection<VisitorPicture>>("notifyVisitorPicturesChanged", OnVisitorPicturesChanged);
hubConnection.Start().ContinueWith(
task =>
{
if (task.IsCompleted)
{
}
});
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
async void OnVisitArrived(Visit visit)
{
bool hasArrived = visit.Status == VisitStatus.Arrived;
int visitorId = visit.VisitorId;
IEnumerable<VMVisit> visitsWithChangedVisitor;
foreach (VisitsGroup visitGroup in VisitsList)
{
visitsWithChangedVisitor = visitGroup.Items.Where(v => v.VisitorId == visitorId);
foreach (VMVisit v in visitsWithChangedVisitor)
{
v.HasArrived = hasArrived;
}
}
//base.RaisePropertyChanged(() => VisitsList);
visitsWithChangedVisitor = OtherVisits.Where(v => v.VisitorId == visitorId);
if (visitsWithChangedVisitor.Any())
{
foreach (VMVisit v in visitsWithChangedVisitor)
{
v.HasArrived = hasArrived;
}
//base.RaisePropertyChanged(() => OtherVisits);
}
visitsWithChangedVisitor = TodayVisits.Where(v => v.VisitorId == visitorId);
if (visitsWithChangedVisitor.Any())
{
foreach (VMVisit v in visitsWithChangedVisitor)
{
v.HasArrived = hasArrived;
}
//base.RaisePropertyChanged(() => TodayVisits);
}
if (NextVisit.VisitorId == visitorId)
{
NextVisit.HasArrived = hasArrived;// .ChangePhotos(visitorPictures);
//base.RaisePropertyChanged(() => NextVisit);
}
}
async void OnVisitAdded(Visit visit)
{
//await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
bool isNext = NextVisit == null || visit.VisitDateTime < NextVisit.VisitDate;
bool isToday = visit.VisitDateTime.ToLocalTime().Date == DateTime.Now.Date;
ObservableCollection<VMVisit> list = isToday ? TodayVisits : OtherVisits;
int maxNumberOfItems = isToday ? ITEMS_TO_RETRIEVE_TODAY : ITEMS_TO_RETRIEVE_OTHER;
int visitGroup = isToday ? TODAY_GROUP_ID : OTHER_GROUP_ID;
var VMVisit = new VMVisit(visit, visitGroup);
VMVisit previousVisit = list.LastOrDefault(v => v.VisitDate < VMVisit.VisitDate);
int visitIndex = previousVisit == null ? 0 : list.IndexOf(previousVisit) + 1;
bool hasToBeAdded = visitIndex <= list.Count;
bool needToRemoveLast = list.Count() == maxNumberOfItems;
if (isNext)
NextVisit = VMVisit;
if (hasToBeAdded)
{
list.Insert(visitIndex, VMVisit);
}
if (needToRemoveLast)
{
list.Remove(list.Last());
}
if (isToday)
{
ShowTodayVisits = true;
TodayVisitsCount++;
}
else
{
ShowOtherVisits = true;
OtherVisitsCount++;
}
RaisePropertyChanged(() => ShowNextVisit);
}
//);
}
async Task UpdateLiveTileData()
{
if (!IsInDesignMode)
{
IList<Visit> visitsToShowInTile =
await
clientService.VisitService.GetVisitsFromDate(string.Empty, PictureType.Small, ITEMS_TO_RETRIEVE_LIVETILE,
ITEMS_TO_RETRIEVE_PAGEZERO, DateTime.Now.ToUniversalTime());
//this.tilesService.UpdateMainTile(visitsToShowInTile);
}
}
async void OnVisitorPicturesChanged(ICollection<VisitorPicture> visitorPictures)
{
//await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
int visitorId = visitorPictures.First().VisitorId;
IEnumerable<VMVisit> visitsWithChangedVisitor;
foreach (VisitsGroup visitGroup in VisitsList)
{
visitsWithChangedVisitor = visitGroup.Items.Where(v => v.VisitorId == visitorId);
foreach (VMVisit visit in visitsWithChangedVisitor)
{
visit.ChangePhotos(visitorPictures);
}
}
//base.RaisePropertyChanged(() => VisitsList);
visitsWithChangedVisitor = OtherVisits.Where(v => v.VisitorId == visitorId);
if (visitsWithChangedVisitor.Any())
{
foreach (VMVisit visit in visitsWithChangedVisitor)
{
visit.ChangePhotos(visitorPictures);
}
//base.RaisePropertyChanged(() => OtherVisits);
}
visitsWithChangedVisitor = TodayVisits.Where(v => v.VisitorId == visitorId);
if (visitsWithChangedVisitor.Any())
{
foreach (VMVisit visit in visitsWithChangedVisitor)
{
visit.ChangePhotos(visitorPictures);
}
//base.RaisePropertyChanged(() => TodayVisits);
}
if (NextVisit.VisitorId == visitorId)
{
NextVisit.ChangePhotos(visitorPictures);
//base.RaisePropertyChanged(() => NextVisit);
}
foreach (var vmVisitor in visitors.Where(x=> x.Visitor.VisitorId == visitorId))
{
vmVisitor.ChangePhotos(visitorPictures);
}
} //);
}
}
}
| |
using System;
using System.Text;
/// <summary>
/// Encoding.GetChars(Byte[],Int32,Int32)
/// </summary>
public class EncodingGetChars2
{
public static int Main()
{
EncodingGetChars2 enGetChars2 = new EncodingGetChars2();
TestLibrary.TestFramework.BeginTestCase("EncodingGetChars2");
if (enGetChars2.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the GetChars method 1");
try
{
byte[] bytes = new byte[0];
Encoding myEncode = Encoding.GetEncoding("utf-16");
int startIndex = 0;
int count = 0;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
if (charsVal.Length != 0)
{
TestLibrary.TestFramework.LogError("001", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the GetChars method 2");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int startIndex = 0;
int count = 0;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
if (charsVal.Length != 0)
{
TestLibrary.TestFramework.LogError("003", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the GetChars method 3");
try
{
string myStr = "za\u0306\u01fd\u03b2";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int startIndex = 0;
int count = bytes.Length;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
string strVal = new string(charsVal);
if (strVal != myStr)
{
TestLibrary.TestFramework.LogError("005", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The byte array is null");
try
{
byte[] bytes = null;
Encoding myEncode = Encoding.GetEncoding("utf-16");
int startIndex = 0;
int count = 0;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
TestLibrary.TestFramework.LogError("N001", "the byte array is null but not throw exception");
retVal = false;
}
catch (ArgumentNullException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2:The startIndex is less than zero");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int startIndex = -1;
int count = myStr.Length;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
TestLibrary.TestFramework.LogError("N003", "the startIndex is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3:The count is less than zero");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int startIndex = 0;
int count = -1;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
TestLibrary.TestFramework.LogError("N005", "the count is less than zero but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4:The startIndex and count do not denote a valid range of bytes");
try
{
string myStr = "helloworld";
Encoding myEncode = Encoding.GetEncoding("utf-16");
byte[] bytes = myEncode.GetBytes(myStr);
int startIndex = 0;
int count = bytes.Length + 1;
char[] charsVal = myEncode.GetChars(bytes, startIndex, count);
TestLibrary.TestFramework.LogError("N007", "The startIndex and count do not denote a valid range of bytes but not throw exception");
retVal = false;
}
catch (ArgumentOutOfRangeException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
namespace Unity.Appodeal.Xcode
{
public class JsonElement
{
protected JsonElement() {}
// convenience methods
public string AsString() { return ((JsonElementString)this).value; }
public int AsInteger() { return ((JsonElementInteger)this).value; }
public bool AsBoolean() { return ((JsonElementBoolean)this).value; }
public JsonElementArray AsArray() { return (JsonElementArray)this; }
public JsonElementDict AsDict() { return (JsonElementDict)this; }
public JsonElement this[string key]
{
get { return AsDict()[key]; }
set { AsDict()[key] = value; }
}
}
public class JsonElementString : JsonElement
{
public JsonElementString(string v) { value = v; }
public string value;
}
public class JsonElementInteger : JsonElement
{
public JsonElementInteger(int v) { value = v; }
public int value;
}
public class JsonElementBoolean : JsonElement
{
public JsonElementBoolean(bool v) { value = v; }
public bool value;
}
public class JsonElementDict : JsonElement
{
public JsonElementDict() : base() {}
private SortedDictionary<string, JsonElement> m_PrivateValue = new SortedDictionary<string, JsonElement>();
public IDictionary<string, JsonElement> values { get { return m_PrivateValue; }}
new public JsonElement this[string key]
{
get {
if (values.ContainsKey(key))
return values[key];
return null;
}
set { this.values[key] = value; }
}
public bool Contains(string key)
{
return values.ContainsKey(key);
}
public void Remove(string key)
{
values.Remove(key);
}
// convenience methods
public void SetInteger(string key, int val)
{
values[key] = new JsonElementInteger(val);
}
public void SetString(string key, string val)
{
values[key] = new JsonElementString(val);
}
public void SetBoolean(string key, bool val)
{
values[key] = new JsonElementBoolean(val);
}
public JsonElementArray CreateArray(string key)
{
var v = new JsonElementArray();
values[key] = v;
return v;
}
public JsonElementDict CreateDict(string key)
{
var v = new JsonElementDict();
values[key] = v;
return v;
}
}
public class JsonElementArray : JsonElement
{
public JsonElementArray() : base() {}
public List<JsonElement> values = new List<JsonElement>();
// convenience methods
public void AddString(string val)
{
values.Add(new JsonElementString(val));
}
public void AddInteger(int val)
{
values.Add(new JsonElementInteger(val));
}
public void AddBoolean(bool val)
{
values.Add(new JsonElementBoolean(val));
}
public JsonElementArray AddArray()
{
var v = new JsonElementArray();
values.Add(v);
return v;
}
public JsonElementDict AddDict()
{
var v = new JsonElementDict();
values.Add(v);
return v;
}
}
public class JsonDocument
{
public JsonElementDict root;
public string indentString = " ";
public JsonDocument()
{
root = new JsonElementDict();
}
void AppendIndent(StringBuilder sb, int indent)
{
for (int i = 0; i < indent; ++i)
sb.Append(indentString);
}
void WriteString(StringBuilder sb, string str)
{
// TODO: escape
sb.Append('"');
sb.Append(str);
sb.Append('"');
}
void WriteBoolean(StringBuilder sb, bool value)
{
sb.Append(value ? "true" : "false");
}
void WriteInteger(StringBuilder sb, int value)
{
sb.Append(value.ToString());
}
void WriteDictKeyValue(StringBuilder sb, string key, JsonElement value, int indent)
{
sb.Append("\n");
AppendIndent(sb, indent);
WriteString(sb, key);
sb.Append(" : ");
if (value is JsonElementString)
WriteString(sb, value.AsString());
else if (value is JsonElementInteger)
WriteInteger(sb, value.AsInteger());
else if (value is JsonElementBoolean)
WriteBoolean(sb, value.AsBoolean());
else if (value is JsonElementDict)
WriteDict(sb, value.AsDict(), indent);
else if (value is JsonElementArray)
WriteArray(sb, value.AsArray(), indent);
}
void WriteDict(StringBuilder sb, JsonElementDict el, int indent)
{
sb.Append("{");
bool hasElement = false;
foreach (var key in el.values.Keys)
{
if (hasElement)
sb.Append(","); // trailing commas not supported
WriteDictKeyValue(sb, key, el[key], indent+1);
hasElement = true;
}
sb.Append("\n");
AppendIndent(sb, indent);
sb.Append("}");
}
void WriteArray(StringBuilder sb, JsonElementArray el, int indent)
{
sb.Append("[");
bool hasElement = false;
foreach (var value in el.values)
{
if (hasElement)
sb.Append(","); // trailing commas not supported
sb.Append("\n");
AppendIndent(sb, indent+1);
if (value is JsonElementString)
WriteString(sb, value.AsString());
else if (value is JsonElementInteger)
WriteInteger(sb, value.AsInteger());
else if (value is JsonElementBoolean)
WriteBoolean(sb, value.AsBoolean());
else if (value is JsonElementDict)
WriteDict(sb, value.AsDict(), indent+1);
else if (value is JsonElementArray)
WriteArray(sb, value.AsArray(), indent+1);
hasElement = true;
}
sb.Append("\n");
AppendIndent(sb, indent);
sb.Append("]");
}
public void WriteToFile(string path)
{
File.WriteAllText(path, WriteToString());
}
public void WriteToStream(TextWriter tw)
{
tw.Write(WriteToString());
}
public string WriteToString()
{
var sb = new StringBuilder();
WriteDict(sb, root, 0);
return sb.ToString();
}
}
} // namespace Unity.Appodeal.Xcode
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Utility.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Utility\Invoke-WebRequest command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class InvokeWebRequest : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public InvokeWebRequest()
{
this.DisplayName = "Invoke-WebRequest";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Utility\\Invoke-WebRequest"; } }
// Arguments
/// <summary>
/// Provides access to the UseBasicParsing parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseBasicParsing { get; set; }
/// <summary>
/// Provides access to the Uri parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> Uri { get; set; }
/// <summary>
/// Provides access to the WebSession parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.PowerShell.Commands.WebRequestSession> WebSession { get; set; }
/// <summary>
/// Provides access to the SessionVariable parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> SessionVariable { get; set; }
/// <summary>
/// Provides access to the Credential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> Credential { get; set; }
/// <summary>
/// Provides access to the UseDefaultCredentials parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseDefaultCredentials { get; set; }
/// <summary>
/// Provides access to the CertificateThumbprint parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> CertificateThumbprint { get; set; }
/// <summary>
/// Provides access to the Certificate parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Security.Cryptography.X509Certificates.X509Certificate> Certificate { get; set; }
/// <summary>
/// Provides access to the UserAgent parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> UserAgent { get; set; }
/// <summary>
/// Provides access to the DisableKeepAlive parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> DisableKeepAlive { get; set; }
/// <summary>
/// Provides access to the TimeoutSec parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> TimeoutSec { get; set; }
/// <summary>
/// Provides access to the Headers parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Collections.IDictionary> Headers { get; set; }
/// <summary>
/// Provides access to the MaximumRedirection parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Int32> MaximumRedirection { get; set; }
/// <summary>
/// Provides access to the Method parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<Microsoft.PowerShell.Commands.WebRequestMethod> Method { get; set; }
/// <summary>
/// Provides access to the Proxy parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Uri> Proxy { get; set; }
/// <summary>
/// Provides access to the ProxyCredential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> ProxyCredential { get; set; }
/// <summary>
/// Provides access to the ProxyUseDefaultCredentials parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> ProxyUseDefaultCredentials { get; set; }
/// <summary>
/// Provides access to the Body parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Object> Body { get; set; }
/// <summary>
/// Provides access to the ContentType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ContentType { get; set; }
/// <summary>
/// Provides access to the TransferEncoding parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> TransferEncoding { get; set; }
/// <summary>
/// Provides access to the InFile parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> InFile { get; set; }
/// <summary>
/// Provides access to the OutFile parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> OutFile { get; set; }
/// <summary>
/// Provides access to the PassThru parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> PassThru { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(UseBasicParsing.Expression != null)
{
targetCommand.AddParameter("UseBasicParsing", UseBasicParsing.Get(context));
}
if(Uri.Expression != null)
{
targetCommand.AddParameter("Uri", Uri.Get(context));
}
if(WebSession.Expression != null)
{
targetCommand.AddParameter("WebSession", WebSession.Get(context));
}
if(SessionVariable.Expression != null)
{
targetCommand.AddParameter("SessionVariable", SessionVariable.Get(context));
}
if(Credential.Expression != null)
{
targetCommand.AddParameter("Credential", Credential.Get(context));
}
if(UseDefaultCredentials.Expression != null)
{
targetCommand.AddParameter("UseDefaultCredentials", UseDefaultCredentials.Get(context));
}
if(CertificateThumbprint.Expression != null)
{
targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
}
if(Certificate.Expression != null)
{
targetCommand.AddParameter("Certificate", Certificate.Get(context));
}
if(UserAgent.Expression != null)
{
targetCommand.AddParameter("UserAgent", UserAgent.Get(context));
}
if(DisableKeepAlive.Expression != null)
{
targetCommand.AddParameter("DisableKeepAlive", DisableKeepAlive.Get(context));
}
if(TimeoutSec.Expression != null)
{
targetCommand.AddParameter("TimeoutSec", TimeoutSec.Get(context));
}
if(Headers.Expression != null)
{
targetCommand.AddParameter("Headers", Headers.Get(context));
}
if(MaximumRedirection.Expression != null)
{
targetCommand.AddParameter("MaximumRedirection", MaximumRedirection.Get(context));
}
if(Method.Expression != null)
{
targetCommand.AddParameter("Method", Method.Get(context));
}
if(Proxy.Expression != null)
{
targetCommand.AddParameter("Proxy", Proxy.Get(context));
}
if(ProxyCredential.Expression != null)
{
targetCommand.AddParameter("ProxyCredential", ProxyCredential.Get(context));
}
if(ProxyUseDefaultCredentials.Expression != null)
{
targetCommand.AddParameter("ProxyUseDefaultCredentials", ProxyUseDefaultCredentials.Get(context));
}
if(Body.Expression != null)
{
targetCommand.AddParameter("Body", Body.Get(context));
}
if(ContentType.Expression != null)
{
targetCommand.AddParameter("ContentType", ContentType.Get(context));
}
if(TransferEncoding.Expression != null)
{
targetCommand.AddParameter("TransferEncoding", TransferEncoding.Get(context));
}
if(InFile.Expression != null)
{
targetCommand.AddParameter("InFile", InFile.Get(context));
}
if(OutFile.Expression != null)
{
targetCommand.AddParameter("OutFile", OutFile.Get(context));
}
if(PassThru.Expression != null)
{
targetCommand.AddParameter("PassThru", PassThru.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using Newtonsoft.Json.Linq;
namespace PlaylistTranslate
{
public class Track
{
public static readonly String[] Formats = new[] {
".mp3", ".m4a", ".wma", ".flac", ".wav", ".ogg", ".aac"
};
public String Title { get; private set; }
public int Length { get; private set; }
public String Artist { get; private set; }
public String Album { get; private set; }
public String Path { get; set; }
public Track(JObject obj)
{
Title = (String) obj["title"];
Length = (int) obj["length"];
Artist = (String) obj["artist"];
Album = (String) obj["album"];
Path = null;
}
internal bool DiscoverPath(AlbumDirectory[] albums)
{
if (albums.Length == 0) return false;
const float margin = 0.125f;
var albumLower = Album.ToLower();
var scores = albums.Select(x => new {
album = x,
score = x.Name.Levenshtein(albumLower)
}).OrderBy(x => x.score).Take(2).ToArray();
var bestAlbum = scores[0];
var goodmatch = true;
var trackFormats = new[] {
Title.ToLower(),
String.Format("{0} - {1}", Artist, Title).ToLower()
};
if (albums.Length > 1) {
var next = scores[1];
if (bestAlbum.score > 1 && (next.score - bestAlbum.score) <= albumLower.Length * margin) {
goodmatch = false;
bestAlbum = albums.Select(x => new {
album = x,
score = x.Tracks.Min(y => trackFormats.Min(z => y.Name.Levenshtein(z)))
}).OrderBy(x => x.score).First();
}
}
var tracks = bestAlbum.album.Tracks.Select(x => new {
track = x,
score = trackFormats.Min(y => x.Name.Levenshtein(y))
}).OrderBy(x => x.score).Take(2).ToArray();
var bestTrack = tracks[0];
if (tracks.Length > 1) {
var next = tracks[1];
if ((next.score - bestTrack.score) <= bestTrack.track.Name.Length * margin) {
goodmatch = false;
}
}
Path = bestTrack.track.Location;
return goodmatch;
}
}
public class AlbumDirectory
{
public String Name { get; private set; }
public String Location { get; private set; }
public TrackFile[] Tracks { get; private set; }
public AlbumDirectory(String path)
{
Name = Path.GetFileName(path).ToLower();
Location = path;
Tracks = Directory.GetFiles(path)
.Where(x => Track.Formats.Contains(Path.GetExtension(x).ToLower()))
.Select(x => new TrackFile(x))
.ToArray();
}
}
public class TrackFile
{
public String Name { get; private set; }
public String Location { get; private set; }
public TrackFile(String path)
{
Name = Path.GetFileNameWithoutExtension(path).ToLower();
Location = path;
}
}
public class Playlist : IEnumerable<Track>
{
public static Playlist Parse(String json)
{
return new Playlist(JArray.Parse(json));
}
private Track[] _tracks;
public int TrackCount { get { return _tracks.Length; } }
public int TotalLength { get { return _tracks.Sum(x => x.Length); } }
private Playlist(JArray array)
{
_tracks = new Track[array.Count];
for (var i = 0; i < _tracks.Length; ++i) {
_tracks[i] = new Track((JObject) array[i]);
}
}
public IEnumerable<Track> DiscoverPaths(IEnumerable<String> roots)
{
var albums = roots
.SelectMany(x => Directory.GetDirectories(x))
.Select(x => new AlbumDirectory(x))
.ToArray();
var unsure = new List<Track>();
foreach (var track in this) {
if (!track.DiscoverPath(albums)) {
unsure.Add(track);
}
}
return unsure;
}
public void Export(String path, Format format)
{
using (var stream = File.Create(path)) {
switch (format) {
case Format.XSPF:
ExportXSPF(stream);
return;
}
}
}
private void ExportXSPF(Stream stream)
{
using (var writer = new StreamWriter(stream)) {
writer.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
writer.WriteLine("<playlist version=\"1\" xmlns=\"http://xspf.org/ns/0/\">");
writer.WriteLine(" <title>Unnamed</title>");
writer.WriteLine(" <date>{0}</date>", DateTime.UtcNow.ToString("o"));
writer.WriteLine(" <trackList>");
foreach (var track in this) {
writer.WriteLine(" <track>");
writer.WriteLine(" <title>{0}</title>", HttpUtility.HtmlEncode(track.Title));
writer.WriteLine(" <creator>{0}</creator>", HttpUtility.HtmlEncode(track.Artist));
writer.WriteLine(" <album>{0}</album>", HttpUtility.HtmlEncode(track.Album));
writer.WriteLine(" <duration>{0}</duration>", track.Length * 1000);
writer.WriteLine(" <location>{0}</location>",
HttpUtility.UrlEncode(track.Path)
.Replace("+", "%20")
.Replace("%2f", "/"));
writer.WriteLine(" </track>");
}
writer.WriteLine(" </trackList>");
writer.WriteLine("</playlist>");
}
}
public IEnumerator<Track> GetEnumerator()
{
return _tracks.AsEnumerable().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _tracks.GetEnumerator();
}
}
}
| |
#region Copyright
////////////////////////////////////////////////////////////////////////////////
// The following FIT Protocol software provided may be used with FIT protocol
// devices only and remains the copyrighted property of Dynastream Innovations Inc.
// The software is being provided on an "as-is" basis and as an accommodation,
// and therefore all warranties, representations, or guarantees of any kind
// (whether express, implied or statutory) including, without limitation,
// warranties of merchantability, non-infringement, or fitness for a particular
// purpose, are specifically disclaimed.
//
// Copyright 2015 Dynastream Innovations Inc.
////////////////////////////////////////////////////////////////////////////////
// ****WARNING**** This file is auto-generated! Do NOT edit this file.
// Profile Version = 16.10Release
// Tag = development-akw-16.10.00-0
////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.IO;
namespace Dynastream.Fit
{
/// <summary>
/// Implements the GyroscopeData profile message.
/// </summary>
public class GyroscopeDataMesg : Mesg
{
#region Fields
#endregion
#region Constructors
public GyroscopeDataMesg() : base(Profile.mesgs[Profile.GyroscopeDataIndex])
{
}
public GyroscopeDataMesg(Mesg mesg) : base(mesg)
{
}
#endregion // Constructors
#region Methods
///<summary>
/// Retrieves the Timestamp field
/// Units: s
/// Comment: Whole second part of the timestamp</summary>
/// <returns>Returns DateTime representing the Timestamp field</returns>
public DateTime GetTimestamp()
{
return TimestampToDateTime((uint?)GetFieldValue(253, 0, Fit.SubfieldIndexMainField));
}
/// <summary>
/// Set Timestamp field
/// Units: s
/// Comment: Whole second part of the timestamp</summary>
/// <param name="timestamp_">Nullable field value to be set</param>
public void SetTimestamp(DateTime timestamp_)
{
SetFieldValue(253, 0, timestamp_.GetTimeStamp(), Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the TimestampMs field
/// Units: ms
/// Comment: Millisecond part of the timestamp.</summary>
/// <returns>Returns nullable ushort representing the TimestampMs field</returns>
public ushort? GetTimestampMs()
{
return (ushort?)GetFieldValue(0, 0, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set TimestampMs field
/// Units: ms
/// Comment: Millisecond part of the timestamp.</summary>
/// <param name="timestampMs_">Nullable field value to be set</param>
public void SetTimestampMs(ushort? timestampMs_)
{
SetFieldValue(0, 0, timestampMs_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field SampleTimeOffset</returns>
public int GetNumSampleTimeOffset()
{
return GetNumFieldValues(1, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the SampleTimeOffset field
/// Units: ms
/// Comment: Each time in the array describes the time at which the gyro sample with the corrosponding index was taken. Limited to 30 samples in each message. The samples may span across seconds. Array size must match the number of samples in gyro_x and gyro_y and gyro_z</summary>
/// <param name="index">0 based index of SampleTimeOffset element to retrieve</param>
/// <returns>Returns nullable ushort representing the SampleTimeOffset field</returns>
public ushort? GetSampleTimeOffset(int index)
{
return (ushort?)GetFieldValue(1, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set SampleTimeOffset field
/// Units: ms
/// Comment: Each time in the array describes the time at which the gyro sample with the corrosponding index was taken. Limited to 30 samples in each message. The samples may span across seconds. Array size must match the number of samples in gyro_x and gyro_y and gyro_z</summary>
/// <param name="index">0 based index of sample_time_offset</param>
/// <param name="sampleTimeOffset_">Nullable field value to be set</param>
public void SetSampleTimeOffset(int index, ushort? sampleTimeOffset_)
{
SetFieldValue(1, index, sampleTimeOffset_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field GyroX</returns>
public int GetNumGyroX()
{
return GetNumFieldValues(2, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GyroX field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of GyroX element to retrieve</param>
/// <returns>Returns nullable ushort representing the GyroX field</returns>
public ushort? GetGyroX(int index)
{
return (ushort?)GetFieldValue(2, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set GyroX field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of gyro_x</param>
/// <param name="gyroX_">Nullable field value to be set</param>
public void SetGyroX(int index, ushort? gyroX_)
{
SetFieldValue(2, index, gyroX_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field GyroY</returns>
public int GetNumGyroY()
{
return GetNumFieldValues(3, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GyroY field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of GyroY element to retrieve</param>
/// <returns>Returns nullable ushort representing the GyroY field</returns>
public ushort? GetGyroY(int index)
{
return (ushort?)GetFieldValue(3, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set GyroY field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of gyro_y</param>
/// <param name="gyroY_">Nullable field value to be set</param>
public void SetGyroY(int index, ushort? gyroY_)
{
SetFieldValue(3, index, gyroY_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field GyroZ</returns>
public int GetNumGyroZ()
{
return GetNumFieldValues(4, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the GyroZ field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of GyroZ element to retrieve</param>
/// <returns>Returns nullable ushort representing the GyroZ field</returns>
public ushort? GetGyroZ(int index)
{
return (ushort?)GetFieldValue(4, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set GyroZ field
/// Units: counts
/// Comment: These are the raw ADC reading. Maximum number of samples is 30 in each message. The samples may span across seconds. A conversion will need to be done on this data once read.</summary>
/// <param name="index">0 based index of gyro_z</param>
/// <param name="gyroZ_">Nullable field value to be set</param>
public void SetGyroZ(int index, ushort? gyroZ_)
{
SetFieldValue(4, index, gyroZ_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CalibratedGyroX</returns>
public int GetNumCalibratedGyroX()
{
return GetNumFieldValues(5, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CalibratedGyroX field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of CalibratedGyroX element to retrieve</param>
/// <returns>Returns nullable float representing the CalibratedGyroX field</returns>
public float? GetCalibratedGyroX(int index)
{
return (float?)GetFieldValue(5, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CalibratedGyroX field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of calibrated_gyro_x</param>
/// <param name="calibratedGyroX_">Nullable field value to be set</param>
public void SetCalibratedGyroX(int index, float? calibratedGyroX_)
{
SetFieldValue(5, index, calibratedGyroX_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CalibratedGyroY</returns>
public int GetNumCalibratedGyroY()
{
return GetNumFieldValues(6, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CalibratedGyroY field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of CalibratedGyroY element to retrieve</param>
/// <returns>Returns nullable float representing the CalibratedGyroY field</returns>
public float? GetCalibratedGyroY(int index)
{
return (float?)GetFieldValue(6, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CalibratedGyroY field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of calibrated_gyro_y</param>
/// <param name="calibratedGyroY_">Nullable field value to be set</param>
public void SetCalibratedGyroY(int index, float? calibratedGyroY_)
{
SetFieldValue(6, index, calibratedGyroY_, Fit.SubfieldIndexMainField);
}
/// <summary>
///
/// </summary>
/// <returns>returns number of elements in field CalibratedGyroZ</returns>
public int GetNumCalibratedGyroZ()
{
return GetNumFieldValues(7, Fit.SubfieldIndexMainField);
}
///<summary>
/// Retrieves the CalibratedGyroZ field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of CalibratedGyroZ element to retrieve</param>
/// <returns>Returns nullable float representing the CalibratedGyroZ field</returns>
public float? GetCalibratedGyroZ(int index)
{
return (float?)GetFieldValue(7, index, Fit.SubfieldIndexMainField);
}
/// <summary>
/// Set CalibratedGyroZ field
/// Units: deg/s
/// Comment: Calibrated gyro reading</summary>
/// <param name="index">0 based index of calibrated_gyro_z</param>
/// <param name="calibratedGyroZ_">Nullable field value to be set</param>
public void SetCalibratedGyroZ(int index, float? calibratedGyroZ_)
{
SetFieldValue(7, index, calibratedGyroZ_, Fit.SubfieldIndexMainField);
}
#endregion // Methods
} // Class
} // namespace
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for TaskOperations.
/// </summary>
public static partial class TaskOperationsExtensions
{
/// <summary>
/// Adds a task to the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job to which the task is to be added.
/// </param>
/// <param name='task'>
/// The task to be added.
/// </param>
/// <param name='taskAddOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskAddHeaders Add(this ITaskOperations operations, string jobId, TaskAddParameter task, TaskAddOptions taskAddOptions = default(TaskAddOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).AddAsync(jobId, task, taskAddOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Adds a task to the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job to which the task is to be added.
/// </param>
/// <param name='task'>
/// The task to be added.
/// </param>
/// <param name='taskAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskAddHeaders> AddAsync(this ITaskOperations operations, string jobId, TaskAddParameter task, TaskAddOptions taskAddOptions = default(TaskAddOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddWithHttpMessagesAsync(jobId, task, taskAddOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='taskListOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudTask> List(this ITaskOperations operations, string jobId, TaskListOptions taskListOptions = default(TaskListOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).ListAsync(jobId, taskListOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='taskListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CloudTask>> ListAsync(this ITaskOperations operations, string jobId, TaskListOptions taskListOptions = default(TaskListOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(jobId, taskListOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Adds a collection of tasks to the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job to which the task collection is to be added.
/// </param>
/// <param name='value'>
/// The collection of tasks to add.
/// </param>
/// <param name='taskAddCollectionOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskAddCollectionResult AddCollection(this ITaskOperations operations, string jobId, System.Collections.Generic.IList<TaskAddParameter> value, TaskAddCollectionOptions taskAddCollectionOptions = default(TaskAddCollectionOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).AddCollectionAsync(jobId, value, taskAddCollectionOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Adds a collection of tasks to the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job to which the task collection is to be added.
/// </param>
/// <param name='value'>
/// The collection of tasks to add.
/// </param>
/// <param name='taskAddCollectionOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskAddCollectionResult> AddCollectionAsync(this ITaskOperations operations, string jobId, System.Collections.Generic.IList<TaskAddParameter> value, TaskAddCollectionOptions taskAddCollectionOptions = default(TaskAddCollectionOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddCollectionWithHttpMessagesAsync(jobId, value, taskAddCollectionOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a task from the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job from which to delete the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to delete.
/// </param>
/// <param name='taskDeleteOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskDeleteHeaders Delete(this ITaskOperations operations, string jobId, string taskId, TaskDeleteOptions taskDeleteOptions = default(TaskDeleteOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).DeleteAsync(jobId, taskId, taskDeleteOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a task from the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job from which to delete the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to delete.
/// </param>
/// <param name='taskDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskDeleteHeaders> DeleteAsync(this ITaskOperations operations, string jobId, string taskId, TaskDeleteOptions taskDeleteOptions = default(TaskDeleteOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(jobId, taskId, taskDeleteOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Gets information about the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to get information about.
/// </param>
/// <param name='taskGetOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudTask Get(this ITaskOperations operations, string jobId, string taskId, TaskGetOptions taskGetOptions = default(TaskGetOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).GetAsync(jobId, taskId, taskGetOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets information about the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to get information about.
/// </param>
/// <param name='taskGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CloudTask> GetAsync(this ITaskOperations operations, string jobId, string taskId, TaskGetOptions taskGetOptions = default(TaskGetOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(jobId, taskId, taskGetOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates the properties of the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to update.
/// </param>
/// <param name='constraints'>
/// Constraints that apply to this task. If omitted, the task is given the
/// default constraints.
/// </param>
/// <param name='taskUpdateOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskUpdateHeaders Update(this ITaskOperations operations, string jobId, string taskId, TaskConstraints constraints = default(TaskConstraints), TaskUpdateOptions taskUpdateOptions = default(TaskUpdateOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).UpdateAsync(jobId, taskId, constraints, taskUpdateOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates the properties of the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to update.
/// </param>
/// <param name='constraints'>
/// Constraints that apply to this task. If omitted, the task is given the
/// default constraints.
/// </param>
/// <param name='taskUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskUpdateHeaders> UpdateAsync(this ITaskOperations operations, string jobId, string taskId, TaskConstraints constraints = default(TaskConstraints), TaskUpdateOptions taskUpdateOptions = default(TaskUpdateOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.UpdateWithHttpMessagesAsync(jobId, taskId, constraints, taskUpdateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the subtasks that are associated with the specified
/// multi-instance task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='taskId'>
/// The id of the task.
/// </param>
/// <param name='taskListSubtasksOptions'>
/// Additional parameters for the operation
/// </param>
public static CloudTaskListSubtasksResult ListSubtasks(this ITaskOperations operations, string jobId, string taskId, TaskListSubtasksOptions taskListSubtasksOptions = default(TaskListSubtasksOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).ListSubtasksAsync(jobId, taskId, taskListSubtasksOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the subtasks that are associated with the specified
/// multi-instance task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job.
/// </param>
/// <param name='taskId'>
/// The id of the task.
/// </param>
/// <param name='taskListSubtasksOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CloudTaskListSubtasksResult> ListSubtasksAsync(this ITaskOperations operations, string jobId, string taskId, TaskListSubtasksOptions taskListSubtasksOptions = default(TaskListSubtasksOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListSubtasksWithHttpMessagesAsync(jobId, taskId, taskListSubtasksOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Terminates the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to terminate.
/// </param>
/// <param name='taskTerminateOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskTerminateHeaders Terminate(this ITaskOperations operations, string jobId, string taskId, TaskTerminateOptions taskTerminateOptions = default(TaskTerminateOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).TerminateAsync(jobId, taskId, taskTerminateOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Terminates the specified task.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to terminate.
/// </param>
/// <param name='taskTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskTerminateHeaders> TerminateAsync(this ITaskOperations operations, string jobId, string taskId, TaskTerminateOptions taskTerminateOptions = default(TaskTerminateOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.TerminateWithHttpMessagesAsync(jobId, taskId, taskTerminateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Reactivates the specified task.
/// </summary>
/// <remarks>
/// Reactivation makes a task eligible to be retried again up to its maximum
/// retry count. This will fail for tasks that are not completed or that
/// previously completed successfully (with an exit code of 0). Additionally,
/// this will fail if the job has completed (or is terminating or deleting).
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to reactivate.
/// </param>
/// <param name='taskReactivateOptions'>
/// Additional parameters for the operation
/// </param>
public static TaskReactivateHeaders Reactivate(this ITaskOperations operations, string jobId, string taskId, TaskReactivateOptions taskReactivateOptions = default(TaskReactivateOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).ReactivateAsync(jobId, taskId, taskReactivateOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Reactivates the specified task.
/// </summary>
/// <remarks>
/// Reactivation makes a task eligible to be retried again up to its maximum
/// retry count. This will fail for tasks that are not completed or that
/// previously completed successfully (with an exit code of 0). Additionally,
/// this will fail if the job has completed (or is terminating or deleting).
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='jobId'>
/// The id of the job containing the task.
/// </param>
/// <param name='taskId'>
/// The id of the task to reactivate.
/// </param>
/// <param name='taskReactivateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<TaskReactivateHeaders> ReactivateAsync(this ITaskOperations operations, string jobId, string taskId, TaskReactivateOptions taskReactivateOptions = default(TaskReactivateOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ReactivateWithHttpMessagesAsync(jobId, taskId, taskReactivateOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Headers;
}
}
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='taskListNextOptions'>
/// Additional parameters for the operation
/// </param>
public static Microsoft.Rest.Azure.IPage<CloudTask> ListNext(this ITaskOperations operations, string nextPageLink, TaskListNextOptions taskListNextOptions = default(TaskListNextOptions))
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ITaskOperations)s).ListNextAsync(nextPageLink, taskListNextOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all of the tasks that are associated with the specified job.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='taskListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CloudTask>> ListNextAsync(this ITaskOperations operations, string nextPageLink, TaskListNextOptions taskListNextOptions = default(TaskListNextOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, taskListNextOptions, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using Shouldly;
using StructureMap.Testing.Configuration.DSL;
using StructureMap.Testing.GenericWidgets;
using StructureMap.Testing.Widget;
using StructureMap.Testing.Widget2;
using System;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace StructureMap.Testing.Query
{
public class ModelIntegrationTester
{
public interface IEngine
{
}
public class PushrodEngine : IEngine
{
}
public ModelIntegrationTester()
{
container = new Container(x =>
{
x.For(typeof(IService<>)).Add(typeof(Service<>));
x.For(typeof(IService<>)).Add(typeof(Service2<>));
x.For<IWidget>().Singleton().Use<AWidget>();
x.For<Rule>().AddInstances(o =>
{
o.Type<DefaultRule>();
o.Type<ARule>();
o.Type<ColorRule>().Ctor<string>("color").Is("red");
});
x.For<IEngine>().Use<PushrodEngine>();
x.For<Startable1>().Singleton().Use<Startable1>();
x.For<Startable2>().Use<Startable2>();
x.For<Startable3>().Use<Startable3>();
});
}
private Container container;
[Fact]
public void can_iterate_through_families_including_both_generics_and_normal()
{
// +1 for "IContainer" itself + Func + Lazy + FuncWithArg
container.Model.PluginTypes.Count().ShouldBe(11);
container.Model.PluginTypes.Each(x => Debug.WriteLine(x.PluginType.FullName));
}
[Fact]
public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_from_model()
{
container.Model.InstancesOf<Rule>().Count().ShouldBe(3);
}
[Fact]
public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_that_is_not_registered()
{
container.Model.InstancesOf<IServiceProvider>().Count().ShouldBe(0);
}
[Fact]
public void can_iterate_through_instances_of_pipeline_graph_for_generics()
{
container.Model.For(typeof(IService<>)).Instances.Count().ShouldBe(2);
}
[Fact]
public void can_iterate_through_instances_of_pipeline_graph_for_generics_from_model()
{
container.Model.InstancesOf(typeof(IService<>)).Count().ShouldBe(2);
}
[Fact]
public void default_type_for_from_the_top()
{
container.Model.DefaultTypeFor<IWidget>().ShouldBe(typeof(AWidget));
container.Model.DefaultTypeFor<Rule>().ShouldBeNull();
}
[Fact]
public void get_all_instances_from_the_top()
{
container.Model.AllInstances.Count().ShouldBe(14); // Func/Func+Arg/Lazy are built in
}
[Fact]
public void get_all_possibles()
{
// Startable1 is a SingletonThing
var startable1 = container.GetInstance<Startable1>();
startable1.WasStarted.ShouldBeFalse();
// SAMPLE: calling-startable-start
var allStartables = container.Model.GetAllPossible<IStartable>();
allStartables.ToArray()
.Each(x => x.Start());
// ENDSAMPLE
allStartables.Each(x => x.WasStarted.ShouldBeTrue());
startable1.WasStarted.ShouldBeTrue();
}
[Fact]
public void has_default_implementation_from_the_top()
{
container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue();
container.Model.HasDefaultImplementationFor<Rule>().ShouldBeFalse();
container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse();
}
[Fact]
public void has_implementation_from_the_top()
{
container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse();
container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue();
}
[Fact]
public void has_implementations_should_be_false_for_a_type_that_is_not_registered()
{
container.Model.For<ISomething>().HasImplementations().ShouldBeFalse();
}
[Fact]
public void remove_an_entire_closed_type()
{
container.GetAllInstances<Rule>().Count().ShouldBe(3);
container.Model.EjectAndRemove(typeof(Rule));
container.Model.HasImplementationsFor<Rule>().ShouldBeFalse();
container.TryGetInstance<Rule>().ShouldBeNull();
container.GetAllInstances<Rule>().Count().ShouldBe(0);
}
[Fact]
public void remove_an_entire_closed_type_with_the_filter()
{
container.Model.EjectAndRemovePluginTypes(t => t == typeof(Rule) || t == typeof(IWidget));
container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse();
container.Model.HasImplementationsFor<Rule>().ShouldBeFalse();
container.Model.HasImplementationsFor<IEngine>().ShouldBeTrue();
}
[Fact]
public void remove_an_open_type()
{
container.Model.EjectAndRemove(typeof(IService<>));
container.Model.HasImplementationsFor(typeof(IService<>));
container.TryGetInstance<IService<string>>().ShouldBeNull();
}
[Fact]
public void remove_an_open_type_with_a_filter()
{
container.Model.EjectAndRemovePluginTypes(t => t == typeof(IService<>));
container.Model.HasImplementationsFor(typeof(IService<>));
container.TryGetInstance<IService<string>>().ShouldBeNull();
}
[Fact]
public void remove_types_based_on_a_filter()
{
container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeTrue();
container.Model.HasImplementationsFor<IWidget>().ShouldBeTrue();
container.Model.EjectAndRemoveTypes(t => t == typeof(IWidget) || t == typeof(ARule));
container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeFalse();
container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse();
}
}
// SAMPLE: istartable
public interface IStartable
{
bool WasStarted { get; }
void Start();
}
// ENDSAMPLE
public class Startable : IStartable
{
public void Start()
{
WasStarted = true;
}
public bool WasStarted { get; private set; }
}
public class Startable1 : Startable
{
}
public class Startable2 : Startable
{
}
public class Startable3 : Startable
{
}
}
| |
//
// 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 System.Xml.Linq;
using Hyak.Common;
using Microsoft.WindowsAzure.Management.ExpressRoute;
using Microsoft.WindowsAzure.Management.ExpressRoute.Models;
namespace Microsoft.WindowsAzure.Management.ExpressRoute
{
internal partial class DedicatedCircuitLinkOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitLinkOperations
{
/// <summary>
/// Initializes a new instance of the DedicatedCircuitLinkOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DedicatedCircuitLinkOperations(ExpressRouteManagementClient client)
{
this._client = client;
}
private ExpressRouteManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient.
/// </summary>
public ExpressRouteManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// The New Dedicated Circuit Link operation creates a new dedicated
/// circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required.
/// </param>
/// <param name='vnetName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginNewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (vnetName == null)
{
throw new ArgumentNullException("vnetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("vnetName", vnetName);
TracingAdapter.Enter(invocationId, this, "BeginNewAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/vnets/";
url = url + Uri.EscapeDataString(vnetName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
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.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
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
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Remove Dedicated Circuit Link operation deletes an existing
/// dedicated circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service key representing the dedicated circuit.
/// </param>
/// <param name='vnetName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (vnetName == null)
{
throw new ArgumentNullException("vnetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("vnetName", vnetName);
TracingAdapter.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/vnets/";
url = url + Uri.EscapeDataString(vnetName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
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
ExpressRouteOperationResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationAsyncResponseElement != null)
{
XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Dedicated Circuit Link operation retrieves the specified
/// dedicated circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required. The service key representing the circuit.
/// </param>
/// <param name='vnetName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The Get Dedicated Circuit Link operation response.
/// </returns>
public async Task<DedicatedCircuitLinkGetResponse> GetAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
{
// Validate
if (serviceKey == null)
{
throw new ArgumentNullException("serviceKey");
}
if (vnetName == null)
{
throw new ArgumentNullException("vnetName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("vnetName", vnetName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
url = url + Uri.EscapeDataString(serviceKey);
url = url + "/vnets/";
url = url + Uri.EscapeDataString(vnetName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitLinkGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkGetResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinkElement = responseDoc.Element(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinkElement != null)
{
AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink();
result.DedicatedCircuitLink = dedicatedCircuitLinkInstance;
XElement stateElement = dedicatedCircuitLinkElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true));
dedicatedCircuitLinkInstance.State = stateInstance;
}
XElement vnetNameElement = dedicatedCircuitLinkElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure"));
if (vnetNameElement != null)
{
string vnetNameInstance = vnetNameElement.Value;
dedicatedCircuitLinkInstance.VnetName = vnetNameInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The Get Express Route operation status gets information on the
/// status of Express Route operations in Windows Azure. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx
/// for more information)
/// </summary>
/// <param name='operationId'>
/// Required. The id of the operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken)
{
// Validate
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("operationId", operationId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/operation/";
url = url + Uri.EscapeDataString(operationId);
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
ExpressRouteOperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new ExpressRouteOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure"));
if (gatewayOperationElement != null)
{
XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure"));
if (dataElement != null)
{
string dataInstance = dataElement.Value;
result.Data = dataInstance;
}
XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The List Dedicated Circuit Links operation retrieves a list of
/// Vnets that are linked to the circuit with the specified service
/// key.
/// </summary>
/// <param name='serviceKey'>
/// Optional.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Dedicated Circuit Link operation response.
/// </returns>
public async Task<DedicatedCircuitLinkListResponse> ListAsync(string serviceKey, CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/services/networking/dedicatedcircuits/";
if (serviceKey != null)
{
url = url + Uri.EscapeDataString(serviceKey);
}
url = url + "/vnets";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=1.0");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2011-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DedicatedCircuitLinkListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DedicatedCircuitLinkListResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement dedicatedCircuitLinksSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitLinks", "http://schemas.microsoft.com/windowsazure"));
if (dedicatedCircuitLinksSequenceElement != null)
{
foreach (XElement dedicatedCircuitLinksElement in dedicatedCircuitLinksSequenceElement.Elements(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure")))
{
AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink();
result.DedicatedCircuitLinks.Add(dedicatedCircuitLinkInstance);
XElement stateElement = dedicatedCircuitLinksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure"));
if (stateElement != null)
{
DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true));
dedicatedCircuitLinkInstance.State = stateInstance;
}
XElement vnetNameElement = dedicatedCircuitLinksElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure"));
if (vnetNameElement != null)
{
string vnetNameInstance = vnetNameElement.Value;
dedicatedCircuitLinkInstance.VnetName = vnetNameInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// The New Dedicated Circuit Link operation creates a new dedicated
/// circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required.
/// </param>
/// <param name='vnetName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> NewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("vnetName", vnetName);
TracingAdapter.Enter(invocationId, this, "NewAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuitLinks.BeginNewAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
/// <summary>
/// The Remove Dedicated Circuit Link operation deletes an existing
/// dedicated circuit link.
/// </summary>
/// <param name='serviceKey'>
/// Required. Service Key associated with the dedicated circuit.
/// </param>
/// <param name='vnetName'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request, and also includes error
/// information regarding the failure.
/// </returns>
public async Task<ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken)
{
ExpressRouteManagementClient client = this.Client;
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("serviceKey", serviceKey);
tracingParameters.Add("vnetName", vnetName);
TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters);
}
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationResponse response = await client.DedicatedCircuitLinks.BeginRemoveAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
int delayInSeconds = 30;
if (client.LongRunningOperationInitialTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationInitialTimeout;
}
while (result.Status == ExpressRouteOperationStatus.InProgress)
{
cancellationToken.ThrowIfCancellationRequested();
await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false);
delayInSeconds = 30;
if (client.LongRunningOperationRetryTimeout >= 0)
{
delayInSeconds = client.LongRunningOperationRetryTimeout;
}
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
if (result.Status != ExpressRouteOperationStatus.Successful)
{
if (result.Error != null)
{
CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message);
ex.Error = new CloudError();
ex.Error.Code = result.Error.Code;
ex.Error.Message = result.Error.Message;
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
else
{
CloudException ex = new CloudException("");
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
}
return result;
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class TimerEventDecoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 20;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private TimerEventDecoder _parentMessage;
private IDirectBuffer _buffer;
protected int _offset;
protected int _limit;
protected int _actingBlockLength;
protected int _actingVersion;
public TimerEventDecoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public TimerEventDecoder Wrap(
IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion)
{
this._buffer = buffer;
this._offset = offset;
this._actingBlockLength = actingBlockLength;
this._actingVersion = actingVersion;
Limit(offset + actingBlockLength);
return this;
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdId()
{
return 1;
}
public static int LeadershipTermIdSinceVersion()
{
return 0;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static string LeadershipTermIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public long LeadershipTermId()
{
return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian);
}
public static int CorrelationIdId()
{
return 2;
}
public static int CorrelationIdSinceVersion()
{
return 0;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public long CorrelationId()
{
return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian);
}
public static int TimestampId()
{
return 3;
}
public static int TimestampSinceVersion()
{
return 0;
}
public static int TimestampEncodingOffset()
{
return 16;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static string TimestampMetaAttribute(MetaAttribute metaAttribute)
{
switch (metaAttribute)
{
case MetaAttribute.EPOCH: return "unix";
case MetaAttribute.TIME_UNIT: return "nanosecond";
case MetaAttribute.SEMANTIC_TYPE: return "";
case MetaAttribute.PRESENCE: return "required";
}
return "";
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public long Timestamp()
{
return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian);
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
int originalLimit = Limit();
Limit(_offset + _actingBlockLength);
builder.Append("[TimerEvent](sbeTemplateId=");
builder.Append(TEMPLATE_ID);
builder.Append("|sbeSchemaId=");
builder.Append(SCHEMA_ID);
builder.Append("|sbeSchemaVersion=");
if (_parentMessage._actingVersion != SCHEMA_VERSION)
{
builder.Append(_parentMessage._actingVersion);
builder.Append('/');
}
builder.Append(SCHEMA_VERSION);
builder.Append("|sbeBlockLength=");
if (_actingBlockLength != BLOCK_LENGTH)
{
builder.Append(_actingBlockLength);
builder.Append('/');
}
builder.Append(BLOCK_LENGTH);
builder.Append("):");
//Token{signal=BEGIN_FIELD, name='leadershipTermId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("LeadershipTermId=");
builder.Append(LeadershipTermId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("CorrelationId=");
builder.Append(CorrelationId());
builder.Append('|');
//Token{signal=BEGIN_FIELD, name='timestamp', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
//Token{signal=ENCODING, name='time_t', referencedName='null', description='Epoch time since 1 Jan 1970 UTC.', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}}
builder.Append("Timestamp=");
builder.Append(Timestamp());
Limit(originalLimit);
return builder;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using WebApplication3.Models;
namespace WebApplication3.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
public override void BuildModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("WebApplication3.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
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("WebApplication3.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("WebApplication3.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("WebApplication3.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
// 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.IO;
using System.Text;
using System.Globalization;
using System.Runtime.CompilerServices;
using Xunit;
public class Directory_Exists
{
[Fact]
public static void Exists_NullAsPath_ReturnsFalse()
{
bool result = Directory.Exists((string)null);
Assert.False(result);
}
[Fact]
public static void Exists_EmptyAsPath_ReturnsFalse()
{
bool result = Directory.Exists(string.Empty);
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows | PlatformID.OSX)] // testing case insensitivity
public static void Exists_DoesCaseInsensitiveInvariantComparions()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
var paths = new string[] { directory.Path,
directory.Path.ToUpperInvariant(),
directory.Path.ToLowerInvariant() };
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.True(result, path);
}
}
}
[Fact]
public static void Exists_NonExistentValidPathAsPath_ReturnsFalse()
{
var paths = IOInputs.GetValidPathComponentNames();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
public static void Exists_ExistentValidPathAsPath_ReturnsTrue()
{
var components = IOInputs.GetValidPathComponentNames();
foreach (string component in components)
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
string path = Path.Combine(directory.Path, component);
Directory.CreateDirectory(path);
bool result = Directory.Exists(path);
Assert.True(result, path);
}
}
}
[Fact]
public static void Exists_NonSignificantWhiteSpaceAsPath_ReturnsFalse()
{
var paths = IOInputs.GetNonSignificantTrailingWhiteSpace();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[PlatformSpecific(PlatformID.Windows)] // trailing whitespace is significant in filenames
[Fact]
public static void Exists_ExistingDirectoryWithNonSignificantTrailingWhiteSpaceAsPath_ReturnsTrue()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
var components = IOInputs.GetNonSignificantTrailingWhiteSpace();
foreach (string component in components)
{
string path = directory.Path + component;
bool result = Directory.Exists(path);
Assert.True(result, path);
}
}
}
[Fact]
public static void Exists_PathWithInvalidCharactersAsPath_ReturnsFalse()
{
var paths = IOInputs.GetPathsWithInvalidCharacters();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data stream
public static void Exists_PathWithAlternativeDataStreams_ReturnsFalse()
{
var paths = IOInputs.GetPathsWithAlternativeDataStreams();
foreach (var path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device names
public static void Exists_PathWithReservedDeviceNameAsPath_ReturnsFalse()
{
var paths = IOInputs.GetPathsWithReservedDeviceNames();
foreach (var path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC paths
public static void Exists_UncPathWithoutShareNameAsPath_ReturnsFalse()
{
var paths = IOInputs.GetUncPathsWithoutShareName();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public static void Exists_DirectoryEqualToMaxDirectory_ReturnsTrue()
{ // Creates directories up to the maximum directory length all at once
using (TemporaryDirectory directory = new TemporaryDirectory())
{
PathInfo path = IOServices.GetPath(directory.Path, IOInputs.MaxDirectory, maxComponent: 10);
Directory.CreateDirectory(path.FullPath);
bool result = Directory.Exists(path.FullPath);
Assert.True(result, path.FullPath);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public static void Exists_DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
{
var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
public static void Exists_DirectoryLongerThanMaxDirectoryAsPath_ReturnsFalse()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
public static void Exists_DirectoryLongerThanMaxPathAsPath_ReturnsFalse()
{
var paths = IOInputs.GetPathsLongerThanMaxPath();
foreach (string path in paths)
{
bool result = Directory.Exists(path);
Assert.False(result, path);
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public static void Exists_NotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Directory.Exists(drive);
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public static void Exists_SubdirectoryOnNotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Directory.Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public static void Exists_NonExistentDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNonExistentDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a non-existent drive.");
return;
}
bool result = Directory.Exists(drive);
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public static void Exists_SubdirectoryOnNonExistentDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNonExistentDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a non-existent drive.");
return;
}
bool result = Directory.Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
[Fact]
public static void Exists_FileWithoutTrailingSlashAsPath_ReturnsFalse()
{
using (TemporaryFile file = new TemporaryFile())
{
string path = IOServices.RemoveTrailingSlash(file.Path);
bool result = Directory.Exists(path);
Assert.False(result);
}
}
[Fact]
public static void Exists_FileWithTrailingSlashAsPath_ReturnsFalse()
{
using (TemporaryFile file = new TemporaryFile())
{
string path = IOServices.AddTrailingSlashIfNeeded(file.Path);
bool result = Directory.Exists(path);
Assert.False(result);
}
}
[Fact]
public static void Exists_ExistingDirectoryWithoutTrailingSlashAsPath_ReturnsTrue()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
string path = IOServices.RemoveTrailingSlash(directory.Path);
bool result = Directory.Exists(path);
Assert.True(result);
}
}
[Fact]
public static void Exists_ExistingDirectoryWithTrailingSlashAsPath_ReturnsTrue()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
string path = IOServices.AddTrailingSlashIfNeeded(directory.Path);
bool result = Directory.Exists(path);
Assert.True(result);
}
}
[Fact]
public static void Exists_DotAsPath_ReturnsTrue()
{
bool result = Directory.Exists(Path.Combine(TestInfo.CurrentDirectory, "."));
Assert.True(result);
}
[Fact]
public static void Exists_DotDotAsPath_ReturnsTrue()
{
bool result = Directory.Exists(Path.Combine(TestInfo.CurrentDirectory, ".."));
Assert.True(result);
}
#if !TEST_WINRT // WinRT cannot access root
/*
[Fact]
[ActiveIssue(1220)] // SetCurrentDirectory
public static void Exists_DotDotAsPath_WhenCurrentDirectoryIsRoot_ReturnsTrue()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
bool result = Directory.Exists("..");
Assert.True(result);
}
}
*/
#endif
[Fact]
public static void Exists_DirectoryGetCurrentDirectoryAsPath_ReturnsTrue()
{
bool result = Directory.Exists(Directory.GetCurrentDirectory());
Assert.True(result);
}
}
| |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V10.Enums.AccessRoleEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example updates the access role of a user, given the email address.
/// Note: This code example should be run as a user who is an Administrator on the Google Ads
/// account with the specified customer ID. See
/// https://support.google.com/google-ads/answer/9978556 to learn more about account access
/// levels.
/// </summary>
public class UpdateUserAccess : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="UpdateUserAccess"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// Email address of the user whose access role should be updated.
/// </summary>
[Option("emailAddress", Required = true, HelpText =
"Email address of the user whose access role should be updated.")]
public string EmailAddress { get; set; }
/// <summary>
/// The updated access role.
/// </summary>
[Option("accessRole", Required = true, HelpText =
"The updated access role.")]
public AccessRole AccessRole { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
Parser parser = new Parser(settings =>
{
settings.CaseInsensitiveEnumValues = true;
});
parser.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// Email address of the user whose access role should be updated.
options.EmailAddress = "INSERT_EMAIL_ADDRESS_HERE";
// The updated user access role.
options.AccessRole = (AccessRole) Enum.Parse(typeof(AccessRole),
"INSERT_ACCESS_ROLE_HERE");
return 0;
});
UpdateUserAccess codeExample = new UpdateUserAccess();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(),
options.CustomerId,
options.EmailAddress,
options.AccessRole);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example updates the access of a user, given the email " +
"address. Note: This code example should be run as a user who is an Administrator" +
" on the Google Ads account with the specified customer ID. See " +
"https://support.google.com/google-ads/answer/9978556 to learn more about account " +
"access levels.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="emailAddress">Email address of the user whose access role should be
/// updated.</param>
/// <param name="accessRole">The updated access role.</param>
public void Run(GoogleAdsClient client, long customerId, string emailAddress,
AccessRole accessRole)
{
try
{
long? userId = GetUserAccess(client, customerId, emailAddress);
if (userId != null)
{
ModifyUserAccess(client, customerId, userId.Value, accessRole);
}
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Gets the customer user access given an email address.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="emailAddress">Email address of the user whose access role should be
/// retrieved.</param>
/// <returns>The user ID if a customer is found, or null if no matching customers were
/// found.</returns>
private long? GetUserAccess(GoogleAdsClient client, long customerId, string emailAddress)
{
// Get the GoogleAdsService.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V10.GoogleAdsService);
// Create the search query. Use the LIKE query for filtering to ignore the text case
// for email address when searching for a match.
string searchQuery = "Select customer_user_access.user_id, " +
"customer_user_access.email_address, customer_user_access.access_role," +
"customer_user_access.access_creation_date_time from customer_user_access " +
$"where customer_user_access.email_address LIKE '{emailAddress}'";
// Retrieves the user accesses.
PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
googleAdsService.Search(customerId.ToString(), searchQuery);
GoogleAdsRow result = searchPagedResponse.FirstOrDefault();
// Displays the results.
if (result != null)
{
CustomerUserAccess access = result.CustomerUserAccess;
Console.WriteLine("Customer user access with User ID = {0}, Email Address = " +
"{1}, Access Role = {2} and Creation Time = {3} was found in " +
"Customer ID: {4}.", access.UserId, access.EmailAddress, access.AccessRole,
access.AccessCreationDateTime, customerId);
return access.UserId;
}
else
{
Console.WriteLine("No customer user access with requested email was found.");
return null;
}
}
/// <summary>
/// Modifies the user access role to a specified value.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="userId">ID of the user whose access role is modified.</param>
/// <param name="accessRole">The updated access role.</param>
private void ModifyUserAccess(GoogleAdsClient client, long customerId, long userId,
AccessRole accessRole)
{
// Get the CustomerUserAccessService.
CustomerUserAccessServiceClient userAccessService = client.GetService(
Services.V10.CustomerUserAccessService);
// Creates the modified user access.
CustomerUserAccess userAccess = new CustomerUserAccess()
{
ResourceName = ResourceNames.CustomerUserAccess(customerId, userId),
AccessRole = accessRole
};
// Creates the operation.
CustomerUserAccessOperation operation = new CustomerUserAccessOperation()
{
Update = userAccess,
UpdateMask = FieldMasks.AllSetFieldsOf(userAccess)
};
// Updates the user access.
MutateCustomerUserAccessResponse response =
userAccessService.MutateCustomerUserAccess(
customerId.ToString(), operation);
// Displays the result.
Console.WriteLine($"Successfully modified customer user access with " +
$"resource name '{response.Result.ResourceName}'.");
}
}
}
| |
#region Header
// ---------------------------------------------------------------------------
// Sepura - Commercially Confidential.
//
// EnumDefinition.cs
// Implementation of the Class EnumDefinition
//
// Copyright (c) 2010 Sepura Plc
// All Rights reserved.
//
// Original author: robinsond
//
// $Id:$
// ---------------------------------------------------------------------------
#endregion
namespace Sepura.DataDictionary
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;
/// <summary>
/// Class representing an enum definition
/// </summary>
public class EnumDefinition : TypeDefinition
{
/// <summary>
/// Gets the collection of literal associated with this enumeration
/// </summary>
public ReadOnlyCollection<LiteralDefinition> Literals
{
get
{
return m_Literals;
}
}
/// <summary>
/// Gets the underlying integer (base) type.
/// </summary>
/// <value>
/// The type of the base.
/// </value>
public TypeDefinition BaseType
{
get;
private set;
}
/// <summary>
/// Initializes a new instance of the EnumDefinition class
/// Populates this object with information extracted from the XML
/// </summary>
/// <param name="theNode">XML node describing the Enum object</param>
/// <param name="manager">The data dictionary manager constructing this type.</param>
public EnumDefinition(XElement theNode, DictionaryManager manager)
: base(theNode, TypeId.EnumType)
{
// ByteSize may be set either directly as an integer or by inference from the Type field.
// If no Type field is present then the type is assumed to be 'int'
if (theNode.Element("ByteSize") != null)
{
SetByteSize(theNode.Element("ByteSize").Value);
}
else
{
string baseTypeName = theNode.Element("Type") != null ? theNode.Element("Type").Value : "int";
BaseType = manager.GetElementType(baseTypeName);
BaseType = DictionaryManager.DereferenceTypeDef(BaseType);
FixedSizeBytes = BaseType.FixedSizeBytes.Value;
}
// Common properties are parsed by the base class.
// Remaining properties are the Name/Value Literal elements
List<LiteralDefinition> theLiterals = new List<LiteralDefinition>();
foreach (var literalNode in theNode.Elements("Literal"))
{
theLiterals.Add(new LiteralDefinition(literalNode));
}
m_Literals = new ReadOnlyCollection<LiteralDefinition>(theLiterals);
// Check the name. If it's null then make one up
if (theNode.Element("Name") == null)
{
Name = String.Format("Enum_{0}", Ref);
}
}
/// <summary>
/// Return a string describing the object
/// </summary>
/// <returns>String describing the object</returns>
public override string ToString()
{
return String.Format("enum {0}", Name);
}
/// <summary>
/// Creates a new Value object, deriving the value by decoding the specified bytes.
/// Each derived class creates its corresponding value type
/// </summary>
/// <param name="theBytes">The collection of bytes containing the value to be
/// decoded</param>
/// <param name="parent"></param>
/// <returns>
/// The decoded value object
/// </returns>
public override Value Decode(ByteStore theBytes, Value parent)
{
return new EnumValue(this, theBytes, parent);
}
/// <summary>
/// Create a new instance of the type populated with default values.
/// </summary>
/// <param name="parent"></param>
/// <returns>
/// New instance of the type populated with default values
/// </returns>
public override Value Instantiate(Value parent)
{
return new EnumValue(this, parent);
}
/// <summary>
/// Tries to get the literal string corresponding to the integer value
/// </summary>
/// <param name="integerValue">The integer value.</param>
/// <param name="literal">The literal.</param>
/// <returns>True if found, else false</returns>
public bool TryGetLiteral(int integerValue, out string literal)
{
bool found = false;
literal = string.Empty;
foreach (var item in m_Literals)
{
if (item.Value == integerValue)
{
literal = item.Name;
found = true;
break;
}
}
return found;
}
/// <summary>
/// Tries to get the literal string corresponding to the integer value
/// </summary>
/// <param name="literal">The literal.</param>
/// <param name="integerValue">The integer value.</param>
/// <returns>
/// True if found, else false
/// </returns>
public bool TryGetInteger(string literal, out int integerValue)
{
bool found = false;
integerValue = 0;
foreach (var item in m_Literals)
{
if (item.Name == literal)
{
integerValue = item.Value;
found = true;
break;
}
}
return found;
}
/// <summary>
/// Returns the string equivalent of the integer value. Throws if the integer value is not known.
/// </summary>
/// <param name="theIntegerValue">The integer value.</param>
/// <returns>String equivalent of the integer value</returns>
public string IntegerValueToString(int theIntegerValue)
{
string literal;
if (TryGetLiteral(theIntegerValue, out literal))
{
return literal;
}
return string.Format("[{0}]", theIntegerValue);
}
/// <summary>
/// Returns the integer equivalent of the string value. Throws if the string value is not known.
/// </summary>
/// <param name="theStringValue">The string value.</param>
/// <returns>The integer equivalent of the string value</returns>
public int StringValueToInteger(string theStringValue)
{
int intValue;
if (TryGetInteger(theStringValue, out intValue))
{
return intValue;
}
throw new DataDictionaryException("Enum {0}: Illegal string value {1}", Name, theStringValue);
}
/// <summary>
/// Validates the integer value is represented in the enumeration
/// </summary>
/// <param name="theIntegerValue">The integer value.</param>
public void ValidateIntegerValue(int theIntegerValue)
{
IntegerValueToString(theIntegerValue);
}
/// <summary>
/// Validates the string value is represented in the enumeration
/// </summary>
/// <param name="theStringValue">The string value.</param>
public void ValidateStringValue(string theStringValue)
{
StringValueToInteger(theStringValue);
}
/// <summary>
/// Collection of the literal values defined for this enum
/// </summary>
private ReadOnlyCollection<LiteralDefinition> m_Literals;
}
}
| |
using System;
namespace XSharpx {
public struct WriteOp<A> {
private readonly char c;
private readonly A val;
private readonly bool o;
internal WriteOp(char c, A val, bool o) {
this.c = c;
this.val = val;
this.o = o;
}
public Store<char, WriteOp<A>> Character {
get {
var t = this;
return c.StoreSet(x => new WriteOp<A>(x, t.val, t.o));
}
}
public Store<A, WriteOp<A>> Value {
get {
var t = this;
return val.StoreSet(x => new WriteOp<A>(t.c, x, t.o));
}
}
public bool IsOut {
get {
return o;
}
}
public bool IsErr {
get {
return !o;
}
}
public WriteOp<A> SetOut {
get {
return new WriteOp<A>(c, val, true);
}
}
public WriteOp<A> SetErr {
get {
return new WriteOp<A>(c, val, false);
}
}
public WriteOp<A> Redirect {
get {
return new WriteOp<A>(c, val, !o);
}
}
public static WriteOp<A> Out(char c, A val) {
return new WriteOp<A>(c, val, true);
}
public static WriteOp<A> Err(char c, A val) {
return new WriteOp<A>(c, val, false);
}
public WriteOp<B> Extend<B>(Func<WriteOp<A>, B> f) {
var b = f(this);
return new WriteOp<B>(c, b, o);
}
public WriteOp<WriteOp<A>> Duplicate {
get {
return Extend(z => z);
}
}
public Op<A> Op {
get {
return new Op<A>(this.Right<Either<Func<int, A>, Func<string, A>>, WriteOp<A>>());
}
}
}
public static class WriteOpExtension {
public static WriteOp<B> Select<A, B>(this WriteOp<A> k, Func<A, B> f) {
return new WriteOp<B>(k.Character.Get, f(k.Value.Get), k.IsOut);
}
}
public struct Op<A> {
private readonly Either<Either<Func<int, A>, Func<string, A>>, WriteOp<A>> val;
internal Op(Either<Either<Func<int, A>, Func<string, A>>, WriteOp<A>> val) {
this.val = val;
}
public X Fold<X>(Func<Func<int, A>, X> r, Func<Func<string, A>, X> rl, Func<WriteOp<A>, X> p) {
return val.Fold(d => d.Fold(r, rl), p);
}
public bool IsWriteOut {
get {
return val.Any(o => o.IsOut);
}
}
public bool IsWriteErr {
get {
return val.Any(o => o.IsErr);
}
}
public bool IsWrite {
get {
return val.IsRight;
}
}
public bool IsRead {
get {
return val.Swap.Any(o => o.IsLeft);
}
}
public bool IsReadLine {
get {
return val.Swap.Any(o => o.IsRight);
}
}
public Option<WriteOp<A>> WriteOp {
get {
return val.ToOption;
}
}
public Option<char> WriteOpCharacter {
get {
return WriteOp.Select(o => o.Character.Get);
}
}
public Option<A> WriteOpValue {
get {
return WriteOp.Select(o => o.Value.Get);
}
}
public Option<Func<int, A>> ReadValue {
get {
return val.Swap.ToOption.SelectMany(f => f.Swap.ToOption);
}
}
public Option<Func<string, A>> ReadLineValue {
get {
return val.Swap.ToOption.SelectMany(f => f.ToOption);
}
}
public Terminal<A> Lift {
get {
return new Terminal<A>(this.Select(a => Terminal<A>.Done(a)).Right<A, Op<Terminal<A>>>());
}
}
public static Op<A> Read(Func<int, A> f) {
return new Op<A>(f.Left<Func<int, A>, Func<string, A>>().Left<Either<Func<int, A>, Func<string, A>>, WriteOp<A>>()); /// new Op<A>(f.Left<Func<int, A>, WriteOp<A>>());
}
public static Op<A> ReadLine(Func<string, A> f) {
return new Op<A>(f.Right<Func<int, A>, Func<string, A>>().Left<Either<Func<int, A>, Func<string, A>>, WriteOp<A>>()); /// new Op<A>(f.Left<Func<int, A>, WriteOp<A>>());
}
public static Op<A> WriteOut(char c, A a) {
return new Op<A>(WriteOp<A>.Out(c, a).Right<Either<Func<int, A>, Func<string, A>>, WriteOp<A>>());
}
public static Op<A> WriteErr(char c, A a) {
return new Op<A>(WriteOp<A>.Err(c, a).Right<Either<Func<int, A>, Func<string, A>>, WriteOp<A>>());
}
}
public static class OpExtension {
public static Op<B> Select<A, B>(this Op<A> k, Func<A, B> f) {
return k.Fold(q => Op<B>.Read(f.Compose(q)), q => Op<B>.ReadLine(f.Compose(q)), o => o.Select(f).Op);
}
}
public struct Terminal<A> {
internal readonly Either<A, Op<Terminal<A>>> val;
internal Terminal(Either<A, Op<Terminal<A>>> val) {
this.val = val;
}
public Terminal<C> ZipWith<B, C>(Terminal<B> o, Func<A, Func<B, C>> f) {
return this.SelectMany(a => o.Select(b => f(a)(b)));
}
public Terminal<Pair<A, B>> Zip<B>(Terminal<B> o) {
return ZipWith<B, Pair<A, B>>(o, Pair<A, B>.pairF());
}
public static Terminal<A> Done(A a) {
return new Terminal<A>(a.Left<A, Op<Terminal<A>>>());
}
internal static Terminal<A> More(Op<Terminal<A>> o) {
return new Terminal<A>(o.Right<A, Op<Terminal<A>>>());
}
public static Terminal<Unit> WriteOut(char c) {
return Op<Unit>.WriteOut(c, Unit.Value).Lift;
}
public static Terminal<Unit> WriteErr(char c) {
return Op<Unit>.WriteErr(c, Unit.Value).Lift;
}
public static Terminal<int> Read {
get {
return Op<int>.Read(c => c).Lift;
}
}
public static Terminal<string> ReadLine {
get {
return Op<string>.ReadLine(c => c).Lift;
}
}
// CAUTION: unsafe (perform I/O)
//
// This function stands in for the interpreter of 'Terminal programs'.
public A Run {
get {
return val.Swap.Reduce(o => o.Fold(
r => {
var c = Console.Read();
return r(c).Run;
}
, r => {
var s = Console.ReadLine();
return r(s).Run;
}
, r => {
if(r.IsOut) {
Console.Write(r.Character);
return r.Value.Get.Run;
} else {
Console.Error.Write(r.Character);
return r.Value.Get.Run;
}
}
));
}
}
// Select, SelectMany, Apply, Zip and friends, 8Monad functions
}
public static class TerminalExtension {
public static Terminal<B> Select<A, B>(this Terminal<A> k, Func<A, B> f) {
return k.val.Fold(
a => Terminal<B>.Done(f(a))
, o => Terminal<B>.More(o.Select(t => t.Select(f)))
);
}
public static Terminal<B> SelectMany<A, B>(this Terminal<A> k, Func<A, Terminal<B>> f) {
return k.val.Fold(
f
, o => Terminal<B>.More(o.Select(t => t.SelectMany(f)))
);
}
public static Terminal<C> SelectMany<A, B, C>(this Terminal<A> k, Func<A, Terminal<B>> p, Func<A, B, C> f) {
return SelectMany(k, a => Select(p(a), b => f(a, b)));
}
public static Terminal<B> Apply<A, B>(this Terminal<Func<A, B>> f, Terminal<A> o) {
return f.SelectMany(g => o.Select(p => g(p)));
}
public static Terminal<A> Flatten<A>(this Terminal<Terminal<A>> o) {
return o.SelectMany(z => z);
}
public static Terminal<A> TerminalValue<A>(this A a) {
return Terminal<A>.Done(a);
}
}
}
| |
/*
* 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.Reflection;
using BulletDotNET;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Physics.Manager;
using log4net;
namespace OpenSim.Region.Physics.BulletDotNETPlugin
{
public class BulletDotNETCharacter : PhysicsActor
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public btRigidBody Body;
public btCollisionShape Shell;
public btVector3 tempVector1;
public btVector3 tempVector2;
public btVector3 tempVector3;
public btVector3 tempVector4;
public btVector3 tempVector5RayCast;
public btVector3 tempVector6RayCast;
public btVector3 tempVector7RayCast;
public btQuaternion tempQuat1;
public btTransform tempTrans1;
public ClosestNotMeRayResultCallback ClosestCastResult;
private btTransform m_bodyTransform;
private btVector3 m_bodyPosition;
private btVector3 m_CapsuleOrientationAxis;
private btQuaternion m_bodyOrientation;
private btDefaultMotionState m_bodyMotionState;
private btGeneric6DofConstraint m_aMotor;
// private PhysicsVector m_movementComparision;
private PhysicsVector m_position;
private PhysicsVector m_zeroPosition;
private bool m_zeroFlag = false;
private bool m_lastUpdateSent = false;
private PhysicsVector m_velocity;
private PhysicsVector m_target_velocity;
private PhysicsVector m_acceleration;
private PhysicsVector m_rotationalVelocity;
private bool m_pidControllerActive = true;
public float PID_D = 80.0f;
public float PID_P = 90.0f;
public float CAPSULE_RADIUS = 0.37f;
public float CAPSULE_LENGTH = 2.140599f;
public float heightFudgeFactor = 0.52f;
public float walkDivisor = 1.3f;
public float runDivisor = 0.8f;
private float m_mass = 80f;
public float m_density = 60f;
private bool m_flying = false;
private bool m_iscolliding = false;
private bool m_iscollidingGround = false;
private bool m_wascolliding = false;
private bool m_wascollidingGround = false;
private bool m_iscollidingObj = false;
private bool m_alwaysRun = false;
private bool m_hackSentFall = false;
private bool m_hackSentFly = false;
public uint m_localID = 0;
public bool m_returnCollisions = false;
// taints and their non-tainted counterparts
public bool m_isPhysical = false; // the current physical status
public bool m_tainted_isPhysical = false; // set when the physical status is tainted (false=not existing in physics engine, true=existing)
private float m_tainted_CAPSULE_LENGTH; // set when the capsule length changes.
private bool m_taintRemove = false;
// private bool m_taintedPosition = false;
// private PhysicsVector m_taintedPosition_value;
private PhysicsVector m_taintedForce;
private float m_buoyancy = 0f;
// private CollisionLocker ode;
// private string m_name = String.Empty;
private bool[] m_colliderarr = new bool[11];
private bool[] m_colliderGroundarr = new bool[11];
private BulletDotNETScene m_parent_scene;
public int m_eventsubscription = 0;
// private CollisionEventUpdate CollisionEventsThisFrame = new CollisionEventUpdate();
public BulletDotNETCharacter(string avName, BulletDotNETScene parent_scene, PhysicsVector pos, PhysicsVector size, float pid_d, float pid_p, float capsule_radius, float tensor, float density, float height_fudge_factor, float walk_divisor, float rundivisor)
{
m_taintedForce = new PhysicsVector();
m_velocity = new PhysicsVector();
m_target_velocity = new PhysicsVector();
m_position = pos;
m_zeroPosition = new PhysicsVector(pos.X, pos.Y, pos.Z); // this is a class, not a struct. Must make new, or m_zeroPosition will == position regardless
m_acceleration = new PhysicsVector();
m_parent_scene = parent_scene;
PID_D = pid_d;
PID_P = pid_p;
CAPSULE_RADIUS = capsule_radius;
m_density = density;
heightFudgeFactor = height_fudge_factor;
walkDivisor = walk_divisor;
runDivisor = rundivisor;
for (int i = 0; i < 11; i++)
{
m_colliderarr[i] = false;
}
for (int i = 0; i < 11; i++)
{
m_colliderGroundarr[i] = false;
}
CAPSULE_LENGTH = (size.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
m_tainted_CAPSULE_LENGTH = CAPSULE_LENGTH;
m_isPhysical = false; // current status: no ODE information exists
m_tainted_isPhysical = true; // new tainted status: need to create ODE information
m_parent_scene.AddPhysicsActorTaint(this);
// m_name = avName;
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
/// <summary>
/// This creates the Avatar's physical Surrogate at the position supplied
/// </summary>
/// <param name="npositionX"></param>
/// <param name="npositionY"></param>
/// <param name="npositionZ"></param>
// WARNING: This MUST NOT be called outside of ProcessTaints, else we can have unsynchronized access
// to ODE internals. ProcessTaints is called from within thread-locked Simulate(), so it is the only
// place that is safe to call this routine AvatarGeomAndBodyCreation.
private void AvatarGeomAndBodyCreation(float npositionX, float npositionY, float npositionZ)
{
if (CAPSULE_LENGTH <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_LENGTH = 0.01f;
}
if (CAPSULE_RADIUS <= 0)
{
m_log.Warn("[PHYSICS]: The capsule size you specified in opensim.ini is invalid! Setting it to the smallest possible size!");
CAPSULE_RADIUS = 0.01f;
}
Shell = new btCapsuleShape(CAPSULE_RADIUS, CAPSULE_LENGTH);
if (m_bodyPosition == null)
m_bodyPosition = new btVector3(npositionX, npositionY, npositionZ);
m_bodyPosition.setValue(npositionX, npositionY, npositionZ);
if (m_bodyOrientation == null)
m_bodyOrientation = new btQuaternion(m_CapsuleOrientationAxis, (Utils.DEG_TO_RAD * 90));
if (m_bodyTransform == null)
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
else
{
m_bodyTransform.Dispose();
m_bodyTransform = new btTransform(m_bodyOrientation, m_bodyPosition);
}
if (m_bodyMotionState == null)
m_bodyMotionState = new btDefaultMotionState(m_bodyTransform);
else
m_bodyMotionState.setWorldTransform(m_bodyTransform);
m_mass = Mass;
Body = new btRigidBody(m_mass, m_bodyMotionState, Shell);
Body.setUserPointer(new IntPtr((int)Body.Handle));
if (ClosestCastResult != null)
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
m_parent_scene.AddRigidBody(Body);
Body.setActivationState(4);
if (m_aMotor != null)
{
if (m_aMotor.Handle != IntPtr.Zero)
{
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose();
}
m_aMotor = null;
}
m_aMotor = new btGeneric6DofConstraint(Body, m_parent_scene.TerrainBody,
m_parent_scene.TransZero,
m_parent_scene.TransZero, false);
m_aMotor.setAngularLowerLimit(m_parent_scene.VectorZero);
m_aMotor.setAngularUpperLimit(m_parent_scene.VectorZero);
}
public void Remove()
{
m_taintRemove = true;
}
public override bool Stopped
{
get { return m_zeroFlag; }
}
public override PhysicsVector Size
{
get { return new PhysicsVector(CAPSULE_RADIUS * 2, CAPSULE_RADIUS * 2, CAPSULE_LENGTH); }
set
{
m_pidControllerActive = true;
PhysicsVector SetSize = value;
m_tainted_CAPSULE_LENGTH = (SetSize.Z * 1.15f) - CAPSULE_RADIUS * 2.0f;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Velocity = new PhysicsVector(0f, 0f, 0f);
m_parent_scene.AddPhysicsActorTaint(this);
}
}
/// <summary>
/// turn the PID controller on or off.
/// The PID Controller will turn on all by itself in many situations
/// </summary>
/// <param name="status"></param>
public void SetPidStatus(bool status)
{
m_pidControllerActive = status;
}
public override PrimitiveBaseShape Shape
{
set { return; }
}
public override uint LocalID
{
set { m_localID = value; }
}
public override bool Grabbed
{
set { return; }
}
public override bool Selected
{
set { return; }
}
public override void CrossingFailure()
{
}
public override void link(PhysicsActor obj)
{
}
public override void delink()
{
}
public override void LockAngularMotion(PhysicsVector axis)
{
}
public override PhysicsVector Position
{
get { return m_position; }
set
{
// m_taintedPosition_value = value;
m_position = value;
// m_taintedPosition = true;
}
}
public override float Mass
{
get
{
float AVvolume = (float)(Math.PI * Math.Pow(CAPSULE_RADIUS, 2) * CAPSULE_LENGTH);
return m_density * AVvolume;
}
}
public override PhysicsVector Force
{
get { return new PhysicsVector(m_target_velocity.X, m_target_velocity.Y, m_target_velocity.Z); }
set { return; }
}
public override int VehicleType
{
get { return 0; }
set { return; }
}
public override void VehicleFloatParam(int param, float value)
{
}
public override void VehicleVectorParam(int param, PhysicsVector value)
{
}
public override void VehicleRotationParam(int param, Quaternion rotation)
{
}
public override void SetVolumeDetect(int param)
{
}
public override PhysicsVector GeometricCenter
{
get { return PhysicsVector.Zero; }
}
public override PhysicsVector CenterOfMass
{
get { return PhysicsVector.Zero; }
}
public override PhysicsVector Velocity
{
get
{
// There's a problem with PhysicsVector.Zero! Don't Use it Here!
if (m_zeroFlag)
return new PhysicsVector(0f, 0f, 0f);
m_lastUpdateSent = false;
return m_velocity;
}
set
{
m_pidControllerActive = true;
m_target_velocity = value;
}
}
public override PhysicsVector Torque
{
get { return PhysicsVector.Zero; }
set { return; }
}
public override float CollisionScore
{
get { return 0f; }
set { }
}
public override PhysicsVector Acceleration
{
get { return m_acceleration; }
}
public override Quaternion Orientation
{
get { return Quaternion.Identity; }
set
{
}
}
public override int PhysicsActorType
{
get { return (int)ActorTypes.Agent; }
set { return; }
}
public override bool IsPhysical
{
get { return false; }
set { return; }
}
public override bool Flying
{
get { return m_flying; }
set { m_flying = value; }
}
public override bool SetAlwaysRun
{
get { return m_alwaysRun; }
set { m_alwaysRun = value; }
}
public override bool ThrottleUpdates
{
get { return false; }
set { return; }
}
/// <summary>
/// Returns if the avatar is colliding in general.
/// This includes the ground and objects and avatar.
/// </summary>
public override bool IsColliding
{
get { return m_iscolliding; }
set
{
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderarr[i] = m_colliderarr[i + 1];
}
}
m_colliderarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
m_log.DebugFormat("[PHYSICS]: TrueCount:{0}, FalseCount:{1}",truecount,falsecount);
if (falsecount > 1.2 * truecount)
{
m_iscolliding = false;
}
else
{
m_iscolliding = true;
}
if (m_wascolliding != m_iscolliding)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascolliding = m_iscolliding;
}
}
/// <summary>
/// Returns if an avatar is colliding with the ground
/// </summary>
public override bool CollidingGround
{
get { return m_iscollidingGround; }
set
{
// Collisions against the ground are not really reliable
// So, to get a consistant value we have to average the current result over time
// Currently we use 1 second = 10 calls to this.
int i;
int truecount = 0;
int falsecount = 0;
if (m_colliderGroundarr.Length >= 10)
{
for (i = 0; i < 10; i++)
{
m_colliderGroundarr[i] = m_colliderGroundarr[i + 1];
}
}
m_colliderGroundarr[10] = value;
for (i = 0; i < 11; i++)
{
if (m_colliderGroundarr[i])
{
truecount++;
}
else
{
falsecount++;
}
}
// Equal truecounts and false counts means we're colliding with something.
if (falsecount > 1.2 * truecount)
{
m_iscollidingGround = false;
}
else
{
m_iscollidingGround = true;
}
if (m_wascollidingGround != m_iscollidingGround)
{
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
m_wascollidingGround = m_iscollidingGround;
}
}
/// <summary>
/// Returns if the avatar is colliding with an object
/// </summary>
public override bool CollidingObj
{
get { return m_iscollidingObj; }
set
{
m_iscollidingObj = value;
if (value)
m_pidControllerActive = false;
else
m_pidControllerActive = true;
}
}
public override bool FloatOnWater
{
set { return; }
}
public override PhysicsVector RotationalVelocity
{
get { return m_rotationalVelocity; }
set { m_rotationalVelocity = value; }
}
public override bool Kinematic
{
get { return false; }
set { }
}
public override float Buoyancy
{
get { return m_buoyancy; }
set { m_buoyancy = value; }
}
public override PhysicsVector PIDTarget { set { return; } }
public override bool PIDActive { set { return; } }
public override float PIDTau { set { return; } }
public override bool PIDHoverActive
{
set { return; }
}
public override float PIDHoverHeight
{
set { return; }
}
public override PIDHoverType PIDHoverType
{
set { return; }
}
public override float PIDHoverTau
{
set { return; }
}
/// <summary>
/// Adds the force supplied to the Target Velocity
/// The PID controller takes this target velocity and tries to make it a reality
/// </summary>
/// <param name="force"></param>
/// <param name="pushforce">Is this a push by a script?</param>
public override void AddForce(PhysicsVector force, bool pushforce)
{
if (pushforce)
{
m_pidControllerActive = false;
force *= 100f;
doForce(force, false);
//System.Console.WriteLine("Push!");
//_target_velocity.X += force.X;
// _target_velocity.Y += force.Y;
//_target_velocity.Z += force.Z;
}
else
{
m_pidControllerActive = true;
m_target_velocity.X += force.X;
m_target_velocity.Y += force.Y;
m_target_velocity.Z += force.Z;
}
//m_lastUpdateSent = false;
}
public void doForce(PhysicsVector force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralForce(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public void doImpulse(PhysicsVector force, bool now)
{
tempVector3.setValue(force.X, force.Y, force.Z);
if (now)
{
Body.applyCentralImpulse(tempVector3);
}
else
{
m_taintedForce += force;
m_parent_scene.AddPhysicsActorTaint(this);
}
}
public override void AddAngularForce(PhysicsVector force, bool pushforce)
{
}
public override void SetMomentum(PhysicsVector momentum)
{
}
public override void SubscribeEvents(int ms)
{
m_eventsubscription = ms;
m_parent_scene.addCollisionEventReporting(this);
}
public override void UnSubscribeEvents()
{
m_parent_scene.remCollisionEventReporting(this);
m_eventsubscription = 0;
}
public override bool SubscribedEvents()
{
if (m_eventsubscription > 0)
return true;
return false;
}
internal void Dispose()
{
if (Body.isInWorld())
m_parent_scene.removeFromWorld(Body);
if (m_aMotor.Handle != IntPtr.Zero)
m_parent_scene.getBulletWorld().removeConstraint(m_aMotor);
m_aMotor.Dispose(); m_aMotor = null;
ClosestCastResult.Dispose(); ClosestCastResult = null;
Body.Dispose(); Body = null;
Shell.Dispose(); Shell = null;
tempQuat1.Dispose();
tempTrans1.Dispose();
tempVector1.Dispose();
tempVector2.Dispose();
tempVector3.Dispose();
tempVector4.Dispose();
tempVector5RayCast.Dispose();
tempVector6RayCast.Dispose();
}
public void ProcessTaints(float timestep)
{
if (m_tainted_isPhysical != m_isPhysical)
{
if (m_tainted_isPhysical)
{
// Create avatar capsule and related ODE data
if (!(Shell == null && Body == null))
{
m_log.Warn("[PHYSICS]: re-creating the following avatar ODE data, even though it already exists - "
+ (Shell != null ? "Shell " : "")
+ (Body != null ? "Body " : ""));
}
AvatarGeomAndBodyCreation(m_position.X, m_position.Y, m_position.Z);
}
else
{
// destroy avatar capsule and related ODE data
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
}
m_isPhysical = m_tainted_isPhysical;
}
if (m_tainted_CAPSULE_LENGTH != CAPSULE_LENGTH)
{
if (Body != null)
{
m_pidControllerActive = true;
// no lock needed on _parent_scene.OdeLock because we are called from within the thread lock in OdePlugin's simulate()
//d.JointDestroy(Amotor);
float prevCapsule = CAPSULE_LENGTH;
CAPSULE_LENGTH = m_tainted_CAPSULE_LENGTH;
//m_log.Info("[SIZE]: " + CAPSULE_LENGTH.ToString());
Dispose();
tempVector1 = new btVector3(0, 0, 0);
tempVector2 = new btVector3(0, 0, 0);
tempVector3 = new btVector3(0, 0, 0);
tempVector4 = new btVector3(0, 0, 0);
tempVector5RayCast = new btVector3(0, 0, 0);
tempVector6RayCast = new btVector3(0, 0, 0);
tempVector7RayCast = new btVector3(0, 0, 0);
tempQuat1 = new btQuaternion(0, 0, 0, 1);
tempTrans1 = new btTransform(tempQuat1, tempVector1);
// m_movementComparision = new PhysicsVector(0, 0, 0);
m_CapsuleOrientationAxis = new btVector3(1, 0, 1);
AvatarGeomAndBodyCreation(m_position.X, m_position.Y,
m_position.Z + (Math.Abs(CAPSULE_LENGTH - prevCapsule) * 2));
Velocity = new PhysicsVector(0f, 0f, 0f);
}
else
{
m_log.Warn("[PHYSICS]: trying to change capsule size, but the following ODE data is missing - "
+ (Shell == null ? "Shell " : "")
+ (Body == null ? "Body " : ""));
}
}
if (m_taintRemove)
{
Dispose();
}
}
/// <summary>
/// Called from Simulate
/// This is the avatar's movement control + PID Controller
/// </summary>
/// <param name="timeStep"></param>
public void Move(float timeStep)
{
// no lock; for now it's only called from within Simulate()
// If the PID Controller isn't active then we set our force
// calculating base velocity to the current position
if (Body == null)
return;
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
if (m_pidControllerActive == false)
{
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
//PidStatus = true;
PhysicsVector vec = new PhysicsVector();
PhysicsVector vel = new PhysicsVector(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
float movementdivisor = 1f;
if (!m_alwaysRun)
{
movementdivisor = walkDivisor;
}
else
{
movementdivisor = runDivisor;
}
// if velocity is zero, use position control; otherwise, velocity control
if (m_target_velocity.X == 0.0f && m_target_velocity.Y == 0.0f && m_target_velocity.Z == 0.0f && m_iscolliding)
{
// keep track of where we stopped. No more slippin' & slidin'
if (!m_zeroFlag)
{
m_zeroFlag = true;
m_zeroPosition.X = tempVector1.getX();
m_zeroPosition.Y = tempVector1.getY();
m_zeroPosition.Z = tempVector1.getZ();
}
if (m_pidControllerActive)
{
// We only want to deactivate the PID Controller if we think we want to have our surrogate
// react to the physics scene by moving it's position.
// Avatar to Avatar collisions
// Prim to avatar collisions
PhysicsVector pos = new PhysicsVector(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.X = (m_target_velocity.X - vel.X) * (PID_D) + (m_zeroPosition.X - pos.X) * (PID_P * 2);
vec.Y = (m_target_velocity.Y - vel.Y) * (PID_D) + (m_zeroPosition.Y - pos.Y) * (PID_P * 2);
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D) + (m_zeroPosition.Z - pos.Z) * PID_P;
}
}
//PidStatus = true;
}
else
{
m_pidControllerActive = true;
m_zeroFlag = false;
if (m_iscolliding && !m_flying)
{
// We're standing on something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D);
}
else if (m_iscolliding && m_flying)
{
// We're flying and colliding with something
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 16);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 16);
}
else if (!m_iscolliding && m_flying)
{
// we're in mid air suspended
vec.X = ((m_target_velocity.X / movementdivisor) - vel.X) * (PID_D / 6);
vec.Y = ((m_target_velocity.Y / movementdivisor) - vel.Y) * (PID_D / 6);
// We don't want linear velocity to cause our avatar to bounce, so we check target Z and actual velocity X, Y
// rebound preventing
if (m_target_velocity.Z < 0.025f && m_velocity.X < 0.25f && m_velocity.Y < 0.25f)
m_zeroFlag = true;
}
if (m_iscolliding && !m_flying && m_target_velocity.Z > 0.0f)
{
// We're colliding with something and we're not flying but we're moving
// This means we're walking or running.
PhysicsVector pos = new PhysicsVector(tempVector1.getX(), tempVector1.getY(), tempVector1.getZ());
vec.Z = (m_target_velocity.Z - vel.Z) * PID_D + (m_zeroPosition.Z - pos.Z) * PID_P;
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
else if (!m_iscolliding && !m_flying)
{
// we're not colliding and we're not flying so that means we're falling!
// m_iscolliding includes collisions with the ground.
// d.Vector3 pos = d.BodyGetPosition(Body);
if (m_target_velocity.X > 0)
{
vec.X = ((m_target_velocity.X - vel.X) / 1.2f) * PID_D;
}
if (m_target_velocity.Y > 0)
{
vec.Y = ((m_target_velocity.Y - vel.Y) / 1.2f) * PID_D;
}
}
if (m_flying)
{
vec.Z = (m_target_velocity.Z - vel.Z) * (PID_D);
}
}
if (m_flying)
{
// Slight PID correction
vec.Z += (((-1 * m_parent_scene.gravityz) * m_mass) * 0.06f);
//auto fly height. Kitto Flora
//d.Vector3 pos = d.BodyGetPosition(Body);
float target_altitude = m_parent_scene.GetTerrainHeightAtXY(m_position.X, m_position.Y) + 5.0f;
if (m_position.Z < target_altitude)
{
vec.Z += (target_altitude - m_position.Z) * PID_P * 5.0f;
}
}
if (Body != null && (((m_target_velocity.X > 0.2f || m_target_velocity.X < -0.2f) || (m_target_velocity.Y > 0.2f || m_target_velocity.Y < -0.2f))))
{
Body.setFriction(0.001f);
//m_log.DebugFormat("[PHYSICS]: Avatar force applied: {0}, Target:{1}", vec.ToString(), m_target_velocity.ToString());
}
if (Body != null)
{
int activationstate = Body.getActivationState();
if (activationstate == 0)
{
Body.forceActivationState(1);
}
}
doImpulse(vec, true);
}
/// <summary>
/// Updates the reported position and velocity. This essentially sends the data up to ScenePresence.
/// </summary>
public void UpdatePositionAndVelocity()
{
if (Body == null)
return;
//int val = Environment.TickCount;
CheckIfStandingOnObject();
//m_log.DebugFormat("time:{0}", Environment.TickCount - val);
//IsColliding = Body.checkCollideWith(m_parent_scene.TerrainBody);
tempTrans1.Dispose();
tempTrans1 = Body.getInterpolationWorldTransform();
tempVector1.Dispose();
tempVector1 = tempTrans1.getOrigin();
tempVector2.Dispose();
tempVector2 = Body.getInterpolationLinearVelocity();
// no lock; called from Simulate() -- if you call this from elsewhere, gotta lock or do Monitor.Enter/Exit!
PhysicsVector vec = new PhysicsVector(tempVector1.getX(),tempVector1.getY(),tempVector1.getZ());
// kluge to keep things in bounds. ODE lets dead avatars drift away (they should be removed!)
if (vec.X < -10.0f) vec.X = 0.0f;
if (vec.Y < -10.0f) vec.Y = 0.0f;
if (vec.X > (int)Constants.RegionSize + 10.2f) vec.X = (int)Constants.RegionSize + 10.2f;
if (vec.Y > (int)Constants.RegionSize + 10.2f) vec.Y = (int)Constants.RegionSize + 10.2f;
m_position.X = vec.X;
m_position.Y = vec.Y;
m_position.Z = vec.Z;
// Did we move last? = zeroflag
// This helps keep us from sliding all over
if (m_zeroFlag)
{
m_velocity.X = 0.0f;
m_velocity.Y = 0.0f;
m_velocity.Z = 0.0f;
// Did we send out the 'stopped' message?
if (!m_lastUpdateSent)
{
m_lastUpdateSent = true;
//base.RequestPhysicsterseUpdate();
}
}
else
{
m_lastUpdateSent = false;
vec = new PhysicsVector(tempVector2.getX(), tempVector2.getY(), tempVector2.getZ());
m_velocity.X = (vec.X);
m_velocity.Y = (vec.Y);
m_velocity.Z = (vec.Z);
//m_log.Debug(m_target_velocity);
if (m_velocity.Z < -6 && !m_hackSentFall)
{
m_hackSentFall = true;
m_pidControllerActive = false;
}
else if (m_flying && !m_hackSentFly)
{
//m_hackSentFly = true;
//base.SendCollisionUpdate(new CollisionEventUpdate());
}
else
{
m_hackSentFly = false;
m_hackSentFall = false;
}
}
if (Body != null)
{
if (Body.getFriction() < 0.9f)
Body.setFriction(0.9f);
}
//if (Body != null)
// Body.clearForces();
}
public void CheckIfStandingOnObject()
{
float capsuleHalfHeight = ((CAPSULE_LENGTH + 2*CAPSULE_RADIUS)*0.5f);
tempVector5RayCast.setValue(m_position.X, m_position.Y, m_position.Z);
tempVector6RayCast.setValue(m_position.X, m_position.Y, m_position.Z - 1 * capsuleHalfHeight * 1.1f);
ClosestCastResult.Dispose();
ClosestCastResult = new ClosestNotMeRayResultCallback(Body);
try
{
m_parent_scene.getBulletWorld().rayTest(tempVector5RayCast, tempVector6RayCast, ClosestCastResult);
}
catch (AccessViolationException)
{
m_log.Debug("BAD!");
}
if (ClosestCastResult.hasHit())
{
if (tempVector7RayCast != null)
tempVector7RayCast.Dispose();
//tempVector7RayCast = ClosestCastResult.getHitPointWorld();
/*if (tempVector7RayCast == null) // null == no result also
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
return;
}
float zVal = tempVector7RayCast.getZ();
if (zVal != 0)
m_log.Debug("[PHYSICS]: HAAAA");
if (zVal < m_position.Z && zVal > ((CAPSULE_LENGTH + 2 * CAPSULE_RADIUS) *0.5f))
{
CollidingObj = true;
IsColliding = true;
}
else
{
CollidingObj = false;
IsColliding = false;
CollidingGround = false;
}*/
//height+2*radius = capsule full length
//CollidingObj = true;
//IsColliding = true;
m_iscolliding = true;
}
else
{
//CollidingObj = false;
//IsColliding = false;
//CollidingGround = false;
m_iscolliding = false;
}
}
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Storage;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite
{
/// <summary>Represents a view available in a database.</summary>
/// <remarks>Represents a view available in a database.</remarks>
public sealed class View
{
/// <exclude></exclude>
public const int ReduceBatchSize = 100;
/// <exclude></exclude>
public enum TDViewCollation
{
TDViewCollationUnicode,
TDViewCollationRaw,
TDViewCollationASCII
}
private Database database;
private string name;
private int viewId;
private Mapper mapBlock;
private Reducer reduceBlock;
private View.TDViewCollation collation;
private static ViewCompiler compiler;
/// <summary>The registered object, if any, that can compile map/reduce functions from source code.
/// </summary>
/// <remarks>The registered object, if any, that can compile map/reduce functions from source code.
/// </remarks>
[InterfaceAudience.Public]
public static ViewCompiler GetCompiler()
{
return compiler;
}
/// <summary>Registers an object that can compile map/reduce functions from source code.
/// </summary>
/// <remarks>Registers an object that can compile map/reduce functions from source code.
/// </remarks>
[InterfaceAudience.Public]
public static void SetCompiler(ViewCompiler compiler)
{
Couchbase.Lite.View.compiler = compiler;
}
/// <summary>Constructor</summary>
[InterfaceAudience.Private]
internal View(Database database, string name)
{
this.database = database;
this.name = name;
this.viewId = -1;
// means 'unknown'
this.collation = View.TDViewCollation.TDViewCollationUnicode;
}
/// <summary>Get the database that owns this view.</summary>
/// <remarks>Get the database that owns this view.</remarks>
[InterfaceAudience.Public]
public Database GetDatabase()
{
return database;
}
/// <summary>Get the name of the view.</summary>
/// <remarks>Get the name of the view.</remarks>
[InterfaceAudience.Public]
public string GetName()
{
return name;
}
/// <summary>The map function that controls how index rows are created from documents.
/// </summary>
/// <remarks>The map function that controls how index rows are created from documents.
/// </remarks>
[InterfaceAudience.Public]
public Mapper GetMap()
{
return mapBlock;
}
/// <summary>The optional reduce function, which aggregates together multiple rows.</summary>
/// <remarks>The optional reduce function, which aggregates together multiple rows.</remarks>
[InterfaceAudience.Public]
public Reducer GetReduce()
{
return reduceBlock;
}
/// <summary>Is the view's index currently out of date?</summary>
[InterfaceAudience.Public]
public bool IsStale()
{
return (GetLastSequenceIndexed() < database.GetLastSequenceNumber());
}
/// <summary>Get the last sequence number indexed so far.</summary>
/// <remarks>Get the last sequence number indexed so far.</remarks>
[InterfaceAudience.Public]
public long GetLastSequenceIndexed()
{
string sql = "SELECT lastSequence FROM views WHERE name=?";
string[] args = new string[] { name };
Cursor cursor = null;
long result = -1;
try
{
Log.D(Database.TagSql, Sharpen.Thread.CurrentThread().GetName() + " start running query: "
+ sql);
cursor = database.GetDatabase().RawQuery(sql, args);
Log.D(Database.TagSql, Sharpen.Thread.CurrentThread().GetName() + " finish running query: "
+ sql);
if (cursor.MoveToNext())
{
result = cursor.GetLong(0);
}
}
catch (Exception e)
{
Log.E(Database.Tag, "Error getting last sequence indexed", e);
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
return result;
}
/// <summary>Defines a view that has no reduce function.</summary>
/// <remarks>
/// Defines a view that has no reduce function.
/// See setMapReduce() for more information.
/// </remarks>
[InterfaceAudience.Public]
public bool SetMap(Mapper mapBlock, string version)
{
return SetMapReduce(mapBlock, null, version);
}
/// <summary>Defines a view's functions.</summary>
/// <remarks>
/// Defines a view's functions.
/// The view's definition is given as a class that conforms to the Mapper or
/// Reducer interface (or null to delete the view). The body of the block
/// should call the 'emit' object (passed in as a paramter) for every key/value pair
/// it wants to write to the view.
/// Since the function itself is obviously not stored in the database (only a unique
/// string idenfitying it), you must re-define the view on every launch of the app!
/// If the database needs to rebuild the view but the function hasn't been defined yet,
/// it will fail and the view will be empty, causing weird problems later on.
/// It is very important that this block be a law-abiding map function! As in other
/// languages, it must be a "pure" function, with no side effects, that always emits
/// the same values given the same input document. That means that it should not access
/// or change any external state; be careful, since callbacks make that so easy that you
/// might do it inadvertently! The callback may be called on any thread, or on
/// multiple threads simultaneously. This won't be a problem if the code is "pure" as
/// described above, since it will as a consequence also be thread-safe.
/// </remarks>
[InterfaceAudience.Public]
public bool SetMapReduce(Mapper mapBlock, Reducer reduceBlock, string version)
{
System.Diagnostics.Debug.Assert((mapBlock != null));
System.Diagnostics.Debug.Assert((version != null));
this.mapBlock = mapBlock;
this.reduceBlock = reduceBlock;
if (!database.Open())
{
return false;
}
// Update the version column in the database. This is a little weird looking
// because we want to
// avoid modifying the database if the version didn't change, and because the
// row might not exist yet.
SQLiteStorageEngine storageEngine = this.database.GetDatabase();
// Older Android doesnt have reliable insert or ignore, will to 2 step
// FIXME review need for change to execSQL, manual call to changes()
string sql = "SELECT name, version FROM views WHERE name=?";
string[] args = new string[] { name };
Cursor cursor = null;
try
{
cursor = storageEngine.RawQuery(sql, args);
if (!cursor.MoveToNext())
{
// no such record, so insert
ContentValues insertValues = new ContentValues();
insertValues.Put("name", name);
insertValues.Put("version", version);
storageEngine.Insert("views", null, insertValues);
return true;
}
ContentValues updateValues = new ContentValues();
updateValues.Put("version", version);
updateValues.Put("lastSequence", 0);
string[] whereArgs = new string[] { name, version };
int rowsAffected = storageEngine.Update("views", updateValues, "name=? AND version!=?"
, whereArgs);
return (rowsAffected > 0);
}
catch (SQLException e)
{
Log.E(Database.Tag, "Error setting map block", e);
return false;
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
}
/// <summary>Deletes the view's persistent index.</summary>
/// <remarks>Deletes the view's persistent index. It will be regenerated on the next query.
/// </remarks>
[InterfaceAudience.Public]
public void DeleteIndex()
{
if (GetViewId() < 0)
{
return;
}
bool success = false;
try
{
database.BeginTransaction();
string[] whereArgs = new string[] { Sharpen.Extensions.ToString(GetViewId()) };
database.GetDatabase().Delete("maps", "view_id=?", whereArgs);
ContentValues updateValues = new ContentValues();
updateValues.Put("lastSequence", 0);
database.GetDatabase().Update("views", updateValues, "view_id=?", whereArgs);
success = true;
}
catch (SQLException e)
{
Log.E(Database.Tag, "Error removing index", e);
}
finally
{
database.EndTransaction(success);
}
}
/// <summary>Deletes the view, persistently.</summary>
/// <remarks>Deletes the view, persistently.</remarks>
[InterfaceAudience.Public]
public void Delete()
{
database.DeleteViewNamed(name);
viewId = 0;
}
/// <summary>Creates a new query object for this view.</summary>
/// <remarks>Creates a new query object for this view. The query can be customized and then executed.
/// </remarks>
[InterfaceAudience.Public]
public Query CreateQuery()
{
return new Query(GetDatabase(), this);
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public int GetViewId()
{
if (viewId < 0)
{
string sql = "SELECT view_id FROM views WHERE name=?";
string[] args = new string[] { name };
Cursor cursor = null;
try
{
cursor = database.GetDatabase().RawQuery(sql, args);
if (cursor.MoveToNext())
{
viewId = cursor.GetInt(0);
}
else
{
viewId = 0;
}
}
catch (SQLException e)
{
Log.E(Database.Tag, "Error getting view id", e);
viewId = 0;
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
}
return viewId;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public void DatabaseClosing()
{
database = null;
viewId = 0;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public string ToJSONString(object @object)
{
if (@object == null)
{
return null;
}
string result = null;
try
{
result = Manager.GetObjectMapper().WriteValueAsString(@object);
}
catch (Exception e)
{
Log.W(Database.Tag, "Exception serializing object to json: " + @object, e);
}
return result;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public object FromJSON(byte[] json)
{
if (json == null)
{
return null;
}
object result = null;
try
{
result = Manager.GetObjectMapper().ReadValue<object>(json);
}
catch (Exception e)
{
Log.W(Database.Tag, "Exception parsing json", e);
}
return result;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public View.TDViewCollation GetCollation()
{
return collation;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public void SetCollation(View.TDViewCollation collation)
{
this.collation = collation;
}
/// <summary>Updates the view's index (incrementally) if necessary.</summary>
/// <remarks>Updates the view's index (incrementally) if necessary.</remarks>
/// <returns>200 if updated, 304 if already up-to-date, else an error code</returns>
/// <exclude></exclude>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Private]
public void UpdateIndex()
{
Log.V(Database.Tag, "Re-indexing view " + name + " ...");
System.Diagnostics.Debug.Assert((mapBlock != null));
if (GetViewId() < 0)
{
string msg = string.Format("getViewId() < 0");
throw new CouchbaseLiteException(msg, new Status(Status.NotFound));
}
database.BeginTransaction();
Status result = new Status(Status.InternalServerError);
Cursor cursor = null;
try
{
long lastSequence = GetLastSequenceIndexed();
long dbMaxSequence = database.GetLastSequenceNumber();
if (lastSequence == dbMaxSequence)
{
// nothing to do (eg, kCBLStatusNotModified)
string msg = string.Format("lastSequence (%d) == dbMaxSequence (%d), nothing to do"
, lastSequence, dbMaxSequence);
Log.D(Database.Tag, msg);
result.SetCode(Status.Ok);
return;
}
// First remove obsolete emitted results from the 'maps' table:
long sequence = lastSequence;
if (lastSequence < 0)
{
string msg = string.Format("lastSequence < 0 (%s)", lastSequence);
throw new CouchbaseLiteException(msg, new Status(Status.InternalServerError));
}
if (lastSequence == 0)
{
// If the lastSequence has been reset to 0, make sure to remove
// any leftover rows:
string[] whereArgs = new string[] { Sharpen.Extensions.ToString(GetViewId()) };
database.GetDatabase().Delete("maps", "view_id=?", whereArgs);
}
else
{
// Delete all obsolete map results (ones from since-replaced
// revisions):
string[] args = new string[] { Sharpen.Extensions.ToString(GetViewId()), System.Convert.ToString
(lastSequence), System.Convert.ToString(lastSequence) };
database.GetDatabase().ExecSQL("DELETE FROM maps WHERE view_id=? AND sequence IN ("
+ "SELECT parent FROM revs WHERE sequence>? " + "AND parent>0 AND parent<=?)",
args);
}
int deleted = 0;
cursor = database.GetDatabase().RawQuery("SELECT changes()", null);
cursor.MoveToNext();
deleted = cursor.GetInt(0);
cursor.Close();
// This is the emit() block, which gets called from within the
// user-defined map() block
// that's called down below.
AbstractTouchMapEmitBlock emitBlock = new _AbstractTouchMapEmitBlock_446(this);
// find a better way to propagate this back
// Now scan every revision added since the last time the view was
// indexed:
string[] selectArgs = new string[] { System.Convert.ToString(lastSequence) };
cursor = database.GetDatabase().RawQuery("SELECT revs.doc_id, sequence, docid, revid, json FROM revs, docs "
+ "WHERE sequence>? AND current!=0 AND deleted=0 " + "AND revs.doc_id = docs.doc_id "
+ "ORDER BY revs.doc_id, revid DESC", selectArgs);
cursor.MoveToNext();
long lastDocID = 0;
while (!cursor.IsAfterLast())
{
long docID = cursor.GetLong(0);
if (docID != lastDocID)
{
// Only look at the first-iterated revision of any document,
// because this is the
// one with the highest revid, hence the "winning" revision
// of a conflict.
lastDocID = docID;
// Reconstitute the document as a dictionary:
sequence = cursor.GetLong(1);
string docId = cursor.GetString(2);
if (docId.StartsWith("_design/"))
{
// design docs don't get indexed!
cursor.MoveToNext();
continue;
}
string revId = cursor.GetString(3);
byte[] json = cursor.GetBlob(4);
IDictionary<string, object> properties = database.DocumentPropertiesFromJSON(json
, docId, revId, false, sequence, EnumSet.NoneOf<Database.TDContentOptions>());
if (properties != null)
{
// Call the user-defined map() to emit new key/value
// pairs from this revision:
Log.V(Database.Tag, " call map for sequence=" + System.Convert.ToString(sequence
));
emitBlock.SetSequence(sequence);
mapBlock.Map(properties, emitBlock);
}
}
cursor.MoveToNext();
}
// Finally, record the last revision sequence number that was
// indexed:
ContentValues updateValues = new ContentValues();
updateValues.Put("lastSequence", dbMaxSequence);
string[] whereArgs_1 = new string[] { Sharpen.Extensions.ToString(GetViewId()) };
database.GetDatabase().Update("views", updateValues, "view_id=?", whereArgs_1);
// FIXME actually count number added :)
Log.V(Database.Tag, "...Finished re-indexing view " + name + " up to sequence " +
System.Convert.ToString(dbMaxSequence) + " (deleted " + deleted + " added " + "?"
+ ")");
result.SetCode(Status.Ok);
}
catch (SQLException e)
{
throw new CouchbaseLiteException(e, new Status(Status.DbError));
}
finally
{
if (cursor != null)
{
cursor.Close();
}
if (!result.IsSuccessful())
{
Log.W(Database.Tag, "Failed to rebuild view " + name + ": " + result.GetCode());
}
if (database != null)
{
database.EndTransaction(result.IsSuccessful());
}
}
}
private sealed class _AbstractTouchMapEmitBlock_446 : AbstractTouchMapEmitBlock
{
public _AbstractTouchMapEmitBlock_446(View _enclosing)
{
this._enclosing = _enclosing;
}
public override void Emit(object key, object value)
{
try
{
string valueJson;
string keyJson = Manager.GetObjectMapper().WriteValueAsString(key);
if (value == null)
{
valueJson = null;
}
else
{
valueJson = Manager.GetObjectMapper().WriteValueAsString(value);
}
Log.V(Database.Tag, " emit(" + keyJson + ", " + valueJson + ")");
ContentValues insertValues = new ContentValues();
insertValues.Put("view_id", this._enclosing.GetViewId());
insertValues.Put("sequence", this.sequence);
insertValues.Put("key", keyJson);
insertValues.Put("value", valueJson);
this._enclosing.database.GetDatabase().Insert("maps", null, insertValues);
}
catch (Exception e)
{
Log.E(Database.Tag, "Error emitting", e);
}
}
private readonly View _enclosing;
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public Cursor ResultSetWithOptions(QueryOptions options)
{
if (options == null)
{
options = new QueryOptions();
}
// OPT: It would be faster to use separate tables for raw-or ascii-collated views so that
// they could be indexed with the right collation, instead of having to specify it here.
string collationStr = string.Empty;
if (collation == View.TDViewCollation.TDViewCollationASCII)
{
collationStr += " COLLATE JSON_ASCII";
}
else
{
if (collation == View.TDViewCollation.TDViewCollationRaw)
{
collationStr += " COLLATE JSON_RAW";
}
}
string sql = "SELECT key, value, docid, revs.sequence";
if (options.IsIncludeDocs())
{
sql = sql + ", revid, json";
}
sql = sql + " FROM maps, revs, docs WHERE maps.view_id=?";
IList<string> argsList = new AList<string>();
argsList.AddItem(Sharpen.Extensions.ToString(GetViewId()));
if (options.GetKeys() != null)
{
sql += " AND key in (";
string item = "?";
foreach (object key in options.GetKeys())
{
sql += item;
item = ", ?";
argsList.AddItem(ToJSONString(key));
}
sql += ")";
}
object minKey = options.GetStartKey();
object maxKey = options.GetEndKey();
bool inclusiveMin = true;
bool inclusiveMax = options.IsInclusiveEnd();
if (options.IsDescending())
{
minKey = maxKey;
maxKey = options.GetStartKey();
inclusiveMin = inclusiveMax;
inclusiveMax = true;
}
if (minKey != null)
{
System.Diagnostics.Debug.Assert((minKey is string));
if (inclusiveMin)
{
sql += " AND key >= ?";
}
else
{
sql += " AND key > ?";
}
sql += collationStr;
argsList.AddItem(ToJSONString(minKey));
}
if (maxKey != null)
{
System.Diagnostics.Debug.Assert((maxKey is string));
if (inclusiveMax)
{
sql += " AND key <= ?";
}
else
{
sql += " AND key < ?";
}
sql += collationStr;
argsList.AddItem(ToJSONString(maxKey));
}
sql = sql + " AND revs.sequence = maps.sequence AND docs.doc_id = revs.doc_id ORDER BY key";
sql += collationStr;
if (options.IsDescending())
{
sql = sql + " DESC";
}
sql = sql + " LIMIT ? OFFSET ?";
argsList.AddItem(Sharpen.Extensions.ToString(options.GetLimit()));
argsList.AddItem(Sharpen.Extensions.ToString(options.GetSkip()));
Log.V(Database.Tag, "Query " + name + ": " + sql);
Cursor cursor = database.GetDatabase().RawQuery(sql, Sharpen.Collections.ToArray(
argsList, new string[argsList.Count]));
return cursor;
}
/// <summary>Are key1 and key2 grouped together at this groupLevel?</summary>
/// <exclude></exclude>
[InterfaceAudience.Private]
public static bool GroupTogether(object key1, object key2, int groupLevel)
{
if (groupLevel == 0 || !(key1 is IList) || !(key2 is IList))
{
return key1.Equals(key2);
}
IList<object> key1List = (IList<object>)key1;
IList<object> key2List = (IList<object>)key2;
int end = Math.Min(groupLevel, Math.Min(key1List.Count, key2List.Count));
for (int i = 0; i < end; ++i)
{
if (!key1List[i].Equals(key2List[i]))
{
return false;
}
}
return true;
}
/// <summary>Returns the prefix of the key to use in the result row, at this groupLevel
/// </summary>
/// <exclude></exclude>
[InterfaceAudience.Private]
public static object GroupKey(object key, int groupLevel)
{
if (groupLevel > 0 && (key is IList) && (((IList<object>)key).Count > groupLevel))
{
return ((IList<object>)key).SubList(0, groupLevel);
}
else
{
return key;
}
}
/// <exclude></exclude>
[InterfaceAudience.Private]
public IList<IDictionary<string, object>> Dump()
{
if (GetViewId() < 0)
{
return null;
}
string[] selectArgs = new string[] { Sharpen.Extensions.ToString(GetViewId()) };
Cursor cursor = null;
IList<IDictionary<string, object>> result = null;
try
{
cursor = database.GetDatabase().RawQuery("SELECT sequence, key, value FROM maps WHERE view_id=? ORDER BY key"
, selectArgs);
cursor.MoveToNext();
result = new AList<IDictionary<string, object>>();
while (!cursor.IsAfterLast())
{
IDictionary<string, object> row = new Dictionary<string, object>();
row.Put("seq", cursor.GetInt(0));
row.Put("key", cursor.GetString(1));
row.Put("value", cursor.GetString(2));
result.AddItem(row);
cursor.MoveToNext();
}
}
catch (SQLException e)
{
Log.E(Database.Tag, "Error dumping view", e);
return null;
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
return result;
}
/// <exclude></exclude>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Private]
internal IList<QueryRow> ReducedQuery(Cursor cursor, bool group, int groupLevel)
{
IList<object> keysToReduce = null;
IList<object> valuesToReduce = null;
object lastKey = null;
if (GetReduce() != null)
{
keysToReduce = new AList<object>(ReduceBatchSize);
valuesToReduce = new AList<object>(ReduceBatchSize);
}
IList<QueryRow> rows = new AList<QueryRow>();
cursor.MoveToNext();
while (!cursor.IsAfterLast())
{
object keyData = FromJSON(cursor.GetBlob(0));
object value = FromJSON(cursor.GetBlob(1));
System.Diagnostics.Debug.Assert((keyData != null));
if (group && !GroupTogether(keyData, lastKey, groupLevel))
{
if (lastKey != null)
{
// This pair starts a new group, so reduce & record the last one:
object reduced = (reduceBlock != null) ? reduceBlock.Reduce(keysToReduce, valuesToReduce
, false) : null;
object key = GroupKey(lastKey, groupLevel);
QueryRow row = new QueryRow(null, 0, key, reduced, null);
row.SetDatabase(database);
rows.AddItem(row);
keysToReduce.Clear();
valuesToReduce.Clear();
}
lastKey = keyData;
}
keysToReduce.AddItem(keyData);
valuesToReduce.AddItem(value);
cursor.MoveToNext();
}
if (keysToReduce.Count > 0)
{
// Finish the last group (or the entire list, if no grouping):
object key = group ? GroupKey(lastKey, groupLevel) : null;
object reduced = (reduceBlock != null) ? reduceBlock.Reduce(keysToReduce, valuesToReduce
, false) : null;
QueryRow row = new QueryRow(null, 0, key, reduced, null);
row.SetDatabase(database);
rows.AddItem(row);
}
return rows;
}
/// <summary>Queries the view.</summary>
/// <remarks>Queries the view. Does NOT first update the index.</remarks>
/// <param name="options">The options to use.</param>
/// <returns>An array of QueryRow objects.</returns>
/// <exclude></exclude>
/// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception>
[InterfaceAudience.Private]
public IList<QueryRow> QueryWithOptions(QueryOptions options)
{
if (options == null)
{
options = new QueryOptions();
}
Cursor cursor = null;
IList<QueryRow> rows = new AList<QueryRow>();
try
{
cursor = ResultSetWithOptions(options);
int groupLevel = options.GetGroupLevel();
bool group = options.IsGroup() || (groupLevel > 0);
bool reduce = options.IsReduce() || group;
if (reduce && (reduceBlock == null) && !group)
{
string msg = "Cannot use reduce option in view " + name + " which has no reduce block defined";
Log.W(Database.Tag, msg);
throw new CouchbaseLiteException(new Status(Status.BadRequest));
}
if (reduce || group)
{
// Reduced or grouped query:
rows = ReducedQuery(cursor, group, groupLevel);
}
else
{
// regular query
cursor.MoveToNext();
while (!cursor.IsAfterLast())
{
object keyData = FromJSON(cursor.GetBlob(0));
// TODO: delay parsing this for increased efficiency
object value = FromJSON(cursor.GetBlob(1));
// TODO: ditto
string docId = cursor.GetString(2);
int sequence = Sharpen.Extensions.ValueOf(cursor.GetString(3));
IDictionary<string, object> docContents = null;
if (options.IsIncludeDocs())
{
// http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
if (value is IDictionary && ((IDictionary)value).ContainsKey("_id"))
{
string linkedDocId = (string)((IDictionary)value).Get("_id");
RevisionInternal linkedDoc = database.GetDocumentWithIDAndRev(linkedDocId, null,
EnumSet.NoneOf<Database.TDContentOptions>());
docContents = linkedDoc.GetProperties();
}
else
{
docContents = database.DocumentPropertiesFromJSON(cursor.GetBlob(5), docId, cursor
.GetString(4), false, cursor.GetLong(3), options.GetContentOptions());
}
}
QueryRow row = new QueryRow(docId, sequence, keyData, value, docContents);
row.SetDatabase(database);
rows.AddItem(row);
cursor.MoveToNext();
}
}
}
catch (SQLException e)
{
string errMsg = string.Format("Error querying view: %s", this);
Log.E(Database.Tag, errMsg, e);
throw new CouchbaseLiteException(errMsg, e, new Status(Status.DbError));
}
finally
{
if (cursor != null)
{
cursor.Close();
}
}
return rows;
}
/// <summary>Utility function to use in reduce blocks.</summary>
/// <remarks>Utility function to use in reduce blocks. Totals an array of Numbers.</remarks>
/// <exclude></exclude>
[InterfaceAudience.Private]
public static double TotalValues(IList<object> values)
{
double total = 0;
foreach (object @object in values)
{
if (@object is Number)
{
Number number = (Number)@object;
total += number;
}
else
{
Log.W(Database.Tag, "Warning non-numeric value found in totalValues: " + @object);
}
}
return total;
}
}
internal abstract class AbstractTouchMapEmitBlock : Emitter
{
protected internal long sequence = 0;
internal virtual void SetSequence(long sequence)
{
this.sequence = sequence;
}
public abstract void Emit(object arg1, object arg2);
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/groups/unassigned_booking_holds.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 HOLMS.Types.Booking.Groups {
/// <summary>Holder for reflection information generated from booking/groups/unassigned_booking_holds.proto</summary>
public static partial class UnassignedBookingHoldsReflection {
#region Descriptor
/// <summary>File descriptor for booking/groups/unassigned_booking_holds.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static UnassignedBookingHoldsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ci1ib29raW5nL2dyb3Vwcy91bmFzc2lnbmVkX2Jvb2tpbmdfaG9sZHMucHJv",
"dG8SGmhvbG1zLnR5cGVzLmJvb2tpbmcuZ3JvdXBzGipwcmltaXRpdmUvcGJf",
"aW5jbHVzaXZlX29wc2RhdGVfcmFuZ2UucHJvdG8aKXN1cHBseS9ldmVudF9i",
"b29raW5nX2hvbGRfaW5kaWNhdG9yLnByb3RvGitzdXBwbHkvcm9vbV90eXBl",
"cy9yb29tX3R5cGVfaW5kaWNhdG9yLnByb3RvGi5ib29raW5nL2luZGljYXRv",
"cnMvcmVzZXJ2YXRpb25faW5kaWNhdG9yLnByb3RvIroCChZVbmFzc2lnbmVk",
"Qm9va2luZ0hvbGRzEkkKEmV2ZW50X2Jvb2tpbmdfaG9sZBgBIAEoCzItLmhv",
"bG1zLnR5cGVzLnN1cHBseS5FdmVudEJvb2tpbmdIb2xkSW5kaWNhdG9yEkIK",
"CmRhdGVfcmFuZ2UYAiABKAsyLi5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJJ",
"bmNsdXNpdmVPcHNkYXRlUmFuZ2USQwoJcm9vbV90eXBlGAMgASgLMjAuaG9s",
"bXMudHlwZXMuc3VwcGx5LnJvb21fdHlwZXMuUm9vbVR5cGVJbmRpY2F0b3IS",
"TAoOcmVzZXJ2YXRpb25faWQYBCABKAsyNC5ob2xtcy50eXBlcy5ib29raW5n",
"LmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3JCLVoOYm9va2luZy9n",
"cm91cHOqAhpIT0xNUy5UeXBlcy5Cb29raW5nLkdyb3Vwc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Supply.EventBookingHoldIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Groups.UnassignedBookingHolds), global::HOLMS.Types.Booking.Groups.UnassignedBookingHolds.Parser, new[]{ "EventBookingHold", "DateRange", "RoomType", "ReservationId" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class UnassignedBookingHolds : pb::IMessage<UnassignedBookingHolds> {
private static readonly pb::MessageParser<UnassignedBookingHolds> _parser = new pb::MessageParser<UnassignedBookingHolds>(() => new UnassignedBookingHolds());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<UnassignedBookingHolds> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Groups.UnassignedBookingHoldsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnassignedBookingHolds() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnassignedBookingHolds(UnassignedBookingHolds other) : this() {
EventBookingHold = other.eventBookingHold_ != null ? other.EventBookingHold.Clone() : null;
DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null;
RoomType = other.roomType_ != null ? other.RoomType.Clone() : null;
ReservationId = other.reservationId_ != null ? other.ReservationId.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public UnassignedBookingHolds Clone() {
return new UnassignedBookingHolds(this);
}
/// <summary>Field number for the "event_booking_hold" field.</summary>
public const int EventBookingHoldFieldNumber = 1;
private global::HOLMS.Types.Supply.EventBookingHoldIndicator eventBookingHold_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.EventBookingHoldIndicator EventBookingHold {
get { return eventBookingHold_; }
set {
eventBookingHold_ = value;
}
}
/// <summary>Field number for the "date_range" field.</summary>
public const int DateRangeFieldNumber = 2;
private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange {
get { return dateRange_; }
set {
dateRange_ = value;
}
}
/// <summary>Field number for the "room_type" field.</summary>
public const int RoomTypeFieldNumber = 3;
private global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator roomType_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator RoomType {
get { return roomType_; }
set {
roomType_ = value;
}
}
/// <summary>Field number for the "reservation_id" field.</summary>
public const int ReservationIdFieldNumber = 4;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservationId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator ReservationId {
get { return reservationId_; }
set {
reservationId_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as UnassignedBookingHolds);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(UnassignedBookingHolds other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(EventBookingHold, other.EventBookingHold)) return false;
if (!object.Equals(DateRange, other.DateRange)) return false;
if (!object.Equals(RoomType, other.RoomType)) return false;
if (!object.Equals(ReservationId, other.ReservationId)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (eventBookingHold_ != null) hash ^= EventBookingHold.GetHashCode();
if (dateRange_ != null) hash ^= DateRange.GetHashCode();
if (roomType_ != null) hash ^= RoomType.GetHashCode();
if (reservationId_ != null) hash ^= ReservationId.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 (eventBookingHold_ != null) {
output.WriteRawTag(10);
output.WriteMessage(EventBookingHold);
}
if (dateRange_ != null) {
output.WriteRawTag(18);
output.WriteMessage(DateRange);
}
if (roomType_ != null) {
output.WriteRawTag(26);
output.WriteMessage(RoomType);
}
if (reservationId_ != null) {
output.WriteRawTag(34);
output.WriteMessage(ReservationId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (eventBookingHold_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(EventBookingHold);
}
if (dateRange_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange);
}
if (roomType_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType);
}
if (reservationId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(UnassignedBookingHolds other) {
if (other == null) {
return;
}
if (other.eventBookingHold_ != null) {
if (eventBookingHold_ == null) {
eventBookingHold_ = new global::HOLMS.Types.Supply.EventBookingHoldIndicator();
}
EventBookingHold.MergeFrom(other.EventBookingHold);
}
if (other.dateRange_ != null) {
if (dateRange_ == null) {
dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
DateRange.MergeFrom(other.DateRange);
}
if (other.roomType_ != null) {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
RoomType.MergeFrom(other.RoomType);
}
if (other.reservationId_ != null) {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
ReservationId.MergeFrom(other.ReservationId);
}
}
[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: {
if (eventBookingHold_ == null) {
eventBookingHold_ = new global::HOLMS.Types.Supply.EventBookingHoldIndicator();
}
input.ReadMessage(eventBookingHold_);
break;
}
case 18: {
if (dateRange_ == null) {
dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange();
}
input.ReadMessage(dateRange_);
break;
}
case 26: {
if (roomType_ == null) {
roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomTypeIndicator();
}
input.ReadMessage(roomType_);
break;
}
case 34: {
if (reservationId_ == null) {
reservationId_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservationId_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
//
// Booter.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 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.
//
//
// Crazy Banshee Boot Procedure
//
// [Exec or DBus Activation] <---------------------------------------------------------.
// | |
// v |
// [Bootloader (Banshee.exe)] |
// | |
// v yes |
// <org.bansheeproject.Banshee?> -------> [Load DBus Proxy Client (Halie.exe)] -----. |
// |no | |
// v yes | |
// <org.bansheeproject.CollectionIndexer?> -------> [Tell Indexer to Reboot] -----/IPC/'
// |no |
// v yes |
// <command line contains --indexer?> -------> [Load Indexer Client (Beroe.exe)] |
// |no |
// v yes |
// <command line contains --client=XYZ> -------> [Load XYZ Client] |
// |no |
// v |
// [Load Primary Interface Client (Nereid.exe)] <-----------------------------------'
//
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Mono.Unix;
using NDesk.DBus;
using Hyena;
using Hyena.CommandLine;
using Banshee.Base;
using Banshee.ServiceStack;
using Banshee.Collection.Indexer;
namespace Booter
{
public static class Booter
{
public static void Main ()
{
Paths.ApplicationName = Application.InternalName;
if (CheckHelpVersion ()) {
return;
}
if (DBusConnection.ApplicationInstanceAlreadyRunning) {
// DBus Command/Query/File Proxy Client
BootClient ("Halie");
NotifyStartupComplete ();
} else if (DBusConnection.NameHasOwner ("CollectionIndexer")) {
// Tell the existing indexer to start Banshee when it's done
IIndexerClient indexer = DBusServiceManager.FindInstance<IIndexerClient> ("CollectionIndexer", "/IndexerClient");
try {
indexer.Hello ();
indexer.RebootWhenFinished (Environment.GetCommandLineArgs ());
Log.Warning ("The Banshee indexer is currently running. Banshee will be started when the indexer finishes.");
} catch (Exception e) {
Log.Exception ("CollectionIndexer found on the Bus, but doesn't say Hello", e);
}
} else if (ApplicationContext.CommandLine.Contains ("indexer")) {
// Indexer Client
BootClient ("Beroe");
} else if (ApplicationContext.CommandLine.Contains ("client")) {
BootClient (Path.GetFileNameWithoutExtension (ApplicationContext.CommandLine["client"]));
} else {
BootClient ("Nereid");
}
}
private static void BootClient (string clientName)
{
AppDomain.CurrentDomain.ExecuteAssembly (Path.Combine (Path.GetDirectoryName (
Assembly.GetEntryAssembly ().Location), String.Format ("{0}.exe", clientName)));
}
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern bool gdk_init_check (IntPtr argc, IntPtr argv);
[DllImport ("libgdk-win32-2.0-0.dll")]
private static extern void gdk_notify_startup_complete ();
private static void NotifyStartupComplete ()
{
try {
if (gdk_init_check (IntPtr.Zero, IntPtr.Zero)) {
gdk_notify_startup_complete ();
}
} catch (Exception e) {
Hyena.Log.Exception ("Problem with NotifyStartupComplete", e);
}
}
private static bool CheckHelpVersion ()
{
if (ApplicationContext.CommandLine.ContainsStart ("help")) {
ShowHelp ();
return true;
} else if (ApplicationContext.CommandLine.Contains ("version")) {
ShowVersion ();
return true;
}
return false;
}
private static void ShowHelp ()
{
Console.WriteLine ("Usage: {0} [options...] [files|URIs...]", "banshee-1");
Console.WriteLine ();
Layout commands = new Layout (
new LayoutGroup ("help", Catalog.GetString ("Help Options"),
new LayoutOption ("help", Catalog.GetString ("Show this help")),
new LayoutOption ("help-playback", Catalog.GetString ("Show options for controlling playback")),
new LayoutOption ("help-query-track", Catalog.GetString ("Show options for querying the playing track")),
new LayoutOption ("help-query-player", Catalog.GetString ("Show options for querying the playing engine")),
new LayoutOption ("help-ui", Catalog.GetString ("Show options for the user interface")),
new LayoutOption ("help-debug", Catalog.GetString ("Show options for developers and debugging")),
new LayoutOption ("help-all", Catalog.GetString ("Show all option groups")),
new LayoutOption ("version", Catalog.GetString ("Show version information"))
),
new LayoutGroup ("playback", Catalog.GetString ("Playback Control Options"),
new LayoutOption ("next", Catalog.GetString ("Play the next track, optionally restarting if the 'restart' value is set")),
new LayoutOption ("previous", Catalog.GetString ("Play the previous track, optionally restarting if the 'restart value is set")),
new LayoutOption ("restart-or-previous", Catalog.GetString ("If the current song has been played longer than 4 seconds then restart it, otherwise the same as --previous")),
new LayoutOption ("play-enqueued", Catalog.GetString ("Automatically start playing any tracks enqueued on the command line")),
new LayoutOption ("play", Catalog.GetString ("Start playback")),
new LayoutOption ("pause", Catalog.GetString ("Pause playback")),
new LayoutOption ("toggle-playing", Catalog.GetString ("Toggle playback")),
new LayoutOption ("stop", Catalog.GetString ("Completely stop playback")),
new LayoutOption ("stop-when-finished", Catalog.GetString (
"Enable or disable playback stopping after the currently playing track (value should be either 'true' or 'false')")),
new LayoutOption ("set-volume=LEVEL", Catalog.GetString ("Set the playback volume (0-100), prefix with +/- for relative values")),
new LayoutOption ("set-position=POS", Catalog.GetString ("Seek to a specific point (seconds, float)")),
new LayoutOption ("set-rating=RATING", Catalog.GetString ("Set the currently played track's rating (0 to 5)"))
),
new LayoutGroup ("query-player", Catalog.GetString ("Player Engine Query Options"),
new LayoutOption ("query-current-state", Catalog.GetString ("Current player state")),
new LayoutOption ("query-last-state", Catalog.GetString ("Last player state")),
new LayoutOption ("query-can-pause", Catalog.GetString ("Query whether the player can be paused")),
new LayoutOption ("query-can-seek", Catalog.GetString ("Query whether the player can seek")),
new LayoutOption ("query-volume", Catalog.GetString ("Player volume")),
new LayoutOption ("query-position", Catalog.GetString ("Player position in currently playing track"))
),
new LayoutGroup ("query-track", Catalog.GetString ("Playing Track Metadata Query Options"),
new LayoutOption ("query-uri", Catalog.GetString ("URI")),
new LayoutOption ("query-artist", Catalog.GetString ("Artist Name")),
new LayoutOption ("query-album", Catalog.GetString ("Album Title")),
new LayoutOption ("query-title", Catalog.GetString ("Track Title")),
new LayoutOption ("query-duration", Catalog.GetString ("Duration")),
new LayoutOption ("query-track-number", Catalog.GetString ("Track Number")),
new LayoutOption ("query-track-count", Catalog.GetString ("Track Count")),
new LayoutOption ("query-disc", Catalog.GetString ("Disc Number")),
new LayoutOption ("query-year", Catalog.GetString ("Year")),
new LayoutOption ("query-rating", Catalog.GetString ("Rating")),
new LayoutOption ("query-score", Catalog.GetString ("Score")),
new LayoutOption ("query-bit-rate", Catalog.GetString ("Bit Rate"))
),
new LayoutGroup ("ui", Catalog.GetString ("User Interface Options"),
new LayoutOption ("show|--present", Catalog.GetString ("Present the user interface on the active workspace")),
new LayoutOption ("fullscreen", Catalog.GetString ("Enter the full-screen mode")),
new LayoutOption ("hide", Catalog.GetString ("Hide the user interface")),
new LayoutOption ("no-present", Catalog.GetString ("Do not present the user interface, regardless of any other options")),
new LayoutOption ("show-import-media", Catalog.GetString ("Present the import media dialog box")),
new LayoutOption ("show-about", Catalog.GetString ("Present the about dialog")),
new LayoutOption ("show-open-location", Catalog.GetString ("Present the open location dialog")),
new LayoutOption ("show-preferences", Catalog.GetString ("Present the preferences dialog"))
),
new LayoutGroup ("debugging", Catalog.GetString ("Debugging and Development Options"),
new LayoutOption ("debug", Catalog.GetString ("Enable general debugging features")),
new LayoutOption ("debug-sql", Catalog.GetString ("Enable debugging output of SQL queries")),
new LayoutOption ("debug-addins", Catalog.GetString ("Enable debugging output of Mono.Addins")),
new LayoutOption ("db=FILE", Catalog.GetString ("Specify an alternate database to use")),
new LayoutOption ("gconf-base-key=KEY", Catalog.GetString ("Specify an alternate key, default is /apps/banshee-1/")),
new LayoutOption ("uninstalled", Catalog.GetString ("Optimize instance for running uninstalled; " +
"most notably, this will create an alternate Mono.Addins database in the working directory")),
new LayoutOption ("disable-dbus", Catalog.GetString ("Disable DBus support completely")),
new LayoutOption ("no-gtkrc", String.Format (Catalog.GetString (
"Skip loading a custom gtkrc file ({0}) if it exists"),
Path.Combine (Paths.ApplicationData, "gtkrc").Replace (
Environment.GetFolderPath (Environment.SpecialFolder.Personal), "~")))
)
);
if (ApplicationContext.CommandLine.Contains ("help-all")) {
Console.WriteLine (commands);
return;
}
List<string> errors = null;
foreach (KeyValuePair<string, string> argument in ApplicationContext.CommandLine.Arguments) {
switch (argument.Key) {
case "help": Console.WriteLine (commands.ToString ("help")); break;
case "help-debug": Console.WriteLine (commands.ToString ("debugging")); break;
case "help-query-track": Console.WriteLine (commands.ToString ("query-track")); break;
case "help-query-player": Console.WriteLine (commands.ToString ("query-player")); break;
case "help-ui": Console.WriteLine (commands.ToString ("ui")); break;
case "help-playback": Console.WriteLine (commands.ToString ("playback")); break;
default:
if (argument.Key.StartsWith ("help")) {
(errors ?? (errors = new List<string> ())).Add (argument.Key);
}
break;
}
}
if (errors != null) {
Console.WriteLine (commands.LayoutLine (String.Format (Catalog.GetString (
"The following help arguments are invalid: {0}"),
Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", "))));
}
}
private static void ShowVersion ()
{
Console.WriteLine ("Banshee {0} ({1}) http://banshee.fm", Application.DisplayVersion, Application.Version);
Console.WriteLine ("Copyright 2005-{0} Novell, Inc. and Contributors.", DateTime.Now.Year);
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.HDInsight.Job;
using Microsoft.Azure.Management.HDInsight.Job.Models;
namespace Microsoft.Azure.Management.HDInsight.Job
{
/// <summary>
/// The HDInsight job client manages jobs against HDInsight clusters.
/// </summary>
public static partial class JobOperationsExtensions
{
/// <summary>
/// Gets job details from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static JobGetResponse GetJob(this IJobOperations operations, string jobId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).GetJobAsync(jobId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets job details from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static Task<JobGetResponse> GetJobAsync(this IJobOperations operations, string jobId)
{
return operations.GetJobAsync(jobId, CancellationToken.None);
}
/// <summary>
/// Initiates cancel on given running job in the specified HDInsight
/// cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static JobGetResponse KillJob(this IJobOperations operations, string jobId)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).KillJobAsync(jobId);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Initiates cancel on given running job in the specified HDInsight
/// cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Required. The id of the job.
/// </param>
/// <returns>
/// The Get Job operation response.
/// </returns>
public static Task<JobGetResponse> KillJobAsync(this IJobOperations operations, string jobId)
{
return operations.KillJobAsync(jobId, CancellationToken.None);
}
/// <summary>
/// Gets the list of jobs from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static JobListResponse ListJobs(this IJobOperations operations)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ListJobsAsync();
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the list of jobs from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static Task<JobListResponse> ListJobsAsync(this IJobOperations operations)
{
return operations.ListJobsAsync(CancellationToken.None);
}
/// <summary>
/// Gets numOfJobs after jobId from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Optional. jobId from where to list jobs.
/// </param>
/// <param name='numOfJobs'>
/// Required. Number of jobs to fetch. Use -1 to get all.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static JobListResponse ListJobsAfterJobId(this IJobOperations operations, string jobId, int numOfJobs)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).ListJobsAfterJobIdAsync(jobId, numOfJobs);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets numOfJobs after jobId from the specified HDInsight cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='jobId'>
/// Optional. jobId from where to list jobs.
/// </param>
/// <param name='numOfJobs'>
/// Required. Number of jobs to fetch. Use -1 to get all.
/// </param>
/// <returns>
/// The List Job operation response.
/// </returns>
public static Task<JobListResponse> ListJobsAfterJobIdAsync(this IJobOperations operations, string jobId, int numOfJobs)
{
return operations.ListJobsAfterJobIdAsync(jobId, numOfJobs, CancellationToken.None);
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Hive job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static JobSubmissionResponse SubmitHiveJob(this IJobOperations operations, JobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitHiveJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Hive job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static Task<JobSubmissionResponse> SubmitHiveJobAsync(this IJobOperations operations, JobSubmissionParameters parameters)
{
return operations.SubmitHiveJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits a MapReduce job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static JobSubmissionResponse SubmitMapReduceJob(this IJobOperations operations, JobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitMapReduceJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits a MapReduce job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static Task<JobSubmissionResponse> SubmitMapReduceJobAsync(this IJobOperations operations, JobSubmissionParameters parameters)
{
return operations.SubmitMapReduceJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits a MapReduce streaming job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static JobSubmissionResponse SubmitMapReduceStreamingJob(this IJobOperations operations, JobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitMapReduceStreamingJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits a MapReduce streaming job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. MapReduce job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static Task<JobSubmissionResponse> SubmitMapReduceStreamingJobAsync(this IJobOperations operations, JobSubmissionParameters parameters)
{
return operations.SubmitMapReduceStreamingJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Pig job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static JobSubmissionResponse SubmitPigJob(this IJobOperations operations, JobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitPigJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Hive job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Pig job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static Task<JobSubmissionResponse> SubmitPigJobAsync(this IJobOperations operations, JobSubmissionParameters parameters)
{
return operations.SubmitPigJobAsync(parameters, CancellationToken.None);
}
/// <summary>
/// Submits an Sqoop job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Sqoop job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static JobSubmissionResponse SubmitSqoopJob(this IJobOperations operations, JobSubmissionParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IJobOperations)s).SubmitSqoopJobAsync(parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Submits an Sqoop job to an HDINSIGHT cluster.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.HDInsight.Job.IJobOperations.
/// </param>
/// <param name='parameters'>
/// Required. Sqoop job parameters.
/// </param>
/// <returns>
/// The Create Job operation response.
/// </returns>
internal static Task<JobSubmissionResponse> SubmitSqoopJobAsync(this IJobOperations operations, JobSubmissionParameters parameters)
{
return operations.SubmitSqoopJobAsync(parameters, CancellationToken.None);
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001
//
// File: BindUriHelper.cs
//
// Description: BindUriHelper class. Allows bindToObject, bindToStream
//
// History: 04-13-01 - marka - created
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using MS.Win32;
using System.Security.Permissions;
#if PRESENTATIONFRAMEWORK
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Media;
using MS.Internal.PresentationFramework;
using MS.Internal.AppModel;
using System.Windows.Controls;
using MS.Internal ;
using System.Security;
using System.IO.Packaging;
using System.Reflection;
using MS.Internal.Utility;
using System.Net;
// In order to avoid generating warnings about unknown message numbers and
// unknown pragmas when compiling your C# source code with the actual C# compiler,
// you need to disable warnings 1634 and 1691. (Presharp Documentation)
#pragma warning disable 1634, 1691
namespace MS.Internal.Utility
{
// A BindUriHelper class
// See also WpfWebRequestHelper.
internal static partial class BindUriHelper
{
private const string PLACEBOURI = "http://microsoft.com/";
static private Uri placeboBase = new Uri(PLACEBOURI);
private const string FRAGMENTMARKER = "#";
static internal Uri GetResolvedUri(Uri originalUri)
{
return GetResolvedUri(null, originalUri);
}
/// <summary>
///
/// </summary>
/// <remarks>
/// Relative Uri resolution logic
///
/// if baseUriString != ""
/// {
/// if (baseUriString is absolute uri)
/// {
/// determine uriToNavigate as baseUriString + inputUri
/// }
/// else
/// {
/// determine uri to navigate wrt application's base uri + baseUriString + inputUri
/// }
/// }
/// else
/// {
/// Get the element's NavigationService
/// if(NavigationService.CurrentSource is absolute uri)
/// {
/// determine uriToNavigate as NavigationService.CurrentSource + inputUri
/// }
/// else // this will be more common
/// {
/// determine uriToNavigate wrt application's base uri (pack://application,,,/) + NavigationService.CurrentSource + inputUri
/// }
///
///
/// If no ns in tree, resolve against the application's base
/// }
/// </remarks>
/// <param name="element"></param>
/// <param name="baseUri"></param>
/// <param name="inputUri"></param>
/// <returns></returns>
static internal Uri GetUriToNavigate(DependencyObject element, Uri baseUri, Uri inputUri)
{
Uri uriToNavigate = inputUri;
if ((inputUri == null) || (inputUri.IsAbsoluteUri == true))
{
return uriToNavigate;
}
// BaseUri doesn't contain the last part of the path: filename,
// so when the inputUri is fragment we cannot resolve with BaseUri, instead
// we should resolve with the element's NavigationService's CurrentSource.
if (StartWithFragment(inputUri))
{
baseUri = null;
}
if (baseUri != null)
{
if (baseUri.IsAbsoluteUri == false)
{
uriToNavigate = GetResolvedUri(BindUriHelper.GetResolvedUri(null, baseUri), inputUri);
}
else
{
uriToNavigate = GetResolvedUri(baseUri, inputUri);
}
}
else // we're in here when baseUri is not set i.e. it's null
{
Uri currentSource = null;
// if the it is an INavigator (Frame, NavWin), we should use its CurrentSource property.
// Otherwise we need to get NavigationService of the container that this element is hosted in,
// and use its CurrentSource.
if (element != null)
{
INavigator navigator = element as INavigator;
if (navigator != null)
{
currentSource = navigator.CurrentSource;
}
else
{
NavigationService ns = null;
ns = element.GetValue(NavigationService.NavigationServiceProperty) as NavigationService;
currentSource = (ns == null) ? null : ns.CurrentSource;
}
}
if (currentSource != null)
{
if (currentSource.IsAbsoluteUri)
{
uriToNavigate = GetResolvedUri(currentSource, inputUri);
}
else
{
uriToNavigate = GetResolvedUri(GetResolvedUri(null, currentSource), inputUri);
}
}
else
{
//
// For now we resolve to Application's base
uriToNavigate = BindUriHelper.GetResolvedUri(null, inputUri);
}
}
return uriToNavigate;
}
static internal bool StartWithFragment(Uri uri)
{
return uri.OriginalString.StartsWith(FRAGMENTMARKER, StringComparison.Ordinal);
}
// Return Fragment string for a given uri without the leading #
static internal string GetFragment(Uri uri)
{
Uri workuri = uri;
string fragment = String.Empty;
string frag;
if (uri.IsAbsoluteUri == false)
{
// this is a relative uri, and Fragement() doesn't work with relative uris. The base uri is completley irrelevant
// here and will never affect the returned fragment, but the method requires something to be there. Therefore,
// we will use "http://microsoft.com" as a convenient substitute.
workuri = new Uri(placeboBase, uri);
}
frag = workuri.Fragment;
if (frag != null && frag.Length > 0)
{
// take off the pound
fragment = frag.Substring(1);
}
return fragment;
}
// In NavigationService we do not want to show users pack://application,,,/ with the
// Source property or any event arguments.
static internal Uri GetUriRelativeToPackAppBase(Uri original)
{
if (original == null)
{
return null;
}
Uri resolved = GetResolvedUri(original);
Uri packUri = BaseUriHelper.PackAppBaseUri;
Uri relative = packUri.MakeRelativeUri(resolved);
return relative;
}
static internal bool IsXamlMimeType(ContentType mimeType)
{
if (MimeTypeMapper.XamlMime.AreTypeAndSubTypeEqual(mimeType)
|| MimeTypeMapper.FixedDocumentSequenceMime.AreTypeAndSubTypeEqual(mimeType)
|| MimeTypeMapper.FixedDocumentMime.AreTypeAndSubTypeEqual(mimeType)
|| MimeTypeMapper.FixedPageMime.AreTypeAndSubTypeEqual(mimeType))
{
return true;
}
return false;
}
}
}
#endif
| |
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Core.TfsInterop;
using StructureMap;
namespace GitTfs.Commands
{
[Pluggable("branch")]
[Description("branch\n\n" +
" * Display inited remote TFS branches:\n git tfs branch\n\n" +
" * Display remote TFS branches:\n git tfs branch -r\n git tfs branch -r -all\n\n" +
" * Create a TFS branch from current commit:\n git tfs branch $/Repository/ProjectBranchToCreate <myWishedRemoteName> --comment=\"Creation of my branch\"\n\n" +
" * Rename a remote branch:\n git tfs branch --move oldTfsRemoteName newTfsRemoteName\n\n" +
" * Delete a remote branch:\n git tfs branch --delete tfsRemoteName\n git tfs branch --delete --all\n\n" +
" * Initialise an existing remote TFS branch:\n git tfs branch --init $/Repository/ProjectBranch\n git tfs branch --init $/Repository/ProjectBranch myNewBranch\n git tfs branch --init --all\n git tfs branch --init --tfs-parent-branch=$/Repository/ProjectParentBranch $/Repository/ProjectBranch\n")]
[RequiresValidGitRepository]
public class Branch : GitTfsCommand
{
private readonly Globals _globals;
private readonly Help _helper;
private readonly Cleanup _cleanup;
private readonly InitBranch _initBranch;
private readonly Rcheckin _rcheckin;
public bool DisplayRemotes { get; set; }
public bool ManageAll { get; set; }
public bool ShouldRenameRemote { get; set; }
public bool ShouldDeleteRemote { get; set; }
public bool ShouldInitBranch { get; set; }
public string IgnoreRegex { get; set; }
public string ExceptRegex { get; set; }
public bool NoFetch { get; set; }
public string Comment { get; set; }
public string TfsUsername { get; set; }
public string TfsPassword { get; set; }
public string ParentBranch { get; set; }
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "r|remotes", "Display the TFS branches of the current TFS root branch existing on the TFS server", v => DisplayRemotes = (v != null) },
{ "all", "Display (used with option --remotes) the TFS branches of all the root branches existing on the TFS server\n" +
" or Initialize (used with option --init) all existing TFS branches (For TFS 2010 and later)\n" +
" or Delete (used with option --delete) all tfs remotes (for example after lfs migration).", v => ManageAll = (v != null) },
{ "comment=", "Comment used for the creation of the TFS branch ", v => Comment = v },
{ "m|move", "Rename a TFS remote", v => ShouldRenameRemote = (v != null) },
{ "delete", "Delete a TFS remote", v => ShouldDeleteRemote = (v != null) },
{ "init", "Initialize an existing TFS branch", v => ShouldInitBranch = (v != null) },
{ "ignore-regex=", "A regex of files to ignore", v => IgnoreRegex = v },
{ "except-regex=", "A regex of exceptions to ignore-regex", v => ExceptRegex = v},
{ "no-fetch", "Don't fetch changeset for newly initialized branch(es)", v => NoFetch = (v != null) },
{ "b|tfs-parent-branch=", "TFS Parent branch of the TFS branch to clone (TFS 2008 only! And required!!) ex: $/Repository/ProjectParentBranch", v => ParentBranch = v },
{ "u|username=", "TFS username", v => TfsUsername = v },
{ "p|password=", "TFS password", v => TfsPassword = v },
}
.Merge(_globals.OptionSet);
}
}
public Branch(Globals globals, Help helper, Cleanup cleanup, InitBranch initBranch, Rcheckin rcheckin)
{
_globals = globals;
_helper = helper;
_cleanup = cleanup;
_initBranch = initBranch;
_rcheckin = rcheckin;
}
public void SetInitBranchParameters()
{
_initBranch.TfsUsername = TfsUsername;
_initBranch.TfsPassword = TfsPassword;
_initBranch.CloneAllBranches = ManageAll;
_initBranch.ParentBranch = ParentBranch;
_initBranch.IgnoreRegex = IgnoreRegex;
_initBranch.ExceptRegex = ExceptRegex;
_initBranch.NoFetch = NoFetch;
}
public bool IsCommandWellUsed()
{
//Verify that some mutual exclusive options are not used together
return new[] { ShouldDeleteRemote, ShouldInitBranch, ShouldRenameRemote }.Count(b => b) <= 1;
}
public int Run()
{
if (!IsCommandWellUsed())
return _helper.Run(this);
_globals.WarnOnGitVersion();
VerifyCloneAllRepository();
if (ShouldRenameRemote)
return _helper.Run(this);
if(ShouldDeleteRemote)
{
if (!ManageAll)
return _helper.Run(this);
else
return DeleteAllRemotes();
}
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run();
}
return DisplayBranchData();
}
public int Run(string param)
{
if (!IsCommandWellUsed())
return _helper.Run(this);
VerifyCloneAllRepository();
_globals.WarnOnGitVersion();
if (ShouldRenameRemote)
return _helper.Run(this);
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run(param);
}
if (ShouldDeleteRemote)
return DeleteRemote(param);
return CreateRemote(param);
}
public int Run(string param1, string param2)
{
if (!IsCommandWellUsed())
return _helper.Run(this);
VerifyCloneAllRepository();
_globals.WarnOnGitVersion();
if (ShouldDeleteRemote)
return _helper.Run(this);
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run(param1, param2);
}
if (ShouldRenameRemote)
return RenameRemote(param1, param2);
return CreateRemote(param1, param2);
}
private void VerifyCloneAllRepository()
{
if (!_globals.Repository.HasRemote(GitTfsConstants.DefaultRepositoryId))
return;
if (_globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId).TfsRepositoryPath == GitTfsConstants.TfsRoot)
throw new GitTfsException("error: you can't use the 'branch' command when you have cloned the whole repository '$/' !");
}
private int RenameRemote(string oldRemoteName, string newRemoteName)
{
var newRemoteNameExpected = _globals.Repository.AssertValidBranchName(newRemoteName.ToGitRefName());
if (newRemoteNameExpected != newRemoteName)
Trace.TraceInformation("The name of the branch after renaming will be : " + newRemoteNameExpected);
if (_globals.Repository.HasRemote(newRemoteNameExpected))
{
throw new GitTfsException("error: this remote name is already used!");
}
Trace.TraceInformation("Cleaning before processing rename...");
_cleanup.Run();
_globals.Repository.MoveRemote(oldRemoteName, newRemoteNameExpected);
if (_globals.Repository.RenameBranch(oldRemoteName, newRemoteName) == null)
Trace.TraceWarning("warning: no local branch found to rename");
return GitTfsExitCodes.OK;
}
private int CreateRemote(string tfsPath, string gitBranchNameExpected = null)
{
bool checkInCurrentBranch = false;
tfsPath.AssertValidTfsPath();
Trace.WriteLine("Getting commit informations...");
var commit = _globals.Repository.GetCurrentTfsCommit();
if (commit == null)
{
checkInCurrentBranch = true;
var parents = _globals.Repository.GetLastParentTfsCommits(_globals.Repository.GetCurrentCommit());
if (!parents.Any())
throw new GitTfsException("error : no tfs remote parent found!");
commit = parents.First();
}
var remote = commit.Remote;
Trace.WriteLine("Creating branch in TFS...");
remote.Tfs.CreateBranch(remote.TfsRepositoryPath, tfsPath, commit.ChangesetId, Comment ?? "Creation branch " + tfsPath);
Trace.WriteLine("Init branch in local repository...");
_initBranch.DontCreateGitBranch = true;
var returnCode = _initBranch.Run(tfsPath, gitBranchNameExpected);
if (returnCode != GitTfsExitCodes.OK || !checkInCurrentBranch)
return returnCode;
_rcheckin.RebaseOnto(_initBranch.RemoteCreated.RemoteRef, commit.GitCommit);
_globals.UserSpecifiedRemoteId = _initBranch.RemoteCreated.Id;
return _rcheckin.Run();
}
private int DeleteRemote(string remoteName)
{
var remote = _globals.Repository.ReadTfsRemote(remoteName);
if (remote == null)
{
throw new GitTfsException(string.Format("Error: Remote \"{0}\" not found!", remoteName));
}
Trace.TraceInformation("Cleaning before processing delete...");
_cleanup.Run();
_globals.Repository.DeleteTfsRemote(remote);
return GitTfsExitCodes.OK;
}
private int DeleteAllRemotes()
{
Trace.TraceInformation("Deleting all remotes!!");
Trace.TraceInformation("Cleaning before processing delete...");
_cleanup.Run();
foreach (var remote in _globals.Repository.ReadAllTfsRemotes())
{
_globals.Repository.DeleteTfsRemote(remote);
}
return GitTfsExitCodes.OK;
}
public int DisplayBranchData()
{
// should probably pull this from options so that it is settable from the command-line
const string remoteId = GitTfsConstants.DefaultRepositoryId;
var tfsRemotes = _globals.Repository.ReadAllTfsRemotes();
if (DisplayRemotes)
{
if (!ManageAll)
{
var remote = _globals.Repository.ReadTfsRemote(remoteId);
Trace.TraceInformation("\nTFS branch structure:");
WriteRemoteTfsBranchStructure(remote.Tfs, remote.TfsRepositoryPath, tfsRemotes);
return GitTfsExitCodes.OK;
}
else
{
var remote = tfsRemotes.First(r => r.Id == remoteId);
if (!remote.Tfs.CanGetBranchInformation)
{
throw new GitTfsException("error: this version of TFS doesn't support this functionality");
}
foreach (var branch in remote.Tfs.GetBranches().Where(b => b.IsRoot))
{
var root = remote.Tfs.GetRootTfsBranchForRemotePath(branch.Path);
var visitor = new WriteBranchStructureTreeVisitor(remote.TfsRepositoryPath, tfsRemotes);
root.AcceptVisitor(visitor);
}
return GitTfsExitCodes.OK;
}
}
WriteTfsRemoteDetails(tfsRemotes);
return GitTfsExitCodes.OK;
}
public static void WriteRemoteTfsBranchStructure(ITfsHelper tfsHelper, string tfsRepositoryPath, IEnumerable<IGitTfsRemote> tfsRemotes = null)
{
var root = tfsHelper.GetRootTfsBranchForRemotePath(tfsRepositoryPath);
if (!tfsHelper.CanGetBranchInformation)
{
throw new GitTfsException("error: this version of TFS doesn't support this functionality");
}
var visitor = new WriteBranchStructureTreeVisitor(tfsRepositoryPath, tfsRemotes);
root.AcceptVisitor(visitor);
}
private void WriteTfsRemoteDetails(IEnumerable<IGitTfsRemote> tfsRemotes)
{
Trace.TraceInformation("\nGit-tfs remote details:");
foreach (var remote in tfsRemotes)
{
Trace.TraceInformation("\n {0} -> {1} {2}", remote.Id, remote.TfsUrl, remote.TfsRepositoryPath);
Trace.TraceInformation(" {0} - {1} @ {2}", remote.RemoteRef, remote.MaxCommitHash, remote.MaxChangesetId);
}
}
private class WriteBranchStructureTreeVisitor : IBranchTreeVisitor
{
private readonly string _targetPath;
private readonly IEnumerable<IGitTfsRemote> _tfsRemotes;
public WriteBranchStructureTreeVisitor(string targetPath, IEnumerable<IGitTfsRemote> tfsRemotes = null)
{
_targetPath = targetPath;
_tfsRemotes = tfsRemotes;
}
public void Visit(BranchTree branch, int level)
{
var writer = new StringWriter();
for (var i = 0; i < level; i++)
writer.Write(" | ");
writer.WriteLine();
for (var i = 0; i < level - 1; i++)
writer.Write(" | ");
if (level > 0)
writer.Write(" +-");
writer.Write(" {0}", branch.Path);
if (_tfsRemotes != null)
{
var remote = _tfsRemotes.FirstOrDefault(r => r.TfsRepositoryPath == branch.Path);
if (remote != null)
writer.Write(" -> " + remote.Id);
}
if (branch.Path.Equals(_targetPath))
writer.Write(" [*]");
Trace.TraceInformation(writer.ToString());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ModestTree;
namespace Zenject
{
public static class TypeAnalyzer
{
static Dictionary<Type, ZenjectTypeInfo> _typeInfo = new Dictionary<Type, ZenjectTypeInfo>();
public static ZenjectTypeInfo GetInfo<T>()
{
return GetInfo(typeof(T));
}
public static ZenjectTypeInfo GetInfo(Type type)
{
#if UNITY_EDITOR && ZEN_PROFILING_ENABLED
using(ProfileBlock.Start("Zenject Reflection"))
#endif
{
Assert.That(!type.IsAbstract(),
"Tried to analyze abstract type '{0}'. This is not currently allowed.", type);
ZenjectTypeInfo info;
#if ZEN_MULTITHREADING
lock(_typeInfo)
#endif
{
if (!_typeInfo.TryGetValue(type, out info))
{
info = CreateTypeInfo(type);
_typeInfo.Add(type, info);
}
}
return info;
}
}
static ZenjectTypeInfo CreateTypeInfo(Type type)
{
var constructor = GetInjectConstructor(type);
return new ZenjectTypeInfo(
type,
GetPostInjectMethods(type),
constructor,
GetFieldInjectables(type).ToList(),
GetPropertyInjectables(type).ToList(),
GetConstructorInjectables(type, constructor).ToList());
}
static IEnumerable<InjectableInfo> GetConstructorInjectables(Type parentType, ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
{
return Enumerable.Empty<InjectableInfo>();
}
return constructorInfo.GetParameters().Select(
paramInfo => CreateInjectableInfoForParam(parentType, paramInfo));
}
static InjectableInfo CreateInjectableInfoForParam(
Type parentType, ParameterInfo paramInfo)
{
var injectAttributes = paramInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type parameter '{0}' of type '{1}'. Parameter should only have one", paramInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
bool isOptionalWithADefaultValue = (paramInfo.Attributes & ParameterAttributes.HasDefault) == ParameterAttributes.HasDefault;
return new InjectableInfo(
isOptionalWithADefaultValue || isOptional,
identifier,
paramInfo.Name,
paramInfo.ParameterType,
parentType,
null,
isOptionalWithADefaultValue ? paramInfo.DefaultValue : null,
sourceType);
}
static List<PostInjectableInfo> GetPostInjectMethods(Type type)
{
// Note that unlike with fields and properties we use GetCustomAttributes
// This is so that we can ignore inherited attributes, which is necessary
// otherwise a base class method marked with [Inject] would cause all overridden
// derived methods to be added as well
var methods = type.GetAllInstanceMethods()
.Where(x => x.GetCustomAttributes(typeof(InjectAttribute), false).Any()).ToList();
var heirarchyList = type.Yield().Concat(type.GetParentTypes()).Reverse().ToList();
// Order by base classes first
// This is how constructors work so it makes more sense
var values = methods.OrderBy(x => heirarchyList.IndexOf(x.DeclaringType));
var postInjectInfos = new List<PostInjectableInfo>();
foreach (var methodInfo in values)
{
var paramsInfo = methodInfo.GetParameters();
var injectAttr = methodInfo.AllAttributes<InjectAttribute>().Single();
Assert.That(!injectAttr.Optional && injectAttr.Id == null && injectAttr.Source == InjectSources.Any,
"Parameters of InjectAttribute do not apply to constructors and methods");
postInjectInfos.Add(
new PostInjectableInfo(
methodInfo,
paramsInfo.Select(paramInfo =>
CreateInjectableInfoForParam(type, paramInfo)).ToList()));
}
return postInjectInfos;
}
static IEnumerable<InjectableInfo> GetPropertyInjectables(Type type)
{
var propInfos = type.GetAllInstanceProperties()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var propInfo in propInfos)
{
yield return CreateForMember(propInfo, type);
}
}
static IEnumerable<InjectableInfo> GetFieldInjectables(Type type)
{
var fieldInfos = type.GetAllInstanceFields()
.Where(x => x.HasAttribute(typeof(InjectAttributeBase)));
foreach (var fieldInfo in fieldInfos)
{
yield return CreateForMember(fieldInfo, type);
}
}
#if !(UNITY_WSA && ENABLE_DOTNET) || UNITY_EDITOR
private static IEnumerable<FieldInfo> GetAllFields(Type t, BindingFlags flags)
{
if (t == null)
{
return Enumerable.Empty<FieldInfo>();
}
return t.GetFields(flags).Concat(GetAllFields(t.BaseType, flags)).Distinct();
}
private static Action<object, object> GetOnlyPropertySetter(
Type parentType,
string propertyName)
{
Assert.That(parentType != null);
Assert.That(!string.IsNullOrEmpty(propertyName));
var allFields = GetAllFields(
parentType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).ToList();
var writeableFields = allFields.Where(f => f.Name == string.Format("<{0}>k__BackingField", propertyName)).ToList();
if (!writeableFields.Any())
{
throw new ZenjectException(string.Format(
"Can't find backing field for get only property {0} on {1}.\r\n{2}",
propertyName, parentType.FullName, string.Join(";", allFields.Select(f => f.Name).ToArray())));
}
return (injectable, value) => writeableFields.ForEach(f => f.SetValue(injectable, value));
}
#endif
static InjectableInfo CreateForMember(MemberInfo memInfo, Type parentType)
{
var injectAttributes = memInfo.AllAttributes<InjectAttributeBase>().ToList();
Assert.That(injectAttributes.Count <= 1,
"Found multiple 'Inject' attributes on type field '{0}' of type '{1}'. Field should only container one Inject attribute", memInfo.Name, parentType);
var injectAttr = injectAttributes.SingleOrDefault();
object identifier = null;
bool isOptional = false;
InjectSources sourceType = InjectSources.Any;
if (injectAttr != null)
{
identifier = injectAttr.Id;
isOptional = injectAttr.Optional;
sourceType = injectAttr.Source;
}
Type memberType;
Action<object, object> setter;
if (memInfo is FieldInfo)
{
var fieldInfo = (FieldInfo)memInfo;
setter = ((object injectable, object value) => fieldInfo.SetValue(injectable, value));
memberType = fieldInfo.FieldType;
}
else
{
Assert.That(memInfo is PropertyInfo);
var propInfo = (PropertyInfo)memInfo;
memberType = propInfo.PropertyType;
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
#else
if (propInfo.CanWrite)
{
setter = ((object injectable, object value) => propInfo.SetValue(injectable, value, null));
}
else
{
setter = GetOnlyPropertySetter(parentType, propInfo.Name);
}
#endif
}
return new InjectableInfo(
isOptional,
identifier,
memInfo.Name,
memberType,
parentType,
setter,
null,
sourceType);
}
static ConstructorInfo GetInjectConstructor(Type parentType)
{
var constructors = parentType.Constructors();
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
// WP8 generates a dummy constructor with signature (internal Classname(UIntPtr dummy))
// So just ignore that
constructors = constructors.Where(c => !IsWp8GeneratedConstructor(c)).ToArray();
#endif
if (constructors.IsEmpty())
{
return null;
}
if (constructors.HasMoreThan(1))
{
var explicitConstructor = (from c in constructors where c.HasAttribute<InjectAttribute>() select c).SingleOrDefault();
if (explicitConstructor != null)
{
return explicitConstructor;
}
// If there is only one public constructor then use that
// This makes decent sense but is also necessary on WSA sometimes since the WSA generated
// constructor can sometimes be private with zero parameters
var singlePublicConstructor = constructors.Where(x => !x.IsPrivate).OnlyOrDefault();
if (singlePublicConstructor != null)
{
return singlePublicConstructor;
}
return null;
}
return constructors[0];
}
#if UNITY_WSA && ENABLE_DOTNET && !UNITY_EDITOR
static bool IsWp8GeneratedConstructor(ConstructorInfo c)
{
ParameterInfo[] args = c.GetParameters();
if (args.Length == 1)
{
return args[0].ParameterType == typeof(UIntPtr) &&
(string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy");
}
if (args.Length == 2)
{
return args[0].ParameterType == typeof(UIntPtr) &&
args[1].ParameterType == typeof(Int64 * ) &&
(string.IsNullOrEmpty(args[0].Name) || args[0].Name == "dummy") &&
(string.IsNullOrEmpty(args[1].Name) || args[1].Name == "dummy");
}
return false;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using NUnit.Framework;
using Quartz.Impl.Calendar;
using Quartz.Tests.Unit.Utils;
using Quartz.Util;
namespace Quartz.Tests.Unit
{
[TestFixture]
public class SerializationTest
{
[Test]
public void TestAnnualCalendarDeserialization()
{
Deserialize<AnnualCalendar>();
}
[Test]
public void TestAnnualCalendarSerialization()
{
AnnualCalendar annualCalendar = new AnnualCalendar();
DateTime day = new DateTime(2011, 12, 20, 0, 0, 0);
annualCalendar.SetDayExcluded(day, true);
AnnualCalendar clone = annualCalendar.DeepClone();
Assert.IsTrue(clone.IsDayExcluded(day));
}
[Test]
public void TestBaseCalendarDeserialization()
{
Deserialize<BaseCalendar>();
}
[Test]
public void TestBaseCalendarSerialization()
{
BaseCalendar baseCalendar = new BaseCalendar();
TimeZoneInfo timeZone = TimeZoneInfo.GetSystemTimeZones()[3];
baseCalendar.TimeZone = timeZone;
BaseCalendar clone = baseCalendar.DeepClone();
Assert.AreEqual(timeZone.Id, clone.TimeZone.Id);
}
[Test]
public void TestCronCalendarDeserialization()
{
Deserialize<CronCalendar>();
}
[Test]
public void TestCronCalendarSerialization()
{
CronCalendar cronCalendar = new CronCalendar("* * 8-17 ? * *");
CronCalendar clone = cronCalendar.DeepClone();
Assert.AreEqual("* * 8-17 ? * *", clone.CronExpression.CronExpressionString);
}
[Test]
public void TestDailyCalendarDeserialization()
{
Deserialize<DailyCalendar>();
}
[Test]
public void TestDailyCalendarSerialization()
{
DailyCalendar dailyCalendar = new DailyCalendar("12:13:14:150", "13:14");
DailyCalendar clone = dailyCalendar.DeepClone();
DateTimeOffset timeRangeStartTimeUtc = clone.GetTimeRangeStartingTimeUtc(DateTimeOffset.UtcNow);
Assert.AreEqual(12, timeRangeStartTimeUtc.Hour);
Assert.AreEqual(13, timeRangeStartTimeUtc.Minute);
Assert.AreEqual(14, timeRangeStartTimeUtc.Second);
Assert.AreEqual(150, timeRangeStartTimeUtc.Millisecond);
DateTimeOffset timeRangeEndingTimeUtc = clone.GetTimeRangeEndingTimeUtc(DateTimeOffset.UtcNow);
Assert.AreEqual(13, timeRangeEndingTimeUtc.Hour);
Assert.AreEqual(14, timeRangeEndingTimeUtc.Minute);
Assert.AreEqual(0, timeRangeEndingTimeUtc.Second);
Assert.AreEqual(0, timeRangeEndingTimeUtc.Millisecond);
}
[Test]
[Ignore("requires binary serilization to be done with 2.4, 2.3 in test is non-compliant")]
public void TestHolidayCalendarDeserialization()
{
var calendar = Deserialize<HolidayCalendar>();
Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));
calendar = Deserialize<HolidayCalendar>(23);
Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));
BinaryFormatter formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
calendar = new HolidayCalendar();
calendar.AddExcludedDate(DateTime.Now.Date);
formatter.Serialize(stream, calendar);
stream.Seek(0, SeekOrigin.Begin);
stream.Position = 0;
calendar = (HolidayCalendar) formatter.Deserialize(stream);
Assert.That(calendar.ExcludedDates.Count, Is.EqualTo(1));
}
}
[Test]
public void TestHolidayCalendarSerialization()
{
HolidayCalendar holidayCalendar = new HolidayCalendar();
holidayCalendar.AddExcludedDate(new DateTime(2010, 1, 20));
HolidayCalendar clone = holidayCalendar.DeepClone();
Assert.AreEqual(1, clone.ExcludedDates.Count);
}
[Test]
public void TestMonthlyCalendarDeserialization()
{
Deserialize<MonthlyCalendar>();
}
[Test]
public void TestMonthlyCalendarSerialization()
{
MonthlyCalendar monthlyCalendar = new MonthlyCalendar();
monthlyCalendar.SetDayExcluded(20, true);
MonthlyCalendar clone = monthlyCalendar.DeepClone();
Assert.IsTrue(clone.IsDayExcluded(20));
}
[Test]
public void TestWeeklyCalendarDeserialization()
{
Deserialize<WeeklyCalendar>();
}
[Test]
public void TestWeeklyCalendarSerialization()
{
WeeklyCalendar weeklyCalendar = new WeeklyCalendar();
weeklyCalendar.SetDayExcluded(DayOfWeek.Monday, true);
WeeklyCalendar clone = weeklyCalendar.DeepClone();
Assert.IsTrue(clone.IsDayExcluded(DayOfWeek.Monday));
}
/* TODO
[Test]
public void TestTreeSetDeserialization()
{
Deserialize<TreeSet>();
}
[Test]
public void TestTreeSetSerialization()
{
new TreeSet<string>().DeepClone();
}
*/
[Test]
public void TestHashSetSerialization()
{
new HashSet<string>().DeepClone();
}
[Test]
public void TestJobDataMapDeserialization()
{
JobDataMap map = Deserialize<JobDataMap>();
Assert.AreEqual("bar", map["foo"]);
Assert.AreEqual(123, map["num"]);
}
[Test]
public void TestJobDataMapSerialization()
{
JobDataMap map = new JobDataMap();
map["foo"] = "bar";
map["num"] = 123;
JobDataMap clone = map.DeepClone();
Assert.AreEqual("bar", clone["foo"]);
Assert.AreEqual(123, clone["num"]);
}
[Test]
public void TestStringKeyDirtyFlagMapSerialization()
{
StringKeyDirtyFlagMap map = new StringKeyDirtyFlagMap();
map["foo"] = "bar";
map["num"] = 123;
StringKeyDirtyFlagMap clone = map.DeepClone();
Assert.AreEqual("bar", clone["foo"]);
Assert.AreEqual(123, clone["num"]);
}
[Test]
public void TestSchedulerContextSerialization()
{
SchedulerContext map = new SchedulerContext();
map["foo"] = "bar";
map["num"] = 123;
SchedulerContext clone = map.DeepClone();
Assert.AreEqual("bar", clone["foo"]);
Assert.AreEqual(123, clone["num"]);
}
private static T Deserialize<T>() where T : class
{
return Deserialize<T>(10);
}
private static T Deserialize<T>(int version) where T : class
{
BinaryFormatter formatter = new BinaryFormatter();
using (var stream = File.OpenRead(Path.Combine("Serialized", typeof(T).Name + "_" + version + ".ser")))
{
return (T) formatter.Deserialize(stream);
}
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing perworlds and
/// limitations under the License.
using UnityEngine;
using System;
namespace Soomla.Levelup
{
/// <summary>
/// A utility class for persisting and querying <c>World</c>s.
/// Use this class to get or set the completion of <c>World</c>s and assign rewards.
/// </summary>
public class WorldStorage
{
protected const string TAG = "SOOMLA WorldStorage";
/// <summary>
/// Holds an instance of <c>WorldStorage</c> or <c>WorldStorageAndroid</c> or <c>WorldStorageIOS</c>.
/// </summary>
static WorldStorage _instance = null;
/// <summary>
/// Determines which <c>Worldtorage</c> to use according to the platform in use
/// and if the Unity Editor is being used.
/// </summary>
/// <value>The instance to use.</value>
static WorldStorage instance {
get {
if(_instance == null) {
#if UNITY_ANDROID && !UNITY_EDITOR
_instance = new WorldStorageAndroid();
#elif UNITY_IOS && !UNITY_EDITOR
_instance = new WorldStorageIOS();
#else
_instance = new WorldStorage();
#endif
}
return _instance;
}
}
public static void InitLevelUp()
{
instance._initLevelUp();
}
/** The following functions call the relevant instance-specific functions. **/
/** WORLD COMPLETION **/
public static void SetCompleted(World world, bool completed) {
SetCompleted(world, completed, true);
}
public static void SetCompleted(World world, bool completed, bool notify) {
instance._setCompleted(world, completed, notify);
}
public static bool IsCompleted(World world) {
return instance._isCompleted(world);
}
/** WORLD REWARDS **/
public static void SetReward(World world, string rewardId) {
instance._setReward(world, rewardId);
}
public static string GetAssignedReward(World world) {
return instance._getAssignedReward(world);
}
/** LAST COMPLETED INNER WORLD **/
public static void SetLastCompletedInnerWorld(World world, string innerWorldId)
{
instance._setLastCompletedInnerWorld(world, innerWorldId);
}
public static string GetLastCompletedInnerWorld(World world)
{
return instance._getLastCompletedInnerWorld(world);
}
/** Unity-Editor Functions **/
/// <summary>
/// Initializes <c>SoomlaLevelUp</c>
/// </summary>
protected virtual void _initLevelUp()
{
#if UNITY_EDITOR
LevelUpEvents.OnLevelUpInitialized();
#endif
}
/// <summary>
/// Sets the given <c>World</c> as completed if <c>completed</c> is <c>true</c>.
/// </summary>
/// <param name="world"><c>World</c> to set as completed.</param>
/// <param name="completed">If set to <c>true</c> the <c>World</c> will be set
/// as completed.</param>
/// <param name="notify">If set to <c>true</c> trigger events.</param>
protected virtual void _setCompleted(World world, bool completed, bool notify) {
#if UNITY_EDITOR
string key = keyWorldCompleted(world.ID);
if (completed) {
PlayerPrefs.SetString(key, "yes");
if (notify) {
LevelUpEvents.OnWorldCompleted(world);
}
} else {
PlayerPrefs.DeleteKey(key);
}
#endif
}
/// <summary>
/// Determines if the given <c>World</c> is completed.
/// </summary>
/// <returns>If the given <c>World</c> is completed returns <c>true</c>;
/// otherwise <c>false</c>.</returns>
/// <param name="world"><c>World</c> to determine if completed.</param>
protected virtual bool _isCompleted(World world) {
#if UNITY_EDITOR
string key = keyWorldCompleted(world.ID);
string val = PlayerPrefs.GetString (key);
return !string.IsNullOrEmpty(val);
#else
return false;
#endif
}
/// <summary>
/// Assigns the reward with the given reward ID to the given <c>World</c>.
/// </summary>
/// <param name="world"><c>World</c> to assign a reward to.</param>
/// <param name="rewardId">ID of reward to assign.</param>
protected virtual void _setReward(World world, string rewardId) {
#if UNITY_EDITOR
string key = keyReward (world.ID);
if (!string.IsNullOrEmpty(rewardId)) {
PlayerPrefs.SetString(key, rewardId);
} else {
PlayerPrefs.DeleteKey(key);
}
// Notify world was assigned a reward
LevelUpEvents.OnWorldAssignedReward(world);
#endif
}
/// <summary>
/// Retrieves the given <c>World</c>'s assigned reward.
/// </summary>
/// <returns>The assigned reward to retrieve.</returns>
/// <param name="world"><c>World</c> whose reward is to be retrieved.</param>
protected virtual string _getAssignedReward(World world) {
#if UNITY_EDITOR
string key = keyReward (world.ID);
return PlayerPrefs.GetString (key);
#else
return null;
#endif
}
protected virtual void _setLastCompletedInnerWorld(World world, string innerWorldId)
{
#if UNITY_EDITOR
string key = keyLastCompletedInnerWorld(world.ID);
if (!string.IsNullOrEmpty(innerWorldId)) {
PlayerPrefs.SetString(key, innerWorldId);
} else {
PlayerPrefs.DeleteKey(key);
}
// Notify world had inner level complete
LevelUpEvents.OnLastCompletedInnerWorldChanged(world, innerWorldId);
#endif
}
protected virtual string _getLastCompletedInnerWorld(World world)
{
#if UNITY_EDITOR
string key = keyLastCompletedInnerWorld(world.ID);
return PlayerPrefs.GetString(key);
#else
return null;
#endif
}
/** Keys (private helper functions if Unity Editor is being used.) **/
#if UNITY_EDITOR
private static string keyWorlds(string worldId, string postfix) {
return SoomlaLevelUp.DB_KEY_PREFIX + "worlds." + worldId + "." + postfix;
}
private static string keyWorldCompleted(string worldId) {
return keyWorlds(worldId, "completed");
}
private static string keyReward(string worldId) {
return keyWorlds(worldId, "assignedReward");
}
private static string keyLastCompletedInnerWorld(string worldId) {
return keyWorlds(worldId, "lastCompletedInnerWorld");
}
#endif
}
}
| |
namespace Microsoft.Protocols.TestSuites.SharedAdapter
{
using Microsoft.Protocols.TestSuites.Common;
using System;
using System.Collections.Generic;
/// <summary>
/// A 9-byte encoding of values in the range 0x0002000000000000 through 0xFFFFFFFFFFFFFFFF
/// </summary>
public class Compact64bitInt : BasicObject
{
/// <summary>
/// Specify the type value for compact uint zero type value.
/// </summary>
public const int CompactUintNullType = 0;
/// <summary>
/// Specify the type value for compact uint 7 bits type value.
/// </summary>
public const int CompactUint7bitType = 1;
/// <summary>
/// Specify the type value for compact uint 14 bits type value.
/// </summary>
public const int CompactUint14bitType = 2;
/// <summary>
/// Specify the type value for compact uint 21 bits type value.
/// </summary>
public const int CompactUint21bitType = 4;
/// <summary>
/// Specify the type value for compact uint 28 bits type value.
/// </summary>
public const int CompactUint28bitType = 8;
/// <summary>
/// Specify the type value for compact uint 35 bits type value.
/// </summary>
public const int CompactUint35bitType = 16;
/// <summary>
/// Specify the type value for compact uint 42 bits type value.
/// </summary>
public const int CompactUint42bitType = 32;
/// <summary>
/// Specify the type value for compact uint 49 bits type value.
/// </summary>
public const int CompactUint49bitType = 64;
/// <summary>
/// Specify the type value for compact uint 64 bits type value.
/// </summary>
public const int CompactUint64bitType = 128;
/// <summary>
/// Initializes a new instance of the Compact64bitInt class with specified value.
/// </summary>
/// <param name="decodedValue">Decoded value</param>
public Compact64bitInt(ulong decodedValue)
{
this.DecodedValue = decodedValue;
}
/// <summary>
/// Initializes a new instance of the Compact64bitInt class, this is the default constructor.
/// </summary>
public Compact64bitInt()
{
this.DecodedValue = 0;
}
/// <summary>
/// Gets or sets the Type value.
/// </summary>
public uint Type { get; set; }
/// <summary>
/// Gets or sets the value represented by the compact uint value.
/// </summary>
public ulong DecodedValue { get; set; }
/// <summary>
/// This method is used to convert the element of Compact64bitInt basic object into a byte List.
/// </summary>
/// <returns>Return the byte list which store the byte information of Compact64bitInt.</returns>
public override List<byte> SerializeToByteList()
{
BitWriter bitWriter = new BitWriter(9);
if (this.DecodedValue == 0)
{
bitWriter.AppendUInt64(0, 8);
}
else if (this.DecodedValue >= 0x01 && this.DecodedValue <= 0x7F)
{
bitWriter.AppendUInt64(CompactUint7bitType, 1);
bitWriter.AppendUInt64(this.DecodedValue, 7);
}
else if (this.DecodedValue >= 0x0080 && this.DecodedValue <= 0x3FFF)
{
bitWriter.AppendUInt64(CompactUint14bitType, 2);
bitWriter.AppendUInt64(this.DecodedValue, 14);
}
else if (this.DecodedValue >= 0x004000 && this.DecodedValue <= 0x1FFFFF)
{
bitWriter.AppendUInt64(CompactUint21bitType, 3);
bitWriter.AppendUInt64(this.DecodedValue, 21);
}
else if (this.DecodedValue >= 0x0200000 && this.DecodedValue <= 0xFFFFFFF)
{
bitWriter.AppendUInt64(CompactUint28bitType, 4);
bitWriter.AppendUInt64(this.DecodedValue, 28);
}
else if (this.DecodedValue >= 0x010000000 && this.DecodedValue <= 0x7FFFFFFFF)
{
bitWriter.AppendUInt64(CompactUint35bitType, 5);
bitWriter.AppendUInt64(this.DecodedValue, 35);
}
else if (this.DecodedValue >= 0x00800000000 && this.DecodedValue <= 0x3FFFFFFFFFF)
{
bitWriter.AppendUInt64(CompactUint42bitType, 6);
bitWriter.AppendUInt64(this.DecodedValue, 42);
}
else if (this.DecodedValue >= 0x0040000000000 && this.DecodedValue <= 0x1FFFFFFFFFFFF)
{
bitWriter.AppendUInt64(CompactUint49bitType, 7);
bitWriter.AppendUInt64(this.DecodedValue, 49);
}
else if (this.DecodedValue >= 0x0002000000000000 && this.DecodedValue <= 0xFFFFFFFFFFFFFFFF)
{
bitWriter.AppendUInt64(CompactUint64bitType, 8);
bitWriter.AppendUInt64(this.DecodedValue, 64);
}
return new List<byte>(bitWriter.Bytes);
}
/// <summary>
/// This method is used to deserialize the Compact64bitInt basic object from the specified byte array and start index.
/// </summary>
/// <param name="byteArray">Specify the byte array.</param>
/// <param name="startIndex">Specify the start index from the byte array.</param>
/// <returns>Return the length in byte of the Compact64bitInt basic object.</returns>
protected override int DoDeserializeFromByteArray(byte[] byteArray, int startIndex) // return the length consumed
{
using (BitReader bitReader = new BitReader(byteArray, startIndex))
{
int numberOfContinousZeroBit = 0;
while (numberOfContinousZeroBit < 8 && bitReader.MoveNext())
{
if (bitReader.Current == false)
{
numberOfContinousZeroBit++;
}
else
{
break;
}
}
switch (numberOfContinousZeroBit)
{
case 0:
this.DecodedValue = bitReader.ReadUInt64(7);
this.Type = CompactUint7bitType;
return 1;
case 1:
this.DecodedValue = bitReader.ReadUInt64(14);
this.Type = CompactUint14bitType;
return 2;
case 2:
this.DecodedValue = bitReader.ReadUInt64(21);
this.Type = CompactUint21bitType;
return 3;
case 3:
this.DecodedValue = bitReader.ReadUInt64(28);
this.Type = CompactUint28bitType;
return 4;
case 4:
this.DecodedValue = bitReader.ReadUInt64(35);
this.Type = CompactUint35bitType;
return 5;
case 5:
this.DecodedValue = bitReader.ReadUInt64(42);
this.Type = CompactUint42bitType;
return 6;
case 6:
this.DecodedValue = bitReader.ReadUInt64(49);
this.Type = CompactUint49bitType;
return 7;
case 7:
this.DecodedValue = bitReader.ReadUInt64(64);
this.Type = CompactUint64bitType;
return 9;
case 8:
this.DecodedValue = 0;
this.Type = CompactUintNullType;
return 1;
default:
throw new InvalidOperationException("Failed to parse the Compact64bitInt, the type value is unexpected");
}
}
}
}
}
| |
#if ANDROID || WINDOWS_8 || IOS
#define USES_DOT_SLASH_ABOLUTE_FILES
#endif
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using FileManager = FlatRedBall.IO.FileManager;
using FlatRedBall.Graphics;
using FlatRedBall.Graphics.Texture;
using FlatRedBall.Graphics.Particle;
using FlatRedBall.Content.Particle;
using FlatRedBall.AI.Pathfinding;
using FlatRedBall.Content.AI.Pathfinding;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Content.Math.Geometry;
using FlatRedBall.Math;
using FlatRedBall.Content.Polygon;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Content.AnimationChain;
using FlatRedBall.Gui;
using FlatRedBall.Content.Saves;
using FlatRedBall.Math.Splines;
using FlatRedBall.Content.Math.Splines;
using System.Threading;
#if MONOGAME
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Audio;
#endif
#if !MONODROID && !MONOGAME
using Image = System.Drawing.Image;
using FlatRedBall.IO.Gif;
using FlatRedBall.IO; // For Image
#endif
using FlatRedBall.IO.Csv;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.IO;
using Color = Microsoft.Xna.Framework.Color;
using Microsoft.Xna.Framework.Media;
using FlatRedBall.Content.ContentLoaders;
namespace FlatRedBall.Content
{
//public delegate void UnloadMethod();
public partial class ContentManager : Microsoft.Xna.Framework.Content.ContentManager
{
#region Fields
TextureContentLoader textureContentLoader = new TextureContentLoader();
//internal Dictionary<string, Type> mAssetTypeAssociation;
internal Dictionary<string, object> mAssets;
internal Dictionary<string, IDisposable> mDisposableDictionary = new Dictionary<string, IDisposable>();
Dictionary<string, object> mNonDisposableDictionary = new Dictionary<string, object>();
Dictionary<string, Action> mUnloadMethods = new Dictionary<string, Action>();
/// <summary>
/// If true FlatRedBall will look for cached content in the Global content manager even if
/// the ContentManager passed to the Load function is not Global. This defaults to true.
/// </summary>
public static bool LoadFromGlobalIfExists = true;
#if FRB_XNA && !WINDOWS_PHONE && !MONOGAME
internal Effect mFirstEffect = null;
internal EffectCache mFirstEffectCache = null;
#endif
#if PROFILE
static List<ContentLoadHistory> mHistory = new List<ContentLoadHistory>();
#endif
string mName;
#endregion
#region Default Content
#region Default Font Texture Data
#if !FRB_MDX && !SILVERLIGHT
public static Texture2D GetDefaultFontTexture(GraphicsDevice graphicsDevice)
{
var colors = DefaultFontDataColors.GetColorArray();
Texture2D texture = new Texture2D(graphicsDevice, 256, 128);
#if XNA3
texture.SetData<Microsoft.Xna.Framework.Graphics.Color>(colors);
#else
texture.SetData<Microsoft.Xna.Framework.Color>(colors);
#endif
return texture;
}
#endif
#endregion
#endregion
#region Properties
public IEnumerable<IDisposable> DisposableObjects
{
get
{
return mDisposableDictionary.Values;
}
}
public List<ManualResetEvent> ManualResetEventList
{
get;
private set;
}
public bool IsWaitingOnAsyncLoadsToFinish
{
get
{
foreach (ManualResetEvent mre in ManualResetEventList)
{
if (mre.WaitOne(0) == false)
{
return true;
}
}
return false;
}
}
public string Name
{
get { return mName; }
}
#if PROFILE
public static List<ContentLoadHistory> LoadingHistory
{
get { return mHistory; }
}
#endif
#if DEBUG
public static bool ThrowExceptionOnGlobalContentLoadedInNonGlobal
{
get;
set;
}
#endif
#endregion
#region Methods
#region Constructors
public ContentManager(string name, IServiceProvider serviceProvider)
: base(serviceProvider)
{
mName = name;
// mAssetTypeAssociation = new Dictionary<string, Type>();
mAssets = new Dictionary<string, object>();
ManualResetEventList = new List<ManualResetEvent>();
}
public ContentManager(string name, IServiceProvider serviceProvider, string rootDictionary)
: base(serviceProvider, rootDictionary)
{
mName = name;
// mAssetTypeAssociation = new Dictionary<string, Type>();
mAssets = new Dictionary<string, object>();
ManualResetEventList = new List<ManualResetEvent>();
}
#endregion
#region Public Methods
public void AddDisposable(string disposableName, IDisposable disposable)
{
if (FileManager.IsRelative(disposableName))
{
disposableName = FileManager.MakeAbsolute(disposableName);
}
disposableName = FileManager.Standardize(disposableName);
string modifiedName = disposableName + disposable.GetType().Name;
lock (mDisposableDictionary)
{
mDisposableDictionary.Add(modifiedName, disposable);
}
}
public void AddNonDisposable(string objectName, object objectToAdd)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
string modifiedName = objectName + objectToAdd.GetType().Name;
mNonDisposableDictionary.Add(modifiedName, objectToAdd);
}
public void AddUnloadMethod(string uniqueID, Action unloadMethod)
{
if (!mUnloadMethods.ContainsKey(uniqueID))
{
mUnloadMethods.Add(uniqueID, unloadMethod);
}
}
public T GetDisposable<T>(string objectName)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
objectName += typeof(T).Name;
return (T)mDisposableDictionary[objectName];
}
// This used to be internal - making it public since users use this
public T GetNonDisposable<T>(string objectName)
{
if (FileManager.IsRelative(objectName))
{
objectName = FileManager.MakeAbsolute(objectName);
}
objectName += typeof(T).Name;
return (T)mNonDisposableDictionary[objectName];
}
public bool IsAssetLoadedByName<T>(string assetName)
{
if (FileManager.IsRelative(assetName))
{
assetName = FileManager.MakeAbsolute(assetName);
}
assetName = FileManager.Standardize(assetName);
string combinedName = assetName + typeof(T).Name;
if (mDisposableDictionary.ContainsKey(combinedName))
{
return true;
}
else if (mNonDisposableDictionary.ContainsKey(combinedName))
{
return true;
}
else if (mAssets.ContainsKey(combinedName))
{
return true;
}
else
{
return false;
}
}
public bool IsAssetLoadedByReference(object objectToCheck)
{
return mDisposableDictionary.ContainsValue(objectToCheck as IDisposable) ||
mNonDisposableDictionary.ContainsValue(objectToCheck) ||
mAssets.ContainsValue(objectToCheck);
}
// Ok, let's explain why this method uses the "new" keyword.
// In the olden days (before September 2009) the user would call
// FlatRedBallServices.Load<TypeToLoad> which would investigate whether
// the user passed an assetName that had an extension or not. Then the
// FlatRedBallServices class would call LoadFromFile or LoadFromProject
// depending on the presence of an extension.
//
// In an effort to reduce the responsibilities of the FlatRedBallServices
// class, Vic decided to move the loading code (including the logic that branches
// depending on whether an asset has an extension) into the ContentManager class.
// To keep things simple, the FlatRedBallServices just has to call Load and the Load
// method will do the branching inside the ContentManager class. That all worked well,
// except that the branching code also "standardizes" the name, which means it turns relative
// paths into absolute paths. The reason this is a problem is IF the user loads an object (such
// as a .X file) which references another file, then the Load method will be called again on the referenced
// asset name.
//
// The FRB ContentManager doesn't use relative directories - instead, it makes all assets relative to the .exe
// by calling Standardize. However, if Load is called by XNA code (such as when loading a .X file)
// then any files referenced by the X will come in already made relative to the ContentManager.
// This means that if a .X file was "Content\myModel" and it referenced myTexture.png which was in the same
// folder as the .X file, then Load would get called with "Content\myTexture" as the argument. That is, the .X loading
// code would already prepend "Content\" before "myTexture. But the FRB content manager wouldn't know this, and it'd
// try to standardize it as well, making the file "Content\Content\myTexture."
//
// So the solution? We make Load a "new" method. That means that if Load is called by XNA, then it'll call the
// Load of XNA's ContentManager. But if FRB calls it, it'll call the "new" version. Problem solved.
public new T Load<T>(string assetName)
{
// Assets can be loaded either from file or from assets referenced
// in the project.
string extension = FileManager.GetExtension(assetName);
#region If there is an extension, loading from file or returning an already-loaded asset
assetName = FileManager.Standardize(assetName);
if (extension != String.Empty)
{
return LoadFromFile<T>(assetName);
}
#endregion
#region Else there is no extension, so the file is already part of the project. Use a ContentManager
else
{
#if PROFILE
bool exists = false;
exists = IsAssetLoadedByName<T>(assetName);
if (exists)
{
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, assetName, ContentLoadDetail.Cached));
}
else
{
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, assetName, ContentLoadDetail.HddFromContentPipeline));
}
#endif
return LoadFromProject<T>(assetName);
}
#endregion
}
public T LoadFromProject<T>(string assetName)
{
string oldRelativePath = FileManager.RelativeDirectory;
FlatRedBall.IO.FileManager.RelativeDirectory = FileManager.GetDirectory(assetName);
#if DEBUG
bool shouldCheckForXnb = true;
#if ANDROID
if(typeof(T) == typeof(Song))
{
shouldCheckForXnb = false;
}
#endif
string fileToCheckFor = assetName + ".xnb";
if (shouldCheckForXnb && !FileManager.FileExists(fileToCheckFor))
{
string errorString = "Could not find the file " + fileToCheckFor + "\n";
#if !WINDOWS_8
List<string> filesInDirectory = FileManager.GetAllFilesInDirectory(FileManager.GetDirectory(assetName), null, 0);
errorString += "Found the following files:\n\n";
foreach (string s in filesInDirectory)
{
errorString += FileManager.RemovePath(s) + "\n";
}
#endif
throw new FileNotFoundException(errorString);
}
#endif
#if XNA4 && !MONOGAME
if (!FileManager.IsRelative(assetName))
{
assetName = FileManager.MakeRelative(
assetName, System.Windows.Forms.Application.StartupPath + "/");
}
#endif
#if USES_DOT_SLASH_ABOLUTE_FILES
T asset;
if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./"))
{
asset = base.Load<T>(assetName.Substring(2));
}
else
{
asset = base.Load<T>(assetName);
}
#else
T asset = base.Load<T>(assetName);
#endif
if (!mAssets.ContainsKey(assetName))
{
mAssets.Add(assetName, asset);
}
FileManager.RelativeDirectory = oldRelativePath;
return AdjustNewAsset(asset, assetName);
}
public T LoadFromFile<T>(string assetName)
{
string extension = FileManager.GetExtension(assetName);
if (FileManager.IsRelative(assetName))
{
// get the absolute path using the current relative directory
assetName = FileManager.RelativeDirectory + assetName;
}
string fullNameWithType = assetName + typeof(T).Name;
// get the dictionary by the contentManagerName. If it doesn't exist, GetDisposableDictionaryByName
// will create it.
if (mDisposableDictionary.ContainsKey(fullNameWithType))
{
#if PROFILE
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime, typeof(T).Name, fullNameWithType, ContentLoadDetail.Cached));
#endif
return ((T)mDisposableDictionary[fullNameWithType]);
}
else if (mNonDisposableDictionary.ContainsKey(fullNameWithType))
{
return ((T)mNonDisposableDictionary[fullNameWithType]);
}
else
{
#if PROFILE
mHistory.Add(new ContentLoadHistory(
TimeManager.CurrentTime,
typeof(T).Name,
fullNameWithType,
ContentLoadDetail.HddFromFile));
#endif
#if DEBUG
// The ThrowExceptionIfFileDoesntExist
// call used to be done before the checks
// in the dictionaries. But whatever is held
// in there may not really be a file so let's check
// if the file exists after we check the dictionaries.
FileManager.ThrowExceptionIfFileDoesntExist(assetName);
#endif
IDisposable loadedAsset = null;
if (typeof(T) == typeof(Texture2D) || typeof(T) == typeof(Microsoft.Xna.Framework.Graphics.Texture2D))
{
// for now we'll create it here, eventually have it in a dictionary:
loadedAsset = textureContentLoader.Load(assetName);
}
#region Scene
else if (typeof(T) == typeof(FlatRedBall.Scene))
{
FlatRedBall.Scene scene = FlatRedBall.Content.Scene.SceneSave.FromFile(assetName).ToScene(mName);
object sceneAsObject = scene;
lock (mNonDisposableDictionary)
{
if (!mNonDisposableDictionary.ContainsKey(fullNameWithType))
{
mNonDisposableDictionary.Add(fullNameWithType, scene);
}
}
return (T)sceneAsObject;
}
#endregion
#region EmitterList
else if (typeof(T) == typeof(EmitterList))
{
EmitterList emitterList = EmitterSaveList.FromFile(assetName).ToEmitterList(mName);
mNonDisposableDictionary.Add(fullNameWithType, emitterList);
return (T)((object)emitterList);
}
#endregion
#region Image
#if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME
else if (typeof(T) == typeof(Image))
{
switch (extension.ToLowerInvariant())
{
case "gif":
Image image = Image.FromFile(assetName);
loadedAsset = image;
break;
}
}
#endif
#endregion
#region BitmapList
#if !XBOX360 && !SILVERLIGHT && !WINDOWS_PHONE && !MONOGAME
else if (typeof(T) == typeof(BitmapList))
{
loadedAsset = BitmapList.FromFile(assetName);
}
#endif
#endregion
#region NodeNetwork
else if (typeof(T) == typeof(NodeNetwork))
{
NodeNetwork nodeNetwork = NodeNetworkSave.FromFile(assetName).ToNodeNetwork();
mNonDisposableDictionary.Add(fullNameWithType, nodeNetwork);
return (T)((object)nodeNetwork);
}
#endregion
#region ShapeCollection
else if (typeof(T) == typeof(ShapeCollection))
{
ShapeCollection shapeCollection =
ShapeCollectionSave.FromFile(assetName).ToShapeCollection();
mNonDisposableDictionary.Add(fullNameWithType, shapeCollection);
return (T)((object)shapeCollection);
}
#endregion
#region PositionedObjectList<Polygon>
else if (typeof(T) == typeof(PositionedObjectList<FlatRedBall.Math.Geometry.Polygon>))
{
PositionedObjectList<FlatRedBall.Math.Geometry.Polygon> polygons =
PolygonSaveList.FromFile(assetName).ToPolygonList();
mNonDisposableDictionary.Add(fullNameWithType, polygons);
return (T)((object)polygons);
}
#endregion
#region AnimationChainList
else if (typeof(T) == typeof(AnimationChainList))
{
if (assetName.EndsWith("gif"))
{
#if WINDOWS_8 || UWP || DESKTOP_GL
throw new NotImplementedException();
#else
AnimationChainList acl = new AnimationChainList();
acl.Add(FlatRedBall.Graphics.Animation.AnimationChain.FromGif(assetName, this.mName));
acl[0].ParentGifFileName = assetName;
loadedAsset = acl;
#endif
}
else
{
loadedAsset =
AnimationChainListSave.FromFile(assetName).ToAnimationChainList(mName);
}
mNonDisposableDictionary.Add(fullNameWithType, loadedAsset);
}
#endregion
else if(typeof(T) == typeof(Song))
{
var loader = new SongLoader();
return (T)(object) loader.Load(assetName);
}
#if MONOGAME
else if (typeof(T) == typeof(SoundEffect))
{
T soundEffect;
if (assetName.StartsWith(@".\") || assetName.StartsWith(@"./"))
{
soundEffect = base.Load<T>(assetName.Substring(2));
}
else
{
soundEffect = base.Load<T>(assetName);
}
return soundEffect;
}
#endif
#region RuntimeCsvRepresentation
#if !SILVERLIGHT
else if (typeof(T) == typeof(RuntimeCsvRepresentation))
{
#if XBOX360
throw new NotImplementedException("Can't load CSV from file. Try instead to use the content pipeline.");
#else
return (T)((object)CsvFileManager.CsvDeserializeToRuntime(assetName));
#endif
}
#endif
#endregion
#region SplineList
else if (typeof(T) == typeof(List<Spline>))
{
List<Spline> splineList = SplineSaveList.FromFile(assetName).ToSplineList();
mNonDisposableDictionary.Add(fullNameWithType, splineList);
object asObject = splineList;
return (T)asObject;
}
else if (typeof(T) == typeof(SplineList))
{
SplineList splineList = SplineSaveList.FromFile(assetName).ToSplineList();
mNonDisposableDictionary.Add(fullNameWithType, splineList);
object asObject = splineList;
return (T)asObject;
}
#endregion
#region BitmapFont
else if (typeof(T) == typeof(BitmapFont))
{
// We used to assume the texture is named the same as the font file
// But now FRB understands the .fnt file and gets the PNG from the font file
//string pngFile = FileManager.RemoveExtension(assetName) + ".png";
string fntFile = FileManager.RemoveExtension(assetName) + ".fnt";
BitmapFont bitmapFont = new BitmapFont(fntFile, this.mName);
object bitmapFontAsObject = bitmapFont;
return (T)bitmapFontAsObject;
}
#endregion
#region Text
else if (typeof(T) == typeof(string))
{
return (T)((object)FileManager.FromFileText(assetName));
}
#endregion
#region Catch mistakes
#if DEBUG
else if (typeof(T) == typeof(Spline))
{
throw new Exception("Cannot load Splines. Try using the List<Spline> type instead.");
}
else if (typeof(T) == typeof(Emitter))
{
throw new Exception("Cannot load Emitters. Try using the EmitterList type instead.");
}
#endif
#endregion
#region else, exception!
else
{
throw new NotImplementedException("Cannot load content of type " +
typeof(T).AssemblyQualifiedName + " from file. If you are loading " +
"through the content pipeline be sure to remove the extension of the file " +
"name.");
}
#endregion
if (loadedAsset != null)
{
lock (mDisposableDictionary)
{
// Multiple threads could try to load this content simultaneously
if (!mDisposableDictionary.ContainsKey(fullNameWithType))
{
mDisposableDictionary.Add(fullNameWithType, loadedAsset);
}
}
}
return ((T)loadedAsset);
}
}
/// <summary>
/// Removes an IDisposable from the ContentManager. This method does not call Dispose on the argument Disposable. It
/// must be disposed
/// </summary>
/// <param name="disposable">The IDisposable to be removed</param>
public void RemoveDisposable(IDisposable disposable)
{
KeyValuePair<string, IDisposable>? found = null;
foreach(var kvp in mDisposableDictionary)
{
if(kvp.Value == disposable)
{
found = kvp;
break;
}
}
if(found != null)
{
mDisposableDictionary.Remove(found.Value.Key);
}
}
public void UnloadAsset<T>(T assetToUnload)
{
#region Remove from non-disposables if the non-disposables containes the assetToUnload
if (this.mNonDisposableDictionary.ContainsValue(assetToUnload))
{
string assetName = "";
foreach (KeyValuePair<string, object> kvp in mNonDisposableDictionary)
{
if (kvp.Value == assetToUnload as object)
{
assetName = kvp.Key;
break;
}
}
mNonDisposableDictionary.Remove(assetName);
}
#endregion
#region If it's an IDisposable, then remove it from the disposable dictionary
if (assetToUnload is IDisposable)
{
IDisposable asDisposable = assetToUnload as IDisposable;
if (this.mDisposableDictionary.ContainsValue(asDisposable))
{
asDisposable.Dispose();
string assetName = "";
foreach (KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
{
if (kvp.Value == ((IDisposable)assetToUnload))
{
assetName = kvp.Key;
break;
}
}
mDisposableDictionary.Remove(assetName);
}
else
{
throw new ArgumentException("The content manager " + mName + " does not contain the argument " +
"assetToUnload. Check the " +
"contentManagerName and verify that it is a contentManager that has loaded this asset. Assets which have been " +
"loaded from the project must be loaded by unloading an entire Content Manager");
}
}
#endregion
}
public new void Unload()
{
if (IsWaitingOnAsyncLoadsToFinish)
{
FlatRedBallServices.MoveContentManagerToWaitingToUnloadList(this);
}
else
{
#if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE
base.Unload();
#endif
this.mAssets.Clear();
this.mNonDisposableDictionary.Clear();
foreach (KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
{
kvp.Value.Dispose();
}
foreach (Action unloadMethod in mUnloadMethods.Values)
{
unloadMethod();
}
mUnloadMethods.Clear();
mDisposableDictionary.Clear();
}
}
#if PROFILE
public static void RecordEvent(string eventName)
{
ContentLoadHistory history = new ContentLoadHistory();
history.SpecialEvent = eventName;
mHistory.Add(history);
}
public static void SaveContentLoadingHistory(string fileToSaveTo)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (ContentLoadHistory clh in mHistory)
{
if (!string.IsNullOrEmpty(clh.SpecialEvent))
{
stringBuilder.AppendLine("========================================");
stringBuilder.AppendLine(clh.SpecialEvent);
stringBuilder.AppendLine("========================================");
stringBuilder.AppendLine();
}
else
{
stringBuilder.AppendLine("Time:\t\t" + clh.Time);
stringBuilder.AppendLine("Content Type:\t" + clh.Type);
stringBuilder.AppendLine("Content Name:\t" + clh.ContentName);
stringBuilder.AppendLine("Detail:\t\t" + clh.ContentLoadDetail);
stringBuilder.AppendLine();
}
}
FileManager.SaveText(stringBuilder.ToString(), fileToSaveTo);
}
#endif
#endregion
#region Internal Methods
// Vic says: I don't think we need this anymore
internal void RefreshTextureOnDeviceLost()
{
//List<string> texturesToReload = new List<string>();
//foreach(KeyValuePair<string, IDisposable> kvp in mDisposableDictionary)
//{
// if (kvp.Value is Texture2D)
// {
// texturesToReload.Add(kvp.Key);
// kvp.Value.Dispose();
// contentManagers.Add(kvp.Key);
// fileNames.Add(subKvp.Key);
// }
//}
//kvp.Value.Clear();
}
#endregion
#region Private Methods
private T AdjustNewAsset<T>(T asset, string assetName)
{
#if FRB_XNA
if (asset is Microsoft.Xna.Framework.Graphics.Texture)
{
(asset as Microsoft.Xna.Framework.Graphics.Texture).Name = assetName;
}
#if WINDOWS_PHONE || WINDOWS_8 || MONOGAME
// do nothing???
#else
else if (mFirstEffect == null && asset is Effect)
{
lock (Renderer.GraphicsDevice)
{
mFirstEffect = asset as Effect;
mFirstEffectCache = new EffectCache(mFirstEffect, true);
}
}
#endif
#elif SILVERLIGHT
if (asset is Texture2D)
{
(asset as Texture2D).Name = assetName;
}
#endif
if (asset is FlatRedBall.Scene)
{
return (T)(object)((asset as FlatRedBall.Scene).Clone());
}
else if (asset is FlatRedBall.Graphics.Particle.EmitterList)
{
return (T)(object)(asset as FlatRedBall.Graphics.Particle.EmitterList).Clone();
}
else
{
return asset;
}
}
#endregion
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//Similar to StrAccess1, but instead of using constants, different expression is used as the index to access the string
using System;
internal struct VT
{
public String str;
public char b0, b1, b2, b3, b4, b5, b6;
public int i;
public int[][] idxja;
}
internal class CL
{
public String str = "test string";
public char b0, b1, b2, b3, b4, b5, b6;
public static int i = 10;
public int[,] idx2darr = { { 5, 6 } };
}
internal unsafe class StrAccess2
{
public static String str1 = "test string";
public static int idx1 = 2;
public static String[,] str2darr = { { "test string" } };
public static int[,,] idx3darr = { { { 8 } } };
public static char sb0, sb1, sb2, sb3, sb4, sb5, sb6;
public static String f(ref String arg)
{
return arg;
}
public static int f1(ref int arg)
{
return arg;
}
public static Random rand = new Random();
public static int Main()
{
bool passed = true;
int* p = stackalloc int[11];
for (int m = 0; m < 11; m++) p[m] = m;
String str2 = "test string";
String[] str1darr = { "string access", "test string" };
Char[,] c2darr = { { '0', '1', '2', '3', '4', '5', '6' }, { 'a', 'b', 'c', 'd', 'e', 'f', 'g' } };
CL cl1 = new CL();
VT vt1;
vt1.i = 0;
vt1.str = "test string";
vt1.idxja = new int[2][];
vt1.idxja[1] = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int idx2 = 4;
int[] idx1darr = { 3, 9, 4, 2, 6, 1, 8, 10, 5, 7, 0 };
char b0, b1, b2, b3, b4, b5, b6;
//accessing the strings at different indices. assign to local char
b0 = str2[vt1.i];
b1 = str1[vt1.i];
b2 = cl1.str[vt1.i];
b3 = vt1.str[vt1.i];
b4 = str1darr[1][vt1.i];
b5 = str2darr[0, 0][vt1.i];
b6 = f(ref str2)[vt1.i];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
if ((str2[idx2] != str1[idx2]) || (str1[idx2] != cl1.str[idx2]) || (cl1.str[idx2] != vt1.str[idx2]) || (vt1.str[idx2] != str1darr[1][idx2]) || (str1darr[1][idx2] != str2darr[0, 0][idx2]) || (str2darr[0, 0][idx2] != f(ref str2)[idx2]))
passed = false;
b0 = str2[CL.i];
b1 = str1[CL.i];
b2 = cl1.str[CL.i];
b3 = vt1.str[CL.i];
b4 = str1darr[1][CL.i];
b5 = str2darr[0, 0][CL.i];
b6 = f(ref str2)[CL.i];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
int j = rand.Next(0, 10);
b0 = str2[idx1darr[j]];
b1 = str1[idx1darr[j]];
b2 = cl1.str[idx1darr[j]];
b3 = vt1.str[idx1darr[j]];
b4 = str1darr[1][idx1darr[j]];
b5 = str2darr[0, 0][idx1darr[j]];
b6 = f(ref str2)[idx1darr[j]];
if ((b0 != b1) || (b1 != b2) || (b2 != b3) || (b3 != b4) || (b4 != b5) || (b5 != b6))
passed = false;
//accessing the strings at different indices, assign to static char
sb0 = str2[idx1 - 1];
sb1 = str1[idx1 - 1];
sb2 = cl1.str[idx1 - 1];
sb3 = vt1.str[idx1 - 1];
sb4 = str1darr[idx1 - 1][idx1 - 1];
sb5 = str2darr[0, 0][idx1 - 1];
sb6 = f(ref str2)[idx1 - 1];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6) || (sb6 != str2[1]))
passed = false;
if ((str2[5] != str1[5]) || (str1[5] != cl1.str[5]) || (cl1.str[5] != vt1.str[5]) || (vt1.str[5] != str1darr[1][5]) || (str1darr[1][5] != str2darr[0, 0][5]) || (str2darr[0, 0][5] != f(ref str2)[5]))
passed = false;
sb0 = str2[idx3darr[0, 0, 0] + 1];
sb1 = str1[idx3darr[0, 0, 0] + 1];
sb2 = cl1.str[idx3darr[0, 0, 0] + 1];
sb3 = vt1.str[idx3darr[0, 0, 0] + 1];
sb4 = str1darr[1][idx3darr[0, 0, 0] + 1];
sb5 = str2darr[0, 0][idx3darr[0, 0, 0] + 1];
sb6 = f(ref str2)[idx3darr[0, 0, 0] + 1];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6))
passed = false;
j = rand.Next(0, 10);
sb0 = str2[vt1.idxja[1][j]];
sb1 = str1[vt1.idxja[1][j]];
sb2 = cl1.str[vt1.idxja[1][j]];
sb3 = vt1.str[vt1.idxja[1][j]];
sb4 = str1darr[1][vt1.idxja[1][j]];
sb5 = str2darr[0, 0][vt1.idxja[1][j]];
sb6 = f(ref str2)[vt1.idxja[1][j]];
if ((sb0 != sb1) || (sb1 != sb2) || (sb2 != sb3) || (sb3 != sb4) || (sb4 != sb5) || (sb5 != sb6))
passed = false;
//accessing the strings at different indices, assign to VT char
vt1.b0 = str2[idx2 - idx1];
vt1.b1 = str1[idx2 - idx1];
vt1.b2 = cl1.str[idx2 - idx1];
vt1.b3 = vt1.str[idx2 - idx1];
vt1.b4 = str1darr[1][idx2 - idx1];
vt1.b5 = str2darr[0, 0][idx2 - idx1];
vt1.b6 = f(ref str2)[idx2 - idx1];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
if ((str2[cl1.idx2darr[0, 1]] != str1[cl1.idx2darr[0, 1]]) || (str1[cl1.idx2darr[0, 1]] != cl1.str[cl1.idx2darr[0, 1]]) || (cl1.str[cl1.idx2darr[0, 1]] != vt1.str[cl1.idx2darr[0, 1]]) || (vt1.str[cl1.idx2darr[0, 1]] != str1darr[1][cl1.idx2darr[0, 1]]) || (str1darr[1][cl1.idx2darr[0, 1]] != str2darr[0, 0][cl1.idx2darr[0, 1]]) || (str2darr[0, 0][cl1.idx2darr[0, 1]] != f(ref str2)[cl1.idx2darr[0, 1]]))
passed = false;
vt1.b0 = str2[idx3darr[0, 0, 0]];
vt1.b1 = str1[idx3darr[0, 0, 0]];
vt1.b2 = cl1.str[idx3darr[0, 0, 0]];
vt1.b3 = vt1.str[idx3darr[0, 0, 0]];
vt1.b4 = str1darr[1][idx3darr[0, 0, 0]];
vt1.b5 = str2darr[0, 0][idx3darr[0, 0, 0]];
vt1.b6 = f(ref str2)[idx3darr[0, 0, 0]];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
j = rand.Next(0, 10);
vt1.b0 = str2[p[j]];
vt1.b1 = str1[p[j]];
vt1.b2 = cl1.str[p[j]];
vt1.b3 = vt1.str[p[j]];
vt1.b4 = str1darr[1][p[j]];
vt1.b5 = str2darr[0, 0][p[j]];
vt1.b6 = f(ref str2)[p[j]];
if ((vt1.b0 != vt1.b1) || (vt1.b1 != vt1.b2) || (vt1.b2 != vt1.b3) || (vt1.b3 != vt1.b4) || (vt1.b4 != vt1.b5) || (vt1.b5 != vt1.b6))
passed = false;
//accessing the strings at different indices, assign to CL char
cl1.b0 = str2[CL.i % idx1darr[0]];
cl1.b1 = str1[CL.i % idx1darr[0]];
cl1.b2 = cl1.str[CL.i % idx1darr[0]];
cl1.b3 = vt1.str[CL.i % idx1darr[0]];
cl1.b4 = str1darr[1][CL.i % idx1darr[0]];
cl1.b5 = str2darr[0, 0][CL.i % idx1darr[0]];
cl1.b6 = f(ref str2)[CL.i % idx1darr[0]];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6))
passed = false;
if ((str2[0] != str1[0]) || (str1[0] != cl1.str[0]) || (cl1.str[0] != vt1.str[0]) || (vt1.str[0] != str1darr[1][0]) || (str1darr[1][0] != str2darr[0, 0][0]) || (str2darr[0, 0][0] != f(ref str2)[0]))
passed = false;
cl1.b0 = str2[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b1 = str1[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b2 = cl1.str[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b3 = vt1.str[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b4 = str1darr[1][Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b5 = str2darr[0, 0][Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
cl1.b6 = f(ref str2)[Convert.ToInt32(c2darr[0, 4]) - Convert.ToInt32(c2darr[0, 0])];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6) || (cl1.b6 != str1[4]))
passed = false;
j = rand.Next(0, 10);
cl1.b0 = str2[j];
cl1.b1 = str1[j];
cl1.b2 = cl1.str[j];
cl1.b3 = vt1.str[j];
cl1.b4 = str1darr[1][j];
cl1.b5 = str2darr[0, 0][j];
cl1.b6 = f(ref str2)[j];
if ((cl1.b0 != cl1.b1) || (cl1.b1 != cl1.b2) || (cl1.b2 != cl1.b3) || (cl1.b3 != cl1.b4) || (cl1.b4 != cl1.b5) || (cl1.b5 != cl1.b6))
passed = false;
//accessing the strings at different indices, assign to 2d array char
c2darr[1, 0] = str2[idx1darr[0] * idx1];
c2darr[1, 1] = str1[idx1darr[0] * idx1];
c2darr[1, 2] = cl1.str[idx1darr[0] * idx1];
c2darr[1, 3] = vt1.str[idx1darr[0] * idx1];
c2darr[1, 4] = str1darr[1][idx1darr[0] * idx1];
c2darr[1, 5] = str2darr[0, 0][idx1darr[0] * idx1];
c2darr[1, 6] = f(ref str2)[idx1darr[0] * idx1];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]) || (str2[6] != c2darr[1, 6]))
passed = false;
if ((str2[vt1.i] != str1[vt1.i]) || (str1[vt1.i] != cl1.str[vt1.i]) || (cl1.str[vt1.i] != vt1.str[vt1.i]) || (vt1.str[vt1.i] != str1darr[1][vt1.i]) || (str1darr[1][vt1.i] != str2darr[0, 0][vt1.i]) || (str2darr[0, 0][vt1.i] != f(ref str2)[vt1.i]))
passed = false;
c2darr[1, 0] = str2[idx1darr[1] - idx1darr[0]];
c2darr[1, 1] = str1[idx1darr[1] - idx1darr[0]];
c2darr[1, 2] = cl1.str[idx1darr[1] - idx1darr[0]];
c2darr[1, 3] = vt1.str[idx1darr[1] - idx1darr[0]];
c2darr[1, 4] = str1darr[1][idx1darr[1] - idx1darr[0]];
c2darr[1, 5] = str2darr[0, 0][idx1darr[1] - idx1darr[0]];
c2darr[1, 6] = f(ref str2)[idx1darr[1] - idx1darr[0]];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]) || (str2[6] != c2darr[1, 6]))
passed = false;
j = rand.Next(0, 10);
c2darr[1, 0] = str2[f1(ref j)];
c2darr[1, 1] = str1[f1(ref j)];
c2darr[1, 2] = cl1.str[f1(ref j)];
c2darr[1, 3] = vt1.str[f1(ref j)];
c2darr[1, 4] = str1darr[1][f1(ref j)];
c2darr[1, 5] = str2darr[0, 0][f1(ref j)];
c2darr[1, 6] = f(ref str2)[f1(ref j)];
if ((c2darr[1, 0] != c2darr[1, 1]) || (c2darr[1, 1] != c2darr[1, 2]) || (c2darr[1, 2] != c2darr[1, 3]) || (c2darr[1, 3] != c2darr[1, 4]) || (c2darr[1, 4] != c2darr[1, 5]) || (c2darr[1, 5] != c2darr[1, 6]))
passed = false;
if (!passed)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1
{
internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer
{
private readonly int _correlationId;
private readonly MemberRangeMap _memberRangeMap;
private readonly AnalyzerExecutor _executor;
private readonly StateManager _stateManager;
/// <summary>
/// PERF: Always run analyzers sequentially for background analysis.
/// </summary>
private const bool ConcurrentAnalysis = false;
/// <summary>
/// Always compute suppressed diagnostics - diagnostic clients may or may not request for suppressed diagnostics.
/// </summary>
private const bool ReportSuppressedDiagnostics = true;
public DiagnosticIncrementalAnalyzer(
DiagnosticAnalyzerService owner,
int correlationId,
Workspace workspace,
HostAnalyzerManager analyzerManager,
AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource)
: base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource)
{
_correlationId = correlationId;
_memberRangeMap = new MemberRangeMap();
_executor = new AnalyzerExecutor(this);
_stateManager = new StateManager(analyzerManager);
_stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged;
}
private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e)
{
if (e.Removed.Length == 0)
{
// nothing to refresh
return;
}
// events will be automatically serialized.
var project = e.Project;
var stateSets = e.Removed;
// first remove all states
foreach (var stateSet in stateSets)
{
foreach (var document in project.Documents)
{
stateSet.Remove(document.Id);
}
stateSet.Remove(project.Id);
}
// now raise events
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var document in project.Documents)
{
RaiseDocumentDiagnosticsRemoved(document, stateSets, includeProjectState: true, raiseEvents: raiseEvents);
}
RaiseProjectDiagnosticsRemoved(project, stateSets, raiseEvents);
});
}
public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken))
{
return ClearOnlyDocumentStates(document);
}
}
public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken))
{
// we don't need the info for closed file
_memberRangeMap.Remove(document.Id);
return ClearOnlyDocumentStates(document);
}
}
public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken))
{
// clear states for re-analysis and raise events about it. otherwise, some states might not updated on re-analysis
// due to our build-live de-duplication logic where we put all state in Documents state.
return ClearOnlyDocumentStates(document);
}
}
private Task ClearOnlyDocumentStates(Document document)
{
// since managing states and raising events are separated, it can't be cancelled.
var stateSets = _stateManager.GetStateSets(document.Project);
// we remove whatever information we used to have on document open/close and re-calculate diagnostics
// we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not.
// so we can't use cached information.
// clean up states
foreach (var stateSet in stateSets)
{
stateSet.Remove(document.Id, onlyDocumentStates: true);
}
// raise events
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
RaiseDocumentDiagnosticsRemoved(document, stateSets, includeProjectState: false, raiseEvents: raiseEvents);
});
return SpecializedTasks.EmptyTask;
}
private bool CheckOptions(Project project, bool forceAnalysis)
{
var workspace = project.Solution.Workspace;
if (ServiceFeatureOnOffOptions.IsClosedFileDiagnosticsEnabled(workspace, project.Language) &&
workspace.Options.GetOption(RuntimeOptions.FullSolutionAnalysis))
{
return true;
}
if (forceAnalysis)
{
return true;
}
return false;
}
internal CompilationWithAnalyzers GetCompilationWithAnalyzers(
Project project,
IEnumerable<DiagnosticAnalyzer> analyzers,
Compilation compilation,
bool concurrentAnalysis,
bool reportSuppressedDiagnostics)
{
Contract.ThrowIfFalse(project.SupportsCompilation);
Contract.ThrowIfNull(compilation);
Func<Exception, bool> analyzerExceptionFilter = ex =>
{
if (project.Solution.Workspace.Options.GetOption(InternalDiagnosticsOptions.CrashOnAnalyzerException))
{
// if option is on, crash the host to get crash dump.
FatalError.ReportUnlessCanceled(ex);
}
return true;
};
var analysisOptions = new CompilationWithAnalyzersOptions(
new WorkspaceAnalyzerOptions(project.AnalyzerOptions, project.Solution.Workspace),
GetOnAnalyzerException(project.Id),
analyzerExceptionFilter: analyzerExceptionFilter,
concurrentAnalysis: concurrentAnalysis,
logAnalyzerExecutionTime: true,
reportSuppressedDiagnostics: reportSuppressedDiagnostics);
var filteredAnalyzers = analyzers
.Where(a => !CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(a, compilation.Options, analysisOptions.OnAnalyzerException))
.Distinct()
.ToImmutableArray();
if (filteredAnalyzers.IsEmpty)
{
return null;
}
return new CompilationWithAnalyzers(compilation, filteredAnalyzers, analysisOptions);
}
public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
await AnalyzeSyntaxAsync(document, diagnosticIds: null, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
try
{
if (!CheckOptions(document.Project, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
var openedDocument = document.IsOpen();
var stateSets = _stateManager.GetOrUpdateStateSets(document.Project);
var analyzers = stateSets.Select(s => s.Analyzer);
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(
document, fullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken);
foreach (var stateSet in stateSets)
{
if (await SkipRunningAnalyzerAsync(document.Project, stateSet.Analyzer, openedDocument, skipClosedFileCheck: false, cancellationToken: cancellationToken).ConfigureAwait(false))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds))
{
var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Syntax, document, stateSet, data.Items);
continue;
}
var state = stateSet.GetState(StateType.Syntax);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, cancellationToken: cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
try
{
if (!CheckOptions(document.Project, document.IsOpen()))
{
return;
}
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(textVersion, dataVersion, projectVersion);
if (bodyOpt == null)
{
await AnalyzeDocumentAsync(document, versions, diagnosticIds, cancellationToken).ConfigureAwait(false);
}
else
{
// only open file can go this route
await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken)
{
try
{
// syntax facts service must exist, otherwise, this method won't have called.
var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var memberId = syntaxFacts.GetMethodLevelMemberId(root, member);
var stateSets = _stateManager.GetOrUpdateStateSets(document.Project);
var analyzers = stateSets.Select(s => s.Analyzer);
var spanBasedDriver = new DiagnosticAnalyzerDriver(
document, member.FullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken);
var documentBasedDriver = new DiagnosticAnalyzerDriver(
document, root.FullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken);
foreach (var stateSet in stateSets)
{
if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document))
{
var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis();
var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver;
var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document);
var data = await _executor.GetDocumentBodyAnalysisDataAsync(
stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false);
_memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges);
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items);
continue;
}
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken)
{
try
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var fullSpan = root == null ? null : (TextSpan?)root.FullSpan;
bool openedDocument = document.IsOpen();
var stateSets = _stateManager.GetOrUpdateStateSets(document.Project);
var analyzers = stateSets.Select(s => s.Analyzer);
var userDiagnosticDriver = new DiagnosticAnalyzerDriver(
document, fullSpan, root, this, analyzers, ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken);
foreach (var stateSet in stateSets)
{
if (await SkipRunningAnalyzerAsync(document.Project, stateSet.Analyzer, openedDocument, skipClosedFileCheck: false, cancellationToken: cancellationToken).ConfigureAwait(false))
{
await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false);
continue;
}
if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds))
{
var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType.Document, document, stateSet, data.Items);
continue;
}
if (openedDocument)
{
_memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion);
}
var state = stateSet.GetState(StateType.Document);
await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false);
RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false);
}
private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken)
{
try
{
if (!CheckOptions(project, forceAnalysis: false))
{
return;
}
// PERF: Ensure that we explicitly ignore the skipped analyzers while creating the analyzer driver, otherwise we might end up running hidden analyzers on closed files.
var stateSets = _stateManager.GetOrUpdateStateSets(project).ToImmutableArray();
var skipAnalyzersMap = new Dictionary<DiagnosticAnalyzer, bool>(stateSets.Length);
var shouldRunAnalyzersMap = new Dictionary<DiagnosticAnalyzer, bool>(stateSets.Length);
var analyzersBuilder = ImmutableArray.CreateBuilder<DiagnosticAnalyzer>(stateSets.Length);
foreach (var stateSet in stateSets)
{
var skip = await SkipRunningAnalyzerAsync(project, stateSet.Analyzer, openedDocument: false, skipClosedFileCheck: true, cancellationToken: cancellationToken).ConfigureAwait(false);
skipAnalyzersMap.Add(stateSet.Analyzer, skip);
var shouldRun = !skip && ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null);
shouldRunAnalyzersMap.Add(stateSet.Analyzer, shouldRun);
if (shouldRun)
{
analyzersBuilder.Add(stateSet.Analyzer);
}
}
var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, analyzersBuilder.ToImmutable(), ConcurrentAnalysis, ReportSuppressedDiagnostics, cancellationToken);
var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false);
var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);
var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion);
foreach (var stateSet in stateSets)
{
// Compilation actions can report diagnostics on open files, so we skipClosedFileChecks.
if (skipAnalyzersMap[stateSet.Analyzer])
{
await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false);
continue;
}
if (shouldRunAnalyzersMap[stateSet.Analyzer])
{
var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false);
if (data.FromCache)
{
RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, ImmutableArray<DiagnosticData>.Empty, data.Items);
continue;
}
var state = stateSet.GetState(StateType.Project);
await PersistProjectData(project, state, data).ConfigureAwait(false);
RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items);
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private async Task<bool> SkipRunningAnalyzerAsync(Project project, DiagnosticAnalyzer analyzer, bool openedDocument, bool skipClosedFileCheck, CancellationToken cancellationToken)
{
// this project is not in a good state. only continue if it is opened document.
if (!await project.HasSuccessfullyLoadedAsync(cancellationToken).ConfigureAwait(false) && !openedDocument)
{
return true;
}
if (Owner.IsAnalyzerSuppressed(analyzer, project))
{
return true;
}
if (skipClosedFileCheck || ShouldRunAnalyzerForClosedFile(analyzer, project.CompilationOptions, openedDocument))
{
return false;
}
return true;
}
private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data)
{
// TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to
// things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesn't come online soon enough
// more refactoring is required on project state.
// clear all existing data
state.Remove(project.Id);
foreach (var document in project.Documents)
{
state.Remove(document.Id);
}
// quick bail out
if (data.Items.Length == 0)
{
return;
}
// save new data
var group = data.Items.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
// save project scope diagnostics
await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
continue;
}
// save document scope diagnostics
var document = project.GetDocument(kv.Key);
if (document == null)
{
continue;
}
await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false);
}
}
public override void RemoveDocument(DocumentId documentId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None))
{
_memberRangeMap.Remove(documentId);
var stateSets = _stateManager.GetStateSets(documentId.ProjectId);
foreach (var stateSet in stateSets)
{
stateSet.Remove(documentId);
}
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId);
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
RaiseDiagnosticsRemoved((StateType)stateType, documentId, stateSet, solutionArgs, raiseEvents);
}
}
});
}
}
public override void RemoveProject(ProjectId projectId)
{
using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None))
{
var stateSets = _stateManager.GetStateSets(projectId);
foreach (var stateSet in stateSets)
{
stateSet.Remove(projectId);
}
_stateManager.RemoveStateSet(projectId);
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
foreach (var stateSet in stateSets)
{
var solutionArgs = new SolutionArgument(null, projectId, null);
RaiseDiagnosticsRemoved(StateType.Project, projectId, stateSet, solutionArgs, raiseEvents);
}
});
}
}
public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
return await getter.TryGetAsync().ConfigureAwait(false);
}
public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, bool includeSuppressedDiagnostics = false, CancellationToken cancellationToken = default(CancellationToken))
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, includeSuppressedDiagnostics: includeSuppressedDiagnostics, cancellationToken: cancellationToken);
var result = await getter.TryGetAsync().ConfigureAwait(false);
Contract.Requires(result);
return getter.Diagnostics;
}
public override bool ContainsDiagnostics(Workspace workspace, ProjectId projectId)
{
// need to improve perf in v2.
foreach (var stateSet in _stateManager.GetStateSets(projectId))
{
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
var state = stateSet.GetState((StateType)stateType);
if (state.Count == 0)
{
continue;
}
if (state.GetDataCount(projectId) > 0)
{
return true;
}
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
continue;
}
foreach (var documentId in project.DocumentIds)
{
if (state.GetDataCount(documentId) > 0)
{
return true;
}
}
}
}
return false;
}
private bool ShouldRunAnalyzerForClosedFile(DiagnosticAnalyzer analyzer, CompilationOptions options, bool openedDocument)
{
// we have opened document, doesn't matter
// PERF: Don't query descriptors for compiler analyzer, always execute it.
if (openedDocument || analyzer.IsCompilerAnalyzer())
{
return true;
}
// most of analyzers, number of descriptor is quite small, so this should be cheap.
return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden);
}
private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds)
{
return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors);
}
private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId,
ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null)
{
// PERF: Don't query descriptors for compiler analyzer, always execute it for all state types.
if (analyzer.IsCompilerAnalyzer())
{
return true;
}
if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id)))
{
return false;
}
switch (stateTypeId)
{
case StateType.Syntax:
return analyzer.SupportsSyntaxDiagnosticAnalysis();
case StateType.Document:
return analyzer.SupportsSemanticDiagnosticAnalysis();
case StateType.Project:
return analyzer.SupportsProjectDiagnosticAnalysis();
default:
throw ExceptionUtilities.Unreachable;
}
}
public override void LogAnalyzerCountSummary()
{
DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator);
DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator);
// reset the log aggregator
ResetDiagnosticLogAggregator();
}
private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) &&
document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions)
{
if (existingData == null)
{
return false;
}
return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) &&
project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion);
}
private void RaiseDiagnosticsCreatedFromCacheIfNeeded(StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> items)
{
RaiseDocumentDiagnosticsUpdatedIfNeeded(type, document, stateSet, ImmutableArray<DiagnosticData>.Empty, items);
}
private void RaiseDocumentDiagnosticsUpdatedIfNeeded(
StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseDiagnosticsCreated(type, document.Id, stateSet, new SolutionArgument(document), newItems);
}
private void RaiseProjectDiagnosticsUpdatedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
var noItems = existingItems.Length == 0 && newItems.Length == 0;
if (noItems)
{
return;
}
RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems);
RaiseProjectDiagnosticsUpdated(project, stateSet, newItems);
}
private void RaiseProjectDiagnosticsRemovedIfNeeded(
Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems)
{
if (existingItems.Length == 0)
{
return;
}
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key));
foreach (var documentId in removedItems)
{
if (documentId == null)
{
RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project), raiseEvents);
continue;
}
var document = project.GetDocument(documentId);
var argument = document == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document);
RaiseDiagnosticsRemoved(StateType.Project, documentId, stateSet, argument, raiseEvents);
}
});
}
private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics)
{
Owner.RaiseBulkDiagnosticsUpdated(raiseEvents =>
{
var group = diagnostics.GroupBy(d => d.DocumentId);
foreach (var kv in group)
{
if (kv.Key == null)
{
RaiseDiagnosticsCreated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty(), raiseEvents);
continue;
}
RaiseDiagnosticsCreated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty(), raiseEvents);
}
});
}
private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId)
{
return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty;
}
private void RaiseDiagnosticsCreated(
StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics)
{
RaiseDiagnosticsCreated(type, key, stateSet, solution, diagnostics, Owner.RaiseDiagnosticsUpdated);
}
private void RaiseDiagnosticsCreated(
StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
// get right arg id for the given analyzer
var id = new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, key, (int)type, stateSet.ErrorSourceName);
raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsCreated(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics));
}
private void RaiseDiagnosticsRemoved(
StateType type, object key, StateSet stateSet, SolutionArgument solution)
{
RaiseDiagnosticsRemoved(type, key, stateSet, solution, Owner.RaiseDiagnosticsUpdated);
}
private void RaiseDiagnosticsRemoved(
StateType type, object key, StateSet stateSet, SolutionArgument solution, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
// get right arg id for the given analyzer
var id = new LiveDiagnosticUpdateArgsId(stateSet.Analyzer, key, (int)type, stateSet.ErrorSourceName);
raiseEvents(DiagnosticsUpdatedArgs.DiagnosticsRemoved(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId));
}
private void RaiseDocumentDiagnosticsRemoved(Document document, IEnumerable<StateSet> stateSets, bool includeProjectState, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
foreach (var stateSet in stateSets)
{
for (var stateType = 0; stateType < s_stateTypeCount; stateType++)
{
if (!includeProjectState && stateType == (int)StateType.Project)
{
// don't re-set project state type
continue;
}
// raise diagnostic updated event
RaiseDiagnosticsRemoved((StateType)stateType, document.Id, stateSet, new SolutionArgument(document), raiseEvents);
}
}
}
private void RaiseProjectDiagnosticsRemoved(Project project, IEnumerable<StateSet> stateSets, Action<DiagnosticsUpdatedArgs> raiseEvents)
{
foreach (var stateSet in stateSets)
{
RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project), raiseEvents);
}
}
private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics(
AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics,
SyntaxTree tree, SyntaxNode member, int memberId)
{
// get old span
var oldSpan = range[memberId];
// get old diagnostics
var diagnostics = existingData.Items;
// check quick exit cases
if (diagnostics.Length == 0 && memberDiagnostics.Length == 0)
{
return diagnostics;
}
// simple case
if (diagnostics.Length == 0 && memberDiagnostics.Length > 0)
{
return memberDiagnostics;
}
// regular case
var result = new List<DiagnosticData>();
// update member location
Contract.Requires(member.FullSpan.Start == oldSpan.Start);
var delta = member.FullSpan.End - oldSpan.End;
var replaced = false;
foreach (var diagnostic in diagnostics)
{
if (diagnostic.TextSpan.Start < oldSpan.Start)
{
result.Add(diagnostic);
continue;
}
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
if (oldSpan.End <= diagnostic.TextSpan.Start)
{
result.Add(UpdatePosition(diagnostic, tree, delta));
continue;
}
}
// if it haven't replaced, replace it now
if (!replaced)
{
result.AddRange(memberDiagnostics);
replaced = true;
}
return result.ToImmutableArray();
}
private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta)
{
Debug.Assert(diagnostic.AdditionalLocations == null || diagnostic.AdditionalLocations.Count == 0);
var newDiagnosticLocation = UpdateDiagnosticLocation(diagnostic.DataLocation, tree, delta);
return new DiagnosticData(
diagnostic.Id,
diagnostic.Category,
diagnostic.Message,
diagnostic.ENUMessageForBingSearch,
diagnostic.Severity,
diagnostic.DefaultSeverity,
diagnostic.IsEnabledByDefault,
diagnostic.WarningLevel,
diagnostic.CustomTags,
diagnostic.Properties,
diagnostic.Workspace,
diagnostic.ProjectId,
newDiagnosticLocation,
additionalLocations: diagnostic.AdditionalLocations,
description: diagnostic.Description,
helpLink: diagnostic.HelpLink,
isSuppressed: diagnostic.IsSuppressed);
}
private DiagnosticDataLocation UpdateDiagnosticLocation(
DiagnosticDataLocation dataLocation, SyntaxTree tree, int delta)
{
var span = dataLocation.SourceSpan.Value;
var start = Math.Min(Math.Max(span.Start + delta, 0), tree.Length);
var newSpan = new TextSpan(start, start >= tree.Length ? 0 : span.Length);
var mappedLineInfo = tree.GetMappedLineSpan(newSpan);
var originalLineInfo = tree.GetLineSpan(newSpan);
return new DiagnosticDataLocation(dataLocation.DocumentId, newSpan,
originalFilePath: originalLineInfo.Path,
originalStartLine: originalLineInfo.StartLinePosition.Line,
originalStartColumn: originalLineInfo.StartLinePosition.Character,
originalEndLine: originalLineInfo.EndLinePosition.Line,
originalEndColumn: originalLineInfo.EndLinePosition.Character,
mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(),
mappedStartLine: mappedLineInfo.StartLinePosition.Line,
mappedStartColumn: mappedLineInfo.StartLinePosition.Character,
mappedEndLine: mappedLineInfo.EndLinePosition.Line,
mappedEndColumn: mappedLineInfo.EndLinePosition.Character);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics)
{
return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null;
}
private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span)
{
if (diagnostic == null)
{
return false;
}
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
return false;
}
if (diagnostic.Location.SourceTree != tree)
{
return false;
}
if (span == null)
{
return true;
}
return span.Value.Contains(diagnostic.Location.SourceSpan);
}
private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics)
{
if (diagnostics == null)
{
yield break;
}
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Location == null || diagnostic.Location == Location.None)
{
yield return DiagnosticData.Create(project, diagnostic);
continue;
}
var document = project.GetDocument(diagnostic.Location.SourceTree);
if (document == null)
{
continue;
}
yield return DiagnosticData.Create(document, diagnostic);
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false);
var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer)
{
using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken))
{
try
{
Contract.ThrowIfNull(analyzer);
var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false);
return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
}
private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken)
{
var state = stateSet.GetState(type);
var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
// remove saved info
state.Remove(document.Id);
// raise diagnostic updated event
RaiseDiagnosticsRemoved(type, document.Id, stateSet, new SolutionArgument(document));
}
}
private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken)
{
var state = stateSet.GetState(StateType.Project);
var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false);
if (existingData?.Items.Length > 0)
{
// remove saved cache
state.Remove(project.Id);
// raise diagnostic updated event
RaiseDiagnosticsRemoved(StateType.Project, project.Id, stateSet, new SolutionArgument(project));
}
}
private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer)
{
return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString());
}
private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer)
{
return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString());
}
private static string GetResetLogMessage(Document document)
{
return string.Format("document reset: {0}", document.FilePath ?? document.Name);
}
private static string GetOpenLogMessage(Document document)
{
return string.Format("document open: {0}", document.FilePath ?? document.Name);
}
private static string GetRemoveLogMessage(DocumentId id)
{
return string.Format("document remove: {0}", id.ToString());
}
private static string GetRemoveLogMessage(ProjectId id)
{
return string.Format("project remove: {0}", id.ToString());
}
public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
namespace AmplifyShaderEditor
{
[Serializable]
[NodeAttributes( "Get Local Var", "Misc", "Use a registered local variable" )]
public class GetLocalVarNode : ParentNode
{
private const float NodeButtonSizeX = 16;
private const float NodeButtonSizeY = 16;
private const float NodeButtonDeltaX = 5;
private const float NodeButtonDeltaY = 11;
[SerializeField]
private int m_referenceId = -1;
[SerializeField]
private float m_referenceWidth = -1;
[SerializeField]
private int m_nodeId = -1;
[SerializeField]
private RegisterLocalVarNode m_currentSelected = null;
private bool m_forceNodeUpdate = false;
private int m_cachedPropertyId = -1;
protected override void CommonInit( int uniqueId )
{
base.CommonInit( uniqueId );
AddOutputPort( WirePortDataType.OBJECT, Constants.EmptyPortValue );
m_textLabelWidth = 80;
m_autoWrapProperties = true;
m_previewShaderGUID = "f21a6e44c7d7b8543afacd19751d24c6";
}
public override void SetPreviewInputs()
{
base.SetPreviewInputs();
if ( m_currentSelected != null )
{
if ( m_drawPreviewAsSphere != m_currentSelected.SpherePreview )
{
m_drawPreviewAsSphere = m_currentSelected.SpherePreview;
OnNodeChange();
}
//CheckSpherePreview();
if ( m_cachedPropertyId == -1 )
m_cachedPropertyId = Shader.PropertyToID( "_A" );
PreviewMaterial.SetTexture( m_cachedPropertyId, m_currentSelected.OutputPorts[ 0 ].OutputPreviewTexture );
}
}
public override void DrawProperties()
{
base.DrawProperties();
EditorGUI.BeginChangeCheck();
m_referenceId = EditorGUILayoutPopup( Constants.AvailableReferenceStr, m_referenceId, UIUtils.LocalVarNodeArr() );
if ( EditorGUI.EndChangeCheck() )
{
UpdateFromSelected();
}
}
void UpdateFromSelected()
{
m_currentSelected = UIUtils.GetLocalVarNode( m_referenceId );
if ( m_currentSelected != null )
{
m_nodeId = m_currentSelected.UniqueId;
m_outputPorts[ 0 ].ChangeType( m_currentSelected.OutputPorts[ 0 ].DataType, false );
m_drawPreviewAsSphere = m_currentSelected.SpherePreview;
CheckSpherePreview();
}
m_sizeIsDirty = true;
m_isDirty = true;
}
public override void Destroy()
{
base.Destroy();
m_currentSelected = null;
}
public override void Draw( DrawInfo drawInfo )
{
base.Draw( drawInfo );
if ( m_forceNodeUpdate )
{
m_forceNodeUpdate = false;
if ( UIUtils.CurrentShaderVersion() > 15 )
{
m_currentSelected = UIUtils.GetNode( m_nodeId ) as RegisterLocalVarNode;
m_referenceId = UIUtils.GetLocalVarNodeRegisterId( m_nodeId );
}
else
{
m_currentSelected = UIUtils.GetLocalVarNode( m_referenceId );
if ( m_currentSelected != null )
{
m_nodeId = m_currentSelected.UniqueId;
}
}
if ( m_currentSelected != null )
{
m_outputPorts[ 0 ].ChangeType( m_currentSelected.OutputPorts[ 0 ].DataType, false );
}
}
Rect rect = m_globalPosition;
rect.x = rect.x + ( NodeButtonDeltaX - 1 ) * drawInfo.InvertedZoom + 1;
rect.y = rect.y + NodeButtonDeltaY * drawInfo.InvertedZoom;
rect.width = NodeButtonSizeX * drawInfo.InvertedZoom;
rect.height = NodeButtonSizeY * drawInfo.InvertedZoom;
EditorGUI.BeginChangeCheck();
m_referenceId = EditorGUIPopup( rect, m_referenceId, UIUtils.LocalVarNodeArr() , UIUtils.PropertyPopUp );
if ( EditorGUI.EndChangeCheck() )
{
UpdateFromSelected();
}
UpdateLocalVar();
}
void UpdateLocalVar()
{
if ( m_referenceId > -1 )
{
ParentNode newNode = UIUtils.GetLocalVarNode( m_referenceId );
if ( newNode != null )
{
if ( newNode.UniqueId != m_nodeId )
{
m_currentSelected = null;
int count = UIUtils.LocalVarNodeAmount();
for ( int i = 0; i < count; i++ )
{
ParentNode node = UIUtils.GetLocalVarNode( i );
if ( node.UniqueId == m_nodeId )
{
m_currentSelected = node as RegisterLocalVarNode;
m_referenceId = i;
break;
}
}
}
}
if ( m_currentSelected != null )
{
if ( m_currentSelected.OutputPorts[ 0 ].DataType != m_outputPorts[ 0 ].DataType )
{
m_outputPorts[ 0 ].ChangeType( m_currentSelected.OutputPorts[ 0 ].DataType, false );
}
m_additionalContent.text = string.Format( Constants.PropertyValueLabel, m_currentSelected.DataToArray );
if ( m_referenceWidth != m_currentSelected.Position.width )
{
m_referenceWidth = m_currentSelected.Position.width;
m_sizeIsDirty = true;
}
}
else
{
m_nodeId = -1;
m_referenceId = -1;
m_referenceWidth = -1;
m_additionalContent.text = string.Empty;
}
}
}
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
if ( m_currentSelected != null )
{
return m_currentSelected.GenerateShaderForOutput( outputId, ref dataCollector, ignoreLocalvar );
}
else
{
Debug.LogError( "Attempting to access inexistant local variable" );
return "0";
}
}
public override void PropagateNodeData( NodeData nodeData , ref MasterNodeDataCollector dataCollector )
{
base.PropagateNodeData( nodeData, ref dataCollector );
if ( m_currentSelected != null )
{
m_currentSelected.PropagateNodeData( nodeData , ref dataCollector );
}
}
public override void ReadFromString( ref string[] nodeParams )
{
base.ReadFromString( ref nodeParams );
if ( UIUtils.CurrentShaderVersion() > 15 )
{
m_nodeId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
else
{
m_referenceId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
}
m_forceNodeUpdate = true;
}
public override void WriteToString( ref string nodeInfo, ref string connectionsInfo )
{
base.WriteToString( ref nodeInfo, ref connectionsInfo );
IOUtils.AddFieldValueToString( ref nodeInfo, ( m_currentSelected != null ? m_currentSelected.UniqueId : -1 ) );
}
public override void OnNodeDoubleClicked( Vector2 currentMousePos2D )
{
if ( m_currentSelected != null )
{
UIUtils.FocusOnNode( m_currentSelected, 0, true );
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using Netron;
using Netron.UI;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.MutableTraversals;
using QuickGraph.Representations;
using QuickGraph;
using QuickGraph.Layout.Providers;
using QuickGraph.Layout.ConnectorChoosers;
using QuickGraph.Layout.Shapes;
using QuickGraph.Layout.Connections;
using NGraphviz.Helpers;
namespace QuickGraph.Layout.Forms
{
/// <summary>
/// Summary description for QuickNetronPanel.
/// </summary>
public class QuickNetronPanel : NetronPanel
{
private IShapeVertexProvider shapeProvider = null;
private IConnectionEdgeProvider connectionProvider = null;
private IConnectorChooser connectorChooser = null;
private NetronAdaptorGraph populator = null;
private GraphvizRankDirection rankDirection = GraphvizRankDirection.TB;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public QuickNetronPanel(System.ComponentModel.IContainer container)
{
container.Add(this);
InitializeComponent();
InitializeQuickNetronPanel();
}
public QuickNetronPanel()
{
///
/// Required for Windows.Forms Class Composition Designer support
///
InitializeComponent();
InitializeQuickNetronPanel();
}
private void InitializeQuickNetronPanel()
{
this.HitEvent += new HitEventHandler(QuickNetronPanel_HitEvent);
this.EntitySelected +=new StatusEventHandler(QuickNetronPanel_SelectEvent);
this.shapeProvider= new TypeShapeVertexProvider(typeof(PropertyGridShape));
this.connectionProvider = new TypeConnectionEdgeProvider(typeof(SplineConnection));
this.connectorChooser = new MinDistanceConnectorChooser();
ZoomWheelMouseBehavior zoom = new ZoomWheelMouseBehavior();
zoom.Attach(this);
}
public IConnectorChooser ConnectorChooser
{
get
{
return this.connectorChooser;
}
set
{
this.connectorChooser = value;
if ( this.populator != null )
populator.ConnectorChooser = value;
}
}
/// <summary>
/// This property allows specification of the class when will be used to draw a Vertex
/// The Shape class must inherit from Netron.Shape
/// </summary>
public IShapeVertexProvider ShapeProvider
{
get
{
return this.shapeProvider;
}
set
{
this.shapeProvider = value;
if ( this.populator != null )
populator.ShapeProvider = value;
}
}
/// <summary>
/// This property allows specification of the class when will be used to draw an Edge
/// The Connection class must inherit from Netron.Connection
/// </summary>
public IConnectionEdgeProvider ConnectionProvider
{
get
{
return this.connectionProvider;
}
set
{
this.connectionProvider = value;
if ( this.populator != null )
populator.ConnectionProvider = value;
}
}
public NetronAdaptorGraph Populator
{
get
{
return this.populator;
}
}
public IMutableBidirectionalVertexAndEdgeListGraph Graph
{
get
{
if (this.populator==null)
return null;
else
return this.populator.VisitedGraph;
}
set
{
if (value==null)
{
this.populator = null;
return;
}
// populator
this.populator = new NetronAdaptorGraph(
value,
this,
shapeProvider,
connectionProvider,
connectorChooser
);
// attaching delegates
this.populator.ConnectEdge +=new ConnectionEdgeEventHandler(populator_ConnectEdge);
this.populator.ConnectVertex +=new ShapeVertexEventHandler(populator_ConnectVertex);
this.populator.RankDirection = this.rankDirection;
this.Invalidate();
}
}
/// <summary>
/// The direction in which to layout the graph
/// Valid values are GraphvizRankDirection.LR for left to right
/// and GraphvizRankDirection.TB for top to bottom
/// </summary>
public GraphvizRankDirection RankDirection
{
get
{
return rankDirection;
}
set
{
rankDirection = value;
if ( this.populator != null )
this.populator.RankDirection = rankDirection;
}
}
public virtual void Clear()
{
this.populator = null;
base.AbstractShape.Shapes.Clear();
base.AbstractShape.Connectors.Clear();
base.AbstractShape.Update();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// QuickNetronPanel
//
this.Click += new System.EventHandler(this.QuickNetronPanel_Click);
}
#endregion
#region Events
public event HitShapeVertexEventHandler HitVertex;
protected void OnHitVertex(Shape shape, PointF location)
{
if (HitVertex!=null)
{
IVertex v = this.populator.ShapeVertices[shape];
if (v==null)
throw new ArgumentException("shape is not part of the graph");
HitVertex(this, new HitShapeVertexEventArgs(shape,v,location));
}
}
public event HitConnectionEdgeEventHandler HitEdge;
protected void OnHitEdge(Connection conn,PointF location)
{
if (HitEdge!=null)
{
IEdge e = this.populator.ConnectionEdges[conn];
if (e==null)
throw new ArgumentException("connection is not part of the graph");
HitEdge(this, new HitConnectionEdgeEventArgs(conn,e,location));
}
}
#endregion
#region Message handler overrides
protected override void OnPaint(System.Windows.Forms.PaintEventArgs args)
{
if (this.Populator!=null)
{
if (this.Populator.GraphDirty)
{
this.Populator.PopulatePanel(args.Graphics);
this.Populator.LayoutPanel();
this.Invalidate();
}
}
Rectangle r = new Rectangle(new Point(0,0), new Size(this.Width,this.Height));
base.OnPaint(new PaintEventArgs(args.Graphics,r));
}
#endregion
private void QuickNetronPanel_Click(object sender, System.EventArgs e)
{
}
private void populator_ConnectEdge(Object sender, ConnectionEdgeEventArgs e)
{
}
private void populator_ConnectVertex(Object sender, ShapeVertexEventArgs args)
{
}
private void QuickNetronPanel_HitEvent(object sender, HitEventArgs e)
{
switch(e.HitType)
{
case EnumHitType.Connection:
if (this.populator.ContainsEdge((Connection)e.Entity))
OnHitEdge((Connection)e.Entity,e.Location);
break;
case EnumHitType.Shape:
if (this.populator.ContainsVertex((Shape)e.Entity))
OnHitVertex((Shape)e.Entity,e.Location);
break;
}
}
private void QuickNetronPanel_SelectEvent(object sender, StatusEventArgs e)
{
switch(e.Status)
{
case EnumStatusType.Deselected:
switch(e.Type)
{
case EnumEntityType.Connection:
if (this.populator.ContainsEdge((Connection)e.Entity))
this.populator.RemoveEdge((Connection)e.Entity);
break;
case EnumEntityType.Shape:
if (this.populator.ContainsVertex((Shape)e.Entity))
this.populator.RemoveVertex((Shape)e.Entity);
break;
}
break;
case EnumStatusType.Inserted:
switch(e.Type)
{
case EnumEntityType.Connection:
if (!this.populator.ContainsEdge((Connection)e.Entity))
this.populator.AddEdge((Connection)e.Entity);
break;
case EnumEntityType.Shape:
if (!this.populator.ContainsVertex((Shape)e.Entity))
this.populator.AddVertex((Shape)e.Entity);
break;
}
break;
}
}
public void MoveToFront(Shape shape)
{
Shape top = this.AbstractShape.Shapes[ this.AbstractShape.Shapes.Count - 1];
int index = this.AbstractShape.Shapes.IndexOf(shape);
this.AbstractShape.Shapes[index]=top;
this.AbstractShape.Shapes[this.AbstractShape.Shapes.Count - 1]=shape;
}
}
}
| |
using System;
using System.Configuration;
using NUnit.Framework;
using StructureMap.Pipeline;
using StructureMap.Testing.Widget;
namespace StructureMap.Testing.Configuration.DSL
{
[TestFixture]
public class AddInstanceTester
{
#region Setup/Teardown
[SetUp]
public void SetUp()
{
container = new Container(registry => {
registry.Scan(x => x.AssemblyContainingType<ColorWidget>());
// Add an instance with properties
registry.For<IWidget>()
.Add<ColorWidget>()
.Named("DarkGreen")
.Ctor<string>("color").Is("DarkGreen");
// Add an instance by specifying the ConcreteKey
registry.For<IWidget>()
.Add<ColorWidget>()
.Named("Purple")
.Ctor<string>("color").Is("Purple");
registry.For<IWidget>().Add<AWidget>();
});
}
#endregion
private IContainer container;
[Test]
public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteKey()
{
var widget = (ColorWidget) container.GetInstance<IWidget>("Purple");
Assert.AreEqual("Purple", widget.Color);
}
[Test]
public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteType()
{
var widget = (ColorWidget) container.GetInstance<IWidget>("DarkGreen");
Assert.AreEqual("DarkGreen", widget.Color);
}
[Test]
public void AddInstanceAndOverrideTheConcreteTypeForADependency()
{
IContainer container = new Container(x => {
x.For<Rule>().Add<WidgetRule>()
.Named("AWidgetRule")
.Ctor<IWidget>().IsSpecial(i => i.Type<AWidget>());
});
container.GetInstance<Rule>("AWidgetRule")
.IsType<WidgetRule>()
.Widget.IsType<AWidget>();
}
// SAMPLE: named-instance
[Test]
public void SimpleCaseWithNamedInstance()
{
container = new Container(x => { x.For<IWidget>().Add<AWidget>().Named("MyInstance"); });
// retrieve an instance by name
var widget = (AWidget) container.GetInstance<IWidget>("MyInstance");
Assert.IsNotNull(widget);
}
// ENDSAMPLE
[Test]
public void SpecifyANewInstanceOverrideADependencyWithANamedInstance()
{
container = new Container(registry => {
registry.For<Rule>().Add<ARule>().Named("Alias");
// Add an instance by specifying the ConcreteKey
registry.For<IWidget>()
.Add<ColorWidget>()
.Named("Purple")
.Ctor<string>("color").Is("Purple");
// Specify a new Instance, override a dependency with a named instance
registry.For<Rule>().Add<WidgetRule>().Named("RuleThatUsesMyInstance")
.Ctor<IWidget>("widget").IsSpecial(x => x.TheInstanceNamed("Purple"));
});
container.GetInstance<Rule>("Alias").ShouldBeOfType<ARule>();
var rule = (WidgetRule) container.GetInstance<Rule>("RuleThatUsesMyInstance");
var widget = (ColorWidget) rule.Widget;
Assert.AreEqual("Purple", widget.Color);
}
[Test]
public void SpecifyANewInstanceWithADependency()
{
// Specify a new Instance, create an instance for a dependency on the fly
var instanceKey = "OrangeWidgetRule";
var theContainer = new Container(registry => {
registry.For<Rule>().Add<WidgetRule>().Named(instanceKey)
.Ctor<IWidget>().IsSpecial(
i => { i.Type<ColorWidget>().Ctor<string>("color").Is("Orange").Named("Orange"); });
});
var rule = (WidgetRule) theContainer.GetInstance<Rule>(instanceKey);
var widget = (ColorWidget) rule.Widget;
Assert.AreEqual("Orange", widget.Color);
}
[Test]
public void UseAPreBuiltObjectWithAName()
{
// Return the specific instance when an IWidget named "Julia" is requested
var julia = new CloneableWidget("Julia");
container =
new Container(x => x.For<IWidget>().Add(julia).Named("Julia"));
var widget1 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
var widget2 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
var widget3 = (CloneableWidget) container.GetInstance<IWidget>("Julia");
Assert.AreSame(julia, widget1);
Assert.AreSame(julia, widget2);
Assert.AreSame(julia, widget3);
}
}
public class WidgetRule : Rule
{
private readonly IWidget _widget;
public WidgetRule(IWidget widget)
{
_widget = widget;
}
public IWidget Widget
{
get { return _widget; }
}
public override bool Equals(object obj)
{
if (this == obj) return true;
var widgetRule = obj as WidgetRule;
if (widgetRule == null) return false;
return Equals(_widget, widgetRule._widget);
}
public override int GetHashCode()
{
return _widget != null ? _widget.GetHashCode() : 0;
}
}
public class WidgetThing : IWidget
{
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
[Serializable]
public class CloneableWidget : IWidget, ICloneable
{
private readonly string _name;
public CloneableWidget(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
}
#region ICloneable Members
public object Clone()
{
return MemberwiseClone();
}
#endregion
#region IWidget Members
public void DoSomething()
{
throw new NotImplementedException();
}
#endregion
}
public class ARule : Rule
{
}
}
| |
// -----
// GNU General Public License
// The Forex Professional Analyzer 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 3 of the License, or (at your option) any later version.
// The Forex Professional Analyzer 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.
// -----
using System;
using System.Collections.Generic;
using System.Text;
namespace fxpa
{
public class RemoteDataProvider : IDataProvider
{
volatile protected OperationalStateEnum _operationalState = OperationalStateEnum.UnInitialized;
public OperationalStateEnum OperationalState
{
get { return _operationalState; }
}
string name;
public string Name
{
get { return name; }
set { name = value; }
}
/// <summary>
/// LiveDataProvider does not support time control.
/// </summary>
public virtual ITimeControl TimeControl
{
get { return null; }
}
public virtual DateTime FirstBarDateTime
{
get
{
lock (this)
{
if (_dataUnits.Count > 0)
{
return _dataUnits[0].DateTime;
}
return DateTime.MaxValue;
}
}
}
public virtual DateTime LastBarDateTime
{
get
{
lock (this)
{
if (_dataUnits.Count > 0)
{
return _dataUnits[_dataUnits.Count - 1].DateTime;
}
return DateTime.MaxValue;
}
}
}
public virtual int DataUnitCount
{
get { lock (this) { return _dataUnits.Count; } }
}
/// <summary>
/// Used when a matching of a given time to a bar data is needed.
/// Matches a time to an index of bar data on this time.
/// </summary>
Dictionary<DateTime, int> _cachedIndexSearches = new Dictionary<DateTime, int>();
protected List<BarData> _dataUnits = new List<BarData>();
public virtual IList<BarData> DataUnits
{
get
{
lock (this) { return _dataUnits; }
}
}
protected double _ask = double.NaN;
public virtual double Ask
{
get
{
lock (this)
{
//SystemMonitor.CheckWarning(double.IsNaN(_ask) == false);
return _ask;
}
}
}
protected double _bid = double.NaN;
public virtual double Bid
{
get
{
lock (this)
{
//SystemMonitor.CheckWarning(double.IsNaN(_bid) == false);
return _bid;
}
}
}
public virtual double Spread
{
get { lock (this) { return Math.Abs(Ask - Bid); } }
}
public event ValuesUpdatedDelegate ValuesUpdateEvent;
/// <summary>
/// The date time of the platform serving this data provider.
/// </summary>
public virtual DateTime CurrentSourceDateTime
{
get
{
lock (this)
{
if (CurrentDataUnit.HasValue)
{
return CurrentDataUnit.Value.DateTime;
}
return DateTime.MinValue;
}
}
}
public virtual BarData ?CurrentDataUnit
{
get
{
lock (this)
{
if (DataUnitCount == 0)
{
return null;
}
return this.DataUnits[DataUnitCount - 1];
}
}
}
public virtual TimeSpan TimeInterval
{
get { return _sessionInfo.TimeInterval; }
}
protected DateTime _lastUpdateDateTime = DateTime.MinValue;
//List<ArbiterClientId?> _forwardTransportation;
protected SessionInfo _sessionInfo;
//public event GeneralHelper.GenericDelegate<IOperational> OperationalStatusChangedEvent;
//private bool _singleThreadOnly;
TimeSpan _defaultTimeOut = TimeSpan.Zero;
protected TimeSpan DefaultTimeOut
{
get { return _defaultTimeOut; }
set { _defaultTimeOut = value; }
}
/// <summary>
/// Constructor.
/// </summary>
public RemoteDataProvider()
//: base("RemoteDataProvider", false)
{
name = "RemoteDataProvider";
//_singleThreadOnly = false;
DefaultTimeOut = TimeSpan.FromSeconds(15);
}
//public bool Initialize(SessionInfo sessionInfo, List<ArbiterClientId?> forwardTransportation)
//{
// lock (this)
// {
// this.Name = "DataProvider of" + sessionInfo.Id;
// //_forwardTransportation = forwardTransportation;
// //_sessionInfo = sessionInfo;
// //// Subscribe to source here.
// //ResultTransportMessage result = SendAndReceiveForwarding<ResultTransportMessage>(_forwardTransportation,
// // new SubscribeToSessionMessage(_sessionInfo));
// //if (result != null && result.OperationResult)
// //{
// // _operationalState = OperationalStateEnum.Initialized;
// //}
// }
// //GeneralHelper.SafeEventRaise(OperationalStatusChangedEvent, this);
// return OperationalState == OperationalStateEnum.Initialized;
//}
bool _requestConfirmtion = true;
public bool RequestConfirmation
{
get { return _requestConfirmtion; }
set { _requestConfirmtion = value; }
}
public virtual void UnInitialize()
{
if (_operationalState == OperationalStateEnum.Initialized ||
_operationalState == OperationalStateEnum.Operational)
{
//UnSubscribeToSessionMessage message = new UnSubscribeToSessionMessage(_sessionInfo);
RequestConfirmation = false;
// UnSubscribe to source here.
//SendForwarding(_forwardTransportation, message);
}
_operationalState = OperationalStateEnum.UnInitialized;
//GeneralHelper.SafeEventRaise(OperationalStatusChangedEvent, this);
}
/// <summary>
///
/// </summary>
/// <param name="updateType"></param>
/// <param name="updatedItemsCount"></param>
/// <param name="isMultiStepMode">Multi step mode occurs when many steps are done one after the other, fast. Usefull for UI not to update itself.</param>
protected void RaiseValuesUpdateEvent(UpdateType updateType, int updatedItemsCount, int stepsRemaining)
{
if (ValuesUpdateEvent != null)
{
//HERRYConsole.WriteLine(" RaiseValuesUpdateEvent updatedItemsCount !!!!!!!!!!!!!!!!!!!!!! " + updatedItemsCount);
ValuesUpdateEvent(this, updateType, updatedItemsCount, stepsRemaining);
//GeneralHelper.FireAndForget(ValuesUpdateEvent, this, updateType, updatedItemsCount, stepsRemaining);
}
}
/// <summary>
/// Helper.
/// </summary>
//public void RequestValuesUpdate()
//{
// TracerHelper.Trace(this.Name);
// RequestValuesMessage message = new RequestValuesMessage(_sessionInfo);
// TradingValuesUpdateMessage resultMessage =
// SendAndReceiveForwarding<TradingValuesUpdateMessage>(_forwardTransportation, message);
// if (resultMessage != null && resultMessage.OperationResult)
// {
// Receive(resultMessage);
// }
//}
/// <summary>
/// Helper.
/// </summary>
protected void RaiseOperationalStatusChangedEvent()
{
// TracerHelper.Trace(this.Name + " " + this._operationalState.ToString());
//OperationalStatusChangedEvent(this);
}
/// <summary>
/// Deltas will return a line indicating the difference of the current bar to the previous one.
/// This is the same as the MOMENTUM indicator.
/// </summary>
public double[] GetDataValuesDeltas(BarData.DataValueSourceEnum valueEnum)
{
return GetDataValuesDeltas(0, _dataUnits.Count, valueEnum);
}
/// <summary>
/// A delta - the value from the previous to the current tick.
/// This is the same as the MOMENTUM indicator.
/// </summary>
public double[] GetDataValuesDeltas(int startingIndex, int indecesLimit, BarData.DataValueSourceEnum valueEnum)
{
double[] values = GetDataValues(valueEnum, startingIndex, indecesLimit);
for (int i = values.Length - 1; i > 0 ; i--)
{
values[i] = values[i] - values[i - 1];
}
if (values.Length > 0)
{
values[0] = 0;
}
return values;
}
/// <summary>
///
/// </summary>
public double[] GetDataValues(BarData.DataValueSourceEnum valueEnum)
{
return GetDataValues(valueEnum, 0, _dataUnits.Count);
}
/// <summary>
///
/// </summary>
public double[] GetDataValues(BarData.DataValueSourceEnum valueEnum, int startingIndex, int indexCount)
{
int count = indexCount;
if (count == 0)
{
count = _dataUnits.Count - startingIndex;
GeneralHelper.Verify(count >= 0, "Invalid starting index.");
}
double[] result = new double[count];
lock (this)
{
for (int i = startingIndex; i < startingIndex + count; i++)
{
result[i - startingIndex] = _dataUnits[i].GetValue(valueEnum);
}
}
return result;
}
/// <summary>
/// Also time gaps must be considered.
/// Result is -1 to indicate not found.
/// Since this method is called very extensively on drawing, it employes a caching mechanism.
/// </summary>
public int GetBarIndexAtTime(DateTime time)
{
lock (this)
{
if (_dataUnits.Count == 0)
{
return 0;
}
if (_cachedIndexSearches.ContainsKey(time))
{
return _cachedIndexSearches[time];
}
TimeSpan difference = (time - _dataUnits[0].DateTime);
if (difference.TotalSeconds < 0)
{// Before time.
return -1;
} else if (difference.TotalSeconds <= _sessionInfo.TimeInterval.TotalSeconds)
{// 0 index.
_cachedIndexSearches.Add(time, 0);
return 0;
}
// Estimated index has skipped time gaps. so now start looking back from it to find the proper period.
int estimatedIndex = 1 + (int)Math.Floor(difference.TotalSeconds / _sessionInfo.TimeInterval.TotalSeconds);
estimatedIndex = Math.Min(_dataUnits.Count - 1, estimatedIndex);
for (int i = estimatedIndex; i >= 1; i--)
{
if (_dataUnits[i - 1].DateTime <= time
&& _dataUnits[i].DateTime >= time)
{
_cachedIndexSearches.Add(time, i);
return i;
}
}
}
return -1;
}
}
}
| |
/*
* 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 log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Connectors.Friends;
using System;
using System.Collections.Generic;
using System.Reflection;
using FriendInfo = OpenSim.Services.Interfaces.FriendInfo;
namespace OpenSim.Services.Connectors.Hypergrid
{
public class HGFriendsServicesConnector : FriendsSimConnector
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_ServerURI = String.Empty;
private string m_ServiceKey = String.Empty;
private UUID m_SessionID;
public HGFriendsServicesConnector()
{
}
public HGFriendsServicesConnector(string serverURI)
{
m_ServerURI = serverURI.TrimEnd('/');
}
public HGFriendsServicesConnector(string serverURI, UUID sessionID, string serviceKey)
{
m_ServerURI = serverURI.TrimEnd('/');
m_ServiceKey = serviceKey;
m_SessionID = sessionID;
}
protected override string ServicePath()
{
return "hgfriends";
}
#region IFriendsService
public bool DeleteFriendship(UUID PrincipalID, UUID Friend, string secret)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = PrincipalID;
finfo.Friend = Friend.ToString();
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "deletefriendship";
sendData["SECRET"] = secret;
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("RESULT"))
{
if (replyData["RESULT"].ToString().ToLower() == "true")
return true;
else
return false;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: reply data does not contain result field");
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: received empty reply");
return false;
}
public uint GetFriendPerms(UUID PrincipalID, UUID friendID)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
sendData["PRINCIPALID"] = PrincipalID.ToString();
sendData["FRIENDID"] = friendID.ToString();
sendData["METHOD"] = "getfriendperms";
sendData["KEY"] = m_ServiceKey;
sendData["SESSIONID"] = m_SessionID.ToString();
string reqString = ServerUtils.BuildQueryString(sendData);
string uri = m_ServerURI + "/hgfriends";
try
{
string reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
reqString);
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("Value") && (replyData["Value"] != null))
{
uint perms = 0;
uint.TryParse(replyData["Value"].ToString(), out perms);
return perms;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: GetFriendPerms {0} received null response",
PrincipalID);
}
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
}
return 0;
}
public bool NewFriendship(UUID PrincipalID, string Friend)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = PrincipalID;
finfo.Friend = Friend;
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "newfriendship";
sendData["KEY"] = m_ServiceKey;
sendData["SESSIONID"] = m_SessionID.ToString();
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if ((replyData != null) && replyData.ContainsKey("Result") && (replyData["Result"] != null))
{
bool success = false;
Boolean.TryParse(replyData["Result"].ToString(), out success);
return success;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: StoreFriend {0} {1} received null response",
PrincipalID, Friend);
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: StoreFriend received null reply");
return false;
}
public List<UUID> StatusNotification(List<string> friends, UUID userID, bool online)
{
Dictionary<string, object> sendData = new Dictionary<string, object>();
List<UUID> friendsOnline = new List<UUID>();
sendData["METHOD"] = "statusnotification";
sendData["userID"] = userID.ToString();
sendData["online"] = online.ToString();
int i = 0;
foreach (string s in friends)
{
sendData["friend_" + i.ToString()] = s;
i++;
}
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData), 15);
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return friendsOnline;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
// Here is the actual response
foreach (string key in replyData.Keys)
{
if (key.StartsWith("friend_") && replyData[key] != null)
{
UUID uuid;
if (UUID.TryParse(replyData[key].ToString(), out uuid))
friendsOnline.Add(uuid);
}
}
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Received empty reply from remote StatusNotify");
return friendsOnline;
}
public bool ValidateFriendshipOffered(UUID fromID, UUID toID)
{
FriendInfo finfo = new FriendInfo();
finfo.PrincipalID = fromID;
finfo.Friend = toID.ToString();
Dictionary<string, object> sendData = finfo.ToKeyValuePairs();
sendData["METHOD"] = "validate_friendship_offered";
string reply = string.Empty;
string uri = m_ServerURI + "/hgfriends";
try
{
reply = SynchronousRestFormsRequester.MakeRequest("POST",
uri,
ServerUtils.BuildQueryString(sendData));
}
catch (Exception e)
{
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: Exception when contacting friends server at {0}: {1}", uri, e.Message);
return false;
}
if (reply != string.Empty)
{
Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply);
if (replyData.ContainsKey("RESULT"))
{
if (replyData["RESULT"].ToString().ToLower() == "true")
return true;
else
return false;
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: reply data does not contain result field");
}
else
m_log.DebugFormat("[HGFRIENDS CONNECTOR]: received empty reply");
return false;
}
#endregion IFriendsService
}
}
| |
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 Bog.Web.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;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using CSJ2K;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Services.Interfaces;
namespace Aurora.Modules.WorldMap.Warp3DMap
{
public static class TerrainSplat
{
#region Constants
private static readonly UUID DIRT_DETAIL = new UUID("0bc58228-74a0-7e83-89bc-5c23464bcec5");
private static readonly UUID GRASS_DETAIL = new UUID("63338ede-0037-c4fd-855b-015d77112fc8");
private static readonly UUID MOUNTAIN_DETAIL = new UUID("303cd381-8560-7579-23f1-f0a880799740");
private static readonly UUID ROCK_DETAIL = new UUID("53a2f406-4895-1d13-d541-d2e3b86bc19c");
private static readonly UUID[] DEFAULT_TERRAIN_DETAIL = new[]
{
DIRT_DETAIL,
GRASS_DETAIL,
MOUNTAIN_DETAIL,
ROCK_DETAIL
};
private static readonly Color[] DEFAULT_TERRAIN_COLOR = new[]
{
Color.FromArgb(255, 164, 136, 117),
Color.FromArgb(255, 65, 87, 47),
Color.FromArgb(255, 157, 145, 131),
Color.FromArgb(255, 125, 128, 130)
};
private static readonly UUID TERRAIN_CACHE_MAGIC = new UUID("2c0c7ef2-56be-4eb8-aacb-76712c535b4b");
#endregion Constants
/// <summary>
/// Builds a composited terrain texture given the region texture
/// and heightmap settings
/// </summary>
/// <param name = "heightmap">Terrain heightmap</param>
/// <param name = "regionInfo">Region information including terrain texture parameters</param>
/// <returns>A composited 256x256 RGB texture ready for rendering</returns>
/// <remarks>
/// Based on the algorithm described at http://opensimulator.org/wiki/Terrain_Splatting
/// </remarks>
public static Bitmap Splat(ITerrainChannel heightmap, UUID[] textureIDs, float[] startHeights,
float[] heightRanges, Vector3d regionPosition, IAssetService assetService,
bool textureTerrain, RegionInfo region)
{
Debug.Assert(textureIDs.Length == 4);
Debug.Assert(startHeights.Length == 4);
Debug.Assert(heightRanges.Length == 4);
Bitmap[] detailTexture = new Bitmap[4];
if (textureTerrain)
{
// Swap empty terrain textureIDs with default IDs
for (int i = 0; i < textureIDs.Length; i++)
{
if (textureIDs[i] == UUID.Zero)
textureIDs[i] = DEFAULT_TERRAIN_DETAIL[i];
}
#region Texture Fetching
if (assetService != null)
{
for (int i = 0; i < 4; i++)
{
UUID cacheID = UUID.Combine(TERRAIN_CACHE_MAGIC, textureIDs[i]);
AssetBase asset = assetService.GetCached(cacheID.ToString());
if ((asset != null) && (asset.Data != null) && (asset.Data.Length != 0))
{
try
{
using (MemoryStream stream = new MemoryStream(asset.Data))
detailTexture[i] = (Bitmap) Image.FromStream(stream);
}
catch (Exception ex)
{
MainConsole.Instance.Warn("Failed to decode cached terrain texture " + cacheID +
" (textureID: " + textureIDs[i] + "): " + ex.Message);
}
}
if (detailTexture[i] == null)
{
// Try to fetch the original JPEG2000 texture, resize if needed, and cache as PNG
asset = assetService.Get(textureIDs[i].ToString());
if (asset != null)
{
try
{
detailTexture[i] = (Bitmap) J2kImage.FromBytes(asset.Data);
}
catch (Exception ex)
{
MainConsole.Instance.Warn("Failed to decode terrain texture " + asset.ID + ": " + ex.Message);
}
}
if (detailTexture[i] != null)
{
Bitmap bitmap = detailTexture[i];
// Make sure this texture is the correct size, otherwise resize
if (bitmap.Width != region.RegionSizeX || bitmap.Height != region.RegionSizeY)
bitmap = ImageUtils.ResizeImage(bitmap, region.RegionSizeX, region.RegionSizeY);
// Save the decoded and resized texture to the cache
byte[] data;
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
data = stream.ToArray();
}
// Cache a PNG copy of this terrain texture
AssetBase newAsset = new AssetBase
{
Data = data,
Description = "PNG",
Flags =
AssetFlags.Collectable | AssetFlags.Temporary |
AssetFlags.Local,
ID = cacheID,
Name = String.Empty,
TypeString = "image/png"
};
newAsset.FillHash();
newAsset.ID = assetService.Store(newAsset);
}
}
}
}
#endregion Texture Fetching
}
// Fill in any missing textures with a solid color
for (int i = 0; i < 4; i++)
{
if (detailTexture[i] == null)
{
// Create a solid color texture for this layer
detailTexture[i] = new Bitmap(region.RegionSizeX, region.RegionSizeY, PixelFormat.Format24bppRgb);
using (Graphics gfx = Graphics.FromImage(detailTexture[i]))
{
using (SolidBrush brush = new SolidBrush(DEFAULT_TERRAIN_COLOR[i]))
gfx.FillRectangle(brush, 0, 0, region.RegionSizeX, region.RegionSizeY);
}
}
else if (detailTexture[i].Width != region.RegionSizeX || detailTexture[i].Height != region.RegionSizeY)
{
detailTexture[i] = FixVariableSizedRegionTerrainSize(region, detailTexture[i]);
}
}
#region Layer Map
float[] layermap = new float[region.RegionSizeX * region.RegionSizeY];
for (float y = 0; y < heightmap.Height; y++)
{
for (float x = 0; x < heightmap.Height; x++)
{
float height = heightmap[(int)x, (int)y];
// Use bilinear interpolation between the four corners of start height and
// height range to select the current values at this position
float startHeight = ImageUtils.Bilinear(
startHeights[0],
startHeights[2],
startHeights[1],
startHeights[3],
x, y);
startHeight = Utils.Clamp(startHeight, 0f, 255f);
float heightRange = ImageUtils.Bilinear(
heightRanges[0],
heightRanges[2],
heightRanges[1],
heightRanges[3],
x, y);
heightRange = Utils.Clamp(heightRange, 0f, 255f);
// Generate two frequencies of perlin noise based on our global position
// The magic values were taken from http://opensimulator.org/wiki/Terrain_Splatting
Vector3 vec = new Vector3
(
((float) regionPosition.X + x)*0.20319f,
((float) regionPosition.Y + y)*0.20319f,
height*0.25f
);
float lowFreq = Perlin.noise2(vec.X*0.222222f, vec.Y*0.222222f)*6.5f;
float highFreq = Perlin.turbulence2(vec.X, vec.Y, 2f)*2.25f;
float noise = (lowFreq + highFreq)*2f;
// Combine the current height, generated noise, start height, and height range parameters, then scale all of it
float layer = ((height + noise - startHeight)/heightRange)*4f;
if (Single.IsNaN(layer))
layer = 0f;
layermap[(int)(y * heightmap.Width + x)] = Utils.Clamp(layer, 0f, 3f);
}
}
#endregion Layer Map
#region Texture Compositing
Bitmap output = new Bitmap(region.RegionSizeX, region.RegionSizeY, PixelFormat.Format24bppRgb);
BitmapData outputData = output.LockBits(new Rectangle(0, 0, region.RegionSizeX, region.RegionSizeY), ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
unsafe
{
// Get handles to all of the texture data arrays
BitmapData[] datas = new[]
{
detailTexture[0].LockBits(new Rectangle(0, 0, region.RegionSizeX, region.RegionSizeY),
ImageLockMode.ReadOnly,
detailTexture[0].PixelFormat),
detailTexture[1].LockBits(new Rectangle(0, 0, region.RegionSizeX, region.RegionSizeY),
ImageLockMode.ReadOnly,
detailTexture[1].PixelFormat),
detailTexture[2].LockBits(new Rectangle(0, 0, region.RegionSizeX, region.RegionSizeY),
ImageLockMode.ReadOnly,
detailTexture[2].PixelFormat),
detailTexture[3].LockBits(new Rectangle(0, 0, region.RegionSizeX, region.RegionSizeY),
ImageLockMode.ReadOnly,
detailTexture[3].PixelFormat)
};
int[] comps = new[]
{
(datas[0].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
(datas[1].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
(datas[2].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3,
(datas[3].PixelFormat == PixelFormat.Format32bppArgb) ? 4 : 3
};
for (int y = 0; y < region.RegionSizeY; y++)
{
for (int x = 0; x < region.RegionSizeX; x++)
{
float layer = layermap[y*heightmap.Width + x];
// Select two textures
int l0 = (int) Math.Floor(layer);
int l1 = Math.Min(l0 + 1, 3);
byte* ptrA = (byte*) datas[l0].Scan0 + y*datas[l0].Stride + x*comps[l0];
byte* ptrB = (byte*) datas[l1].Scan0 + y*datas[l1].Stride + x*comps[l1];
byte* ptrO = (byte*) outputData.Scan0 + y*outputData.Stride + x*3;
float aB = *(ptrA + 0);
float aG = *(ptrA + 1);
float aR = *(ptrA + 2);
float bB = *(ptrB + 0);
float bG = *(ptrB + 1);
float bR = *(ptrB + 2);
float layerDiff = layer - l0;
// Interpolate between the two selected textures
*(ptrO + 0) = (byte) Math.Floor(aB + layerDiff*(bB - aB));
*(ptrO + 1) = (byte) Math.Floor(aG + layerDiff*(bG - aG));
*(ptrO + 2) = (byte) Math.Floor(aR + layerDiff*(bR - aR));
}
}
for (int i = 0; i < 4; i++)
{
detailTexture[i].UnlockBits(datas[i]);
detailTexture[i].Dispose();
}
}
layermap = null;
output.UnlockBits(outputData);
// We generated the texture upside down, so flip it
output.RotateFlip(RotateFlipType.RotateNoneFlipY);
#endregion Texture Compositing
return output;
}
private static Bitmap FixVariableSizedRegionTerrainSize(RegionInfo region, Bitmap image)
{
if (region.RegionSizeX == image.Width && region.RegionSizeY == image.Height)
return image;
Bitmap destImage = new Bitmap(region.RegionSizeX, region.RegionSizeY);
using(TextureBrush brush = new TextureBrush(new Bitmap(image), System.Drawing.Drawing2D.WrapMode.Tile))
using (Graphics g = Graphics.FromImage(destImage))
{
// do your painting in here
g.FillRectangle(brush, 0, 0, destImage.Width, destImage.Height);
}
image.Dispose();
return destImage;
}
public static Bitmap ResizeBitmap(Bitmap b, int nWidth, int nHeight)
{
Bitmap result = new Bitmap(nWidth, nHeight);
using (Graphics g = Graphics.FromImage(result))
g.DrawImage(b, 0, 0, nWidth, nHeight);
b.Dispose();
return result;
}
public static Bitmap SplatSimple(ITerrainChannel heightmap)
{
const float BASE_HSV_H = 93f/360f;
const float BASE_HSV_S = 44f/100f;
const float BASE_HSV_V = 34f/100f;
Bitmap img = new Bitmap(256, 256);
BitmapData bitmapData = img.LockBits(new Rectangle(0, 0, 256, 256), ImageLockMode.WriteOnly,
PixelFormat.Format24bppRgb);
unsafe
{
for (int y = 255; y >= 0; y--)
{
for (int x = 0; x < 256; x++)
{
float normHeight = heightmap[x, y]/255f;
normHeight = Utils.Clamp(normHeight, BASE_HSV_V, 1.0f);
Color4 color = Color4.FromHSV(BASE_HSV_H, BASE_HSV_S, normHeight);
byte* ptr = (byte*) bitmapData.Scan0 + y*bitmapData.Stride + x*3;
*(ptr + 0) = (byte) (color.B*255f);
*(ptr + 1) = (byte) (color.G*255f);
*(ptr + 2) = (byte) (color.R*255f);
}
}
}
img.UnlockBits(bitmapData);
return img;
}
}
}
| |
#region BSD License
/*
Copyright (c) 2010, NETFx
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 Clarius Consulting nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using Microsoft.CSharp.RuntimeBinder;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
namespace System.Dynamic
{
/// <summary>
/// Provides reflection-based dynamic syntax for objects and types.
/// This class provides the extension methods <see cref="AsDynamicReflection(object)"/>
/// and <see cref="AsDynamicReflection(Type)"/> as entry points.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
static partial class DynamicReflection
{
/// <summary>
/// Provides dynamic syntax for accessing the given object members.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="obj" this="true">The object to access dinamically</param>
public static dynamic AsDynamicReflection(this object obj)
{
if (obj == null)
return null;
return new DynamicReflectionObject(obj);
}
/// <summary>
/// Provides dynamic syntax for accessing the given type members.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="type" this="true">The type to access dinamically</param>
public static dynamic AsDynamicReflection(this Type type)
{
if (type == null)
return null;
return new DynamicReflectionObject(type);
}
/// <summary>
/// Converts the type to a <see cref="TypeParameter"/> that
/// the reflection dynamic must use to make a generic
/// method invocation.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="type" this="true">The type to convert</param>
public static TypeParameter AsGenericTypeParameter(this Type type)
{
return new TypeParameter(type);
}
private class DynamicReflectionObject : DynamicObject
{
private static readonly BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
private static readonly MethodInfo castMethod = typeof(DynamicReflectionObject).GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
private object target;
private Type targetType;
public DynamicReflectionObject(object target)
{
this.target = target;
this.targetType = target.GetType();
}
public DynamicReflectionObject(Type type)
{
this.target = null;
this.targetType = type;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (!base.TryInvokeMember(binder, args, out result))
{
var memberName = (binder.Name == "ctor" || binder.Name == "cctor") ? "." + binder.Name : binder.Name;
var method = FindBestMatch(binder, memberName, args);
if (method != null)
{
if (binder.Name == "ctor")
{
var instance = this.target;
if (instance == null)
instance = FormatterServices.GetSafeUninitializedObject(this.targetType);
result = Invoke(method, instance, args);
result = instance.AsDynamicReflection();
}
else
{
result = AsDynamicIfNecessary(Invoke(method, this.target, args));
}
return true;
}
}
result = default(object);
return false;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!base.TryGetMember(binder, out result))
{
var field = targetType.GetField(binder.Name, flags);
var baseType = targetType.BaseType;
while (field == null && baseType != null)
{
field = baseType.GetField(binder.Name, flags);
baseType = baseType.BaseType;
}
if (field != null)
{
result = AsDynamicIfNecessary(field.GetValue(target));
return true;
}
var getter = FindBestMatch(binder, "get_" + binder.Name, new object[0]);
if (getter != null)
{
result = AsDynamicIfNecessary(getter.Invoke(this.target, null));
return true;
}
}
// \o/ If nothing else works, and the member is "target", return our target.
if (binder.Name == "target")
{
result = this.target;
return true;
}
result = default(object);
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!base.TrySetMember(binder, value))
{
var field = targetType.GetField(binder.Name, flags);
var baseType = targetType.BaseType;
while (field == null && baseType != null)
{
field = baseType.GetField(binder.Name, flags);
baseType = baseType.BaseType;
}
if (field != null)
{
field.SetValue(target, value);
return true;
}
var setter = FindBestMatch(binder, "set_" + binder.Name, new[] { value });
if (setter != null)
{
setter.Invoke(this.target, new[] { value });
return true;
}
}
return false;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (!base.TryGetIndex(binder, indexes, out result))
{
var indexer = FindBestMatch(binder, "get_Item", indexes);
if (indexer != null)
{
result = AsDynamicIfNecessary(indexer.Invoke(this.target, indexes));
return true;
}
}
result = default(object);
return false;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (!base.TrySetIndex(binder, indexes, value))
{
var args = indexes.Concat(new[] { value }).ToArray();
var indexer = FindBestMatch(binder, "set_Item", args);
if (indexer != null)
{
indexer.Invoke(this.target, args);
return true;
}
}
return false;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
try
{
result = castMethod.MakeGenericMethod(binder.Type).Invoke(null, new[] { this.target });
return true;
}
catch (Exception) { }
var convertible = this.target as IConvertible;
if (convertible != null)
{
try
{
result = Convert.ChangeType(convertible, binder.Type);
return true;
}
catch (Exception) { }
}
result = default(object);
return false;
}
private static object Invoke(IInvocable method, object instance, object[] args)
{
var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray();
var refArgs = new Dictionary<int, RefValue>();
var outArgs = new Dictionary<int, OutValue>();
for (int i = 0; i < method.Parameters.Count; i++)
{
if (method.Parameters[i].ParameterType.IsByRef)
{
var refArg = finalArgs[i] as RefValue;
var outArg = finalArgs[i] as OutValue;
if (refArg != null)
refArgs[i] = refArg;
else if (outArg != null)
outArgs[i] = outArg;
}
}
foreach (var refArg in refArgs)
{
finalArgs[refArg.Key] = refArg.Value.Value;
}
foreach (var outArg in outArgs)
{
finalArgs[outArg.Key] = null;
}
var result = method.Invoke(instance, finalArgs);
foreach (var refArg in refArgs)
{
refArg.Value.Value = finalArgs[refArg.Key];
}
foreach (var outArg in outArgs)
{
outArg.Value.Value = finalArgs[outArg.Key];
}
return result;
}
/// <summary>
/// Converts dynamic objects to object, which may cause unboxing
/// of the wrapped dynamic such as in our own DynamicReflectionObject type.
/// </summary>
private static object UnboxDynamic(object maybeDynamic)
{
var dyn = maybeDynamic as DynamicObject;
if (dyn == null)
return maybeDynamic;
var binder = (ConvertBinder)Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(object), typeof(DynamicReflectionObject));
//var site = CallSite<Func<CallSite, object, object>>.Create(binder);
object result;
dyn.TryConvert(binder, out result);
return result;
}
private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, string memberName, object[] args)
{
var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray();
var genericTypeArgs = new List<Type>();
if (binder is InvokeBinder || binder is InvokeMemberBinder)
{
IEnumerable typeArgs = binder.AsDynamicReflection().TypeArguments;
genericTypeArgs.AddRange(typeArgs.Cast<Type>());
genericTypeArgs.AddRange(args.OfType<TypeParameter>().Select(x => x.Type));
}
var method = FindBestMatch(binder, finalArgs, genericTypeArgs.Count, this.targetType
.GetMethods(flags)
.Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length)
.Select(x => new MethodInvocable(x)));
if (method == null)
{
// Fallback to explicitly implemented members.
method = FindBestMatch(binder, finalArgs, genericTypeArgs.Count, this.targetType
.GetInterfaces()
.SelectMany(
iface => this.targetType
.GetInterfaceMap(iface)
.TargetMethods.Select(x => new { Interface = iface, Method = x }))
.Where(x =>
x.Method.GetParameters().Length == finalArgs.Length &&
x.Method.Name.Replace(x.Interface.FullName.Replace('+', '.') + ".", "") == memberName)
.Select(x => (IInvocable)new MethodInvocable(x.Method))
.Concat(this.targetType.GetConstructors(flags)
.Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length)
.Select(x => new ConstructorInvocable(x)))
.Distinct());
}
var methodInvocable = method as MethodInvocable;
if (method != null && methodInvocable != null && methodInvocable.Method.IsGenericMethodDefinition)
{
method = new MethodInvocable(methodInvocable.Method.MakeGenericMethod(genericTypeArgs.ToArray()));
}
return method;
}
private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, object[] args, int genericArgs, IEnumerable<IInvocable> candidates)
{
var result = FindBestMatchImpl(binder, args, genericArgs, candidates, false);
if (result == null)
result = FindBestMatchImpl(binder, args, genericArgs, candidates, true);
return result;
}
/// <summary>
/// Finds the best match among the candidates.
/// </summary>
/// <param name="binder">The binder that is requesting the match.</param>
/// <param name="args">The args passed in to the invocation.</param>
/// <param name="genericArgs">The generic args if any.</param>
/// <param name="candidates">The candidate methods to use for the match..</param>
/// <param name="assignableFrom">if set to <c>true</c>, uses a more lax matching approach for arguments, with IsAssignableFrom instead of == for arg type.</param>
private IInvocable FindBestMatchImpl(DynamicMetaObjectBinder binder, object[] args, int genericArgs, IEnumerable<IInvocable> candidates, bool assignableFrom)
{
dynamic dynamicBinder = binder.AsDynamicReflection();
for (int i = 0; i < args.Length; i++)
{
var index = i;
if (args[index] != null)
{
if (assignableFrom)
candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsAssignableFrom(GetArgumentType(args[index])));
else
candidates = candidates.Where(x => x.Parameters[index].ParameterType == GetArgumentType(args[index]));
}
IEnumerable enumerable = dynamicBinder.ArgumentInfo;
// The binder has the extra argument info for the "this" parameter at the beginning.
if (enumerable.Cast<object>().ToList()[index + 1].AsDynamicReflection().IsByRef)
candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsByRef);
if (genericArgs > 0)
candidates = candidates.Where(x => x.IsGeneric && x.GenericParameters == genericArgs);
}
return candidates.FirstOrDefault();
}
private static Type GetArgumentType(object arg)
{
if (arg is RefValue || arg is OutValue)
return arg.GetType().GetGenericArguments()[0].MakeByRefType();
if (arg is DynamicReflectionObject)
return ((DynamicReflectionObject)arg).target.GetType();
return arg.GetType();
}
private object AsDynamicIfNecessary(object value)
{
if (value == null)
return value;
var type = value.GetType();
if (type.IsClass && type != typeof(string))
return value.AsDynamicReflection();
return value;
}
private static T Cast<T>(object target)
{
return (T)target;
}
private interface IInvocable
{
bool IsGeneric { get; }
int GenericParameters { get; }
IList<ParameterInfo> Parameters { get; }
object Invoke(object obj, object[] parameters);
}
private class MethodInvocable : IInvocable
{
private MethodInfo method;
private Lazy<IList<ParameterInfo>> parameters;
public MethodInvocable(MethodInfo method)
{
this.method = method;
this.parameters = new Lazy<IList<ParameterInfo>>(() => this.method.GetParameters());
}
public object Invoke(object obj, object[] parameters)
{
return this.method.Invoke(obj, parameters);
}
public IList<ParameterInfo> Parameters
{
get { return this.parameters.Value; }
}
public MethodInfo Method { get { return this.method; } }
public bool IsGeneric { get { return this.method.IsGenericMethodDefinition; } }
public int GenericParameters { get { return this.method.GetGenericArguments().Length; } }
}
private class ConstructorInvocable : IInvocable
{
private ConstructorInfo ctor;
private Lazy<IList<ParameterInfo>> parameters;
public ConstructorInvocable(ConstructorInfo ctor)
{
this.ctor = ctor;
this.parameters = new Lazy<IList<ParameterInfo>>(() => this.ctor.GetParameters());
}
public object Invoke(object obj, object[] parameters)
{
return this.ctor.Invoke(obj, parameters);
}
public IList<ParameterInfo> Parameters
{
get { return this.parameters.Value; }
}
public bool IsGeneric { get { return false; } }
public int GenericParameters { get { return 0; } }
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.ServiceBus.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition;
using Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update;
using Microsoft.Azure.Management.ServiceBus.Fluent.Models;
using System.Collections.Generic;
using System;
internal partial class ServiceBusNamespaceImpl
{
/// <summary>
/// Creates a queue entity in the Service Bus namespace.
/// </summary>
/// <param name="name">Queue name.</param>
/// <param name="maxSizeInMB">Maximum size of memory allocated for the queue entity.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithQueue.WithNewQueue(string name, int maxSizeInMB)
{
return this.WithNewQueue(name, maxSizeInMB);
}
/// <summary>
/// Removes a queue entity from the Service Bus namespace.
/// </summary>
/// <param name="name">Queue name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithQueue.WithoutQueue(string name)
{
return this.WithoutQueue(name);
}
/// <summary>
/// Creates a queue entity in the Service Bus namespace.
/// </summary>
/// <param name="name">Queue name.</param>
/// <param name="maxSizeInMB">Maximum size of memory allocated for the queue entity.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithQueue.WithNewQueue(string name, int maxSizeInMB)
{
return this.WithNewQueue(name, maxSizeInMB);
}
/// <summary>
/// Creates a manage authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithAuthorizationRule.WithNewManageRule(string name)
{
return this.WithNewManageRule(name);
}
/// <summary>
/// Creates a send authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithAuthorizationRule.WithNewSendRule(string name)
{
return this.WithNewSendRule(name);
}
/// <summary>
/// Removes an authorization rule from the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithAuthorizationRule.WithoutAuthorizationRule(string name)
{
return this.WithoutAuthorizationRule(name);
}
/// <summary>
/// Creates a listen authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithAuthorizationRule.WithNewListenRule(string name)
{
return this.WithNewListenRule(name);
}
/// <summary>
/// Creates a manage authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithAuthorizationRule.WithNewManageRule(string name)
{
return this.WithNewManageRule(name);
}
/// <summary>
/// Creates a send authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithAuthorizationRule.WithNewSendRule(string name)
{
return this.WithNewSendRule(name);
}
/// <summary>
/// Creates a listen authorization rule for the Service Bus namespace.
/// </summary>
/// <param name="name">Rule name.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithAuthorizationRule.WithNewListenRule(string name)
{
return this.WithNewListenRule(name);
}
/// <summary>
/// Creates a topic entity in the Service Bus namespace.
/// </summary>
/// <param name="name">Topic name.</param>
/// <param name="maxSizeInMB">Maximum size of memory allocated for the topic entity.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithTopic.WithNewTopic(string name, int maxSizeInMB)
{
return this.WithNewTopic(name, maxSizeInMB);
}
/// <summary>
/// Removes a topic entity from the Service Bus namespace.
/// </summary>
/// <param name="name">Topic name.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithTopic.WithoutTopic(string name)
{
return this.WithoutTopic(name);
}
/// <summary>
/// Creates a topic entity in the Service Bus namespace.
/// </summary>
/// <param name="name">Topic name.</param>
/// <param name="maxSizeInMB">Maximum size of memory allocated for the topic entity.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithTopic.WithNewTopic(string name, int maxSizeInMB)
{
return this.WithNewTopic(name, maxSizeInMB);
}
/// <summary>
/// Gets the relative DNS name of the Service Bus namespace.
/// </summary>
string Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.DnsLabel
{
get
{
return this.DnsLabel();
}
}
/// <summary>
/// Gets fully qualified domain name (FQDN) of the Service Bus namespace.
/// </summary>
string Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.Fqdn
{
get
{
return this.Fqdn();
}
}
/// <summary>
/// Gets time the namespace was created.
/// </summary>
System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.CreatedAt
{
get
{
return this.CreatedAt();
}
}
/// <summary>
/// Gets sku value.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.NamespaceSku Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.Sku
{
get
{
return this.Sku();
}
}
/// <summary>
/// Gets entry point to manage authorization rules for the Service Bus namespace.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.INamespaceAuthorizationRules Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.AuthorizationRules
{
get
{
return this.AuthorizationRules();
}
}
/// <summary>
/// Gets time the namespace was updated.
/// </summary>
System.DateTime Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.UpdatedAt
{
get
{
return this.UpdatedAt();
}
}
/// <summary>
/// Gets entry point to manage topics entities in the Service Bus namespace.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.ITopics Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.Topics
{
get
{
return this.Topics();
}
}
/// <summary>
/// Gets entry point to manage queue entities in the Service Bus namespace.
/// </summary>
Microsoft.Azure.Management.ServiceBus.Fluent.IQueues Microsoft.Azure.Management.ServiceBus.Fluent.IServiceBusNamespace.Queues
{
get
{
return this.Queues();
}
}
/// <summary>
/// Specifies the namespace sku.
/// </summary>
/// <param name="namespaceSku">The sku.</param>
/// <return>Next stage of the Service Bus namespace update.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IUpdate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Update.IWithSku.WithSku(NamespaceSku namespaceSku)
{
return this.WithSku(namespaceSku);
}
/// <summary>
/// Specifies the namespace sku.
/// </summary>
/// <param name="namespaceSku">The sku.</param>
/// <return>Next stage of the Service Bus namespace definition.</return>
Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithCreate Microsoft.Azure.Management.ServiceBus.Fluent.ServiceBusNamespace.Definition.IWithSku.WithSku(NamespaceSku namespaceSku)
{
return this.WithSku(namespaceSku);
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Runtime;
using Orleans.Transactions.Abstractions;
using Orleans.Transactions.State;
using Orleans.Configuration;
using Orleans.Timers.Internal;
namespace Orleans.Transactions
{
/// <summary>
/// Stateful facet that respects Orleans transaction semantics
/// </summary>
public class TransactionalState<TState> : ITransactionalState<TState>, ILifecycleParticipant<IGrainLifecycle>
where TState : class, new()
{
private readonly TransactionalStateConfiguration config;
private readonly IGrainContext context;
private readonly ITransactionDataCopier<TState> copier;
private readonly Dictionary<Type,object> copiers;
private readonly IGrainRuntime grainRuntime;
private readonly ILogger logger;
private readonly ActivationLifetime activationLifetime;
private ParticipantId participantId;
private TransactionQueue<TState> queue;
public string CurrentTransactionId => TransactionContext.GetRequiredTransactionInfo().Id;
private bool detectReentrancy;
public TransactionalState(
TransactionalStateConfiguration transactionalStateConfiguration,
IGrainContextAccessor contextAccessor,
ITransactionDataCopier<TState> copier,
IGrainRuntime grainRuntime,
ILogger<TransactionalState<TState>> logger)
{
this.config = transactionalStateConfiguration;
this.context = contextAccessor.GrainContext;
this.copier = copier;
this.grainRuntime = grainRuntime;
this.logger = logger;
this.copiers = new Dictionary<Type, object>();
this.copiers.Add(typeof(TState), copier);
this.activationLifetime = new ActivationLifetime(this.context);
}
/// <summary>
/// Read the current state.
/// </summary>
public Task<TResult> PerformRead<TResult>(Func<TState, TResult> operation)
{
if (detectReentrancy)
{
throw new LockRecursionException("cannot perform a read operation from within another operation");
}
var info = (TransactionInfo)TransactionContext.GetRequiredTransactionInfo();
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"StartRead {info}");
info.Participants.TryGetValue(this.participantId, out var recordedaccesses);
// schedule read access to happen under the lock
return this.queue.RWLock.EnterLock<TResult>(info.TransactionId, info.Priority, recordedaccesses, true,
() =>
{
// check if our record is gone because we expired while waiting
if (!this.queue.RWLock.TryGetRecord(info.TransactionId, out TransactionRecord<TState> record))
{
throw new OrleansCascadingAbortException(info.TransactionId.ToString());
}
// merge the current clock into the transaction time stamp
record.Timestamp = this.queue.Clock.MergeUtcNow(info.TimeStamp);
if (record.State == null)
{
this.queue.GetMostRecentState(out record.State, out record.SequenceNumber);
}
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"update-lock read v{record.SequenceNumber} {record.TransactionId} {record.Timestamp:o}");
// record this read in the transaction info data structure
info.RecordRead(this.participantId, record.Timestamp);
// perform the read
TResult result = default(TResult);
try
{
detectReentrancy = true;
result = CopyResult(operation(record.State));
}
finally
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"EndRead {info} {result} {record.State}");
detectReentrancy = false;
}
return result;
});
}
/// <inheritdoc/>
public Task<TResult> PerformUpdate<TResult>(Func<TState, TResult> updateAction)
{
if (updateAction == null) throw new ArgumentNullException(nameof(updateAction));
if (detectReentrancy)
{
throw new LockRecursionException("cannot perform an update operation from within another operation");
}
var info = (TransactionInfo)TransactionContext.GetRequiredTransactionInfo();
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"StartWrite {info}");
if (info.IsReadOnly)
{
throw new OrleansReadOnlyViolatedException(info.Id);
}
info.Participants.TryGetValue(this.participantId, out var recordedaccesses);
return this.queue.RWLock.EnterLock<TResult>(info.TransactionId, info.Priority, recordedaccesses, false,
() =>
{
// check if we expired while waiting
if (!this.queue.RWLock.TryGetRecord(info.TransactionId, out TransactionRecord<TState> record))
{
throw new OrleansCascadingAbortException(info.TransactionId.ToString());
}
// merge the current clock into the transaction time stamp
record.Timestamp = this.queue.Clock.MergeUtcNow(info.TimeStamp);
// link to the latest state
if (record.State == null)
{
this.queue.GetMostRecentState(out record.State, out record.SequenceNumber);
}
// if this is the first write, make a deep copy of the state
if (!record.HasCopiedState)
{
record.State = this.copier.DeepCopy(record.State);
record.SequenceNumber++;
record.HasCopiedState = true;
}
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug($"update-lock write v{record.SequenceNumber} {record.TransactionId} {record.Timestamp:o}");
// record this write in the transaction info data structure
info.RecordWrite(this.participantId, record.Timestamp);
// perform the write
try
{
detectReentrancy = true;
return CopyResult(updateAction(record.State));
}
finally
{
if (logger.IsEnabled(LogLevel.Trace))
logger.Trace($"EndWrite {info} {record.TransactionId} {record.Timestamp}");
detectReentrancy = false;
}
}
);
}
public void Participate(IGrainLifecycle lifecycle)
{
lifecycle.Subscribe<TransactionalState<TState>>(GrainLifecycleStage.SetupState, (ct) => OnSetupState(ct, SetupResourceFactory));
}
private static void SetupResourceFactory(IGrainContext context, string stateName, TransactionQueue<TState> queue)
{
// Add resources factory to the grain context
context.RegisterResourceFactory<ITransactionalResource>(stateName, () => new TransactionalResource<TState>(queue));
// Add tm factory to the grain context
context.RegisterResourceFactory<ITransactionManager>(stateName, () => new TransactionManager<TState>(queue));
}
internal async Task OnSetupState(CancellationToken ct, Action<IGrainContext, string, TransactionQueue<TState>> setupResourceFactory)
{
if (ct.IsCancellationRequested) return;
this.participantId = new ParticipantId(this.config.StateName, this.context.GrainReference, this.config.SupportedRoles);
var storageFactory = this.context.ActivationServices.GetRequiredService<INamedTransactionalStateStorageFactory>();
ITransactionalStateStorage<TState> storage = storageFactory.Create<TState>(this.config.StorageName, this.config.StateName);
// setup transaction processing pipe
Action deactivate = () => grainRuntime.DeactivateOnIdle((Grain)context.GrainInstance);
var options = this.context.ActivationServices.GetRequiredService<IOptions<TransactionalStateOptions>>();
var clock = this.context.ActivationServices.GetRequiredService<IClock>();
var timerManager = this.context.ActivationServices.GetRequiredService<ITimerManager>();
this.queue = new TransactionQueue<TState>(options, this.participantId, deactivate, storage, clock, logger, timerManager, this.activationLifetime);
setupResourceFactory(this.context, this.config.StateName, queue);
// recover state
await this.queue.NotifyOfRestore();
}
private TResult CopyResult<TResult>(TResult result)
{
ITransactionDataCopier<TResult> resultCopier;
if (!this.copiers.TryGetValue(typeof(TResult), out object cp))
{
resultCopier = this.context.ActivationServices.GetRequiredService<ITransactionDataCopier<TResult>>();
this.copiers.Add(typeof(TResult), resultCopier);
}
else
{
resultCopier = (ITransactionDataCopier<TResult>)cp;
}
return resultCopier.DeepCopy(result);
}
}
}
| |
/*
* 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 cloudtrail-2013-11-01.normal.json service model.
*/
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.CloudTrail.Model;
using Amazon.CloudTrail.Model.Internal.MarshallTransformations;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Auth;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.CloudTrail
{
/// <summary>
/// Implementation for accessing CloudTrail
///
/// AWS CloudTrail
/// <para>
/// This is the CloudTrail API Reference. It provides descriptions of actions, data types,
/// common parameters, and common errors for CloudTrail.
/// </para>
///
/// <para>
/// CloudTrail is a web service that records AWS API calls for your AWS account and delivers
/// log files to an Amazon S3 bucket. The recorded information includes the identity of
/// the user, the start time of the AWS API call, the source IP address, the request parameters,
/// and the response elements returned by the service.
/// </para>
/// <note> As an alternative to using the API, you can use one of the AWS SDKs, which
/// consist of libraries and sample code for various programming languages and platforms
/// (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient way to create
/// programmatic access to AWSCloudTrail. For example, the SDKs take care of cryptographically
/// signing requests, managing errors, and retrying requests automatically. For information
/// about the AWS SDKs, including how to download and install them, see the <a href="http://aws.amazon.com/tools/">Tools
/// for Amazon Web Services page</a>. </note>
/// <para>
/// See the CloudTrail User Guide for information about the data that is included with
/// each AWS API call listed in the log files.
/// </para>
/// </summary>
public partial class AmazonCloudTrailClient : AmazonServiceClient, IAmazonCloudTrail
{
#region Constructors
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
public AmazonCloudTrailClient(AWSCredentials credentials)
: this(credentials, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(AWSCredentials credentials, RegionEndpoint region)
: this(credentials, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Credentials and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="credentials">AWS Credentials</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(AWSCredentials credentials, AmazonCloudTrailConfig clientConfig)
: base(credentials, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, new AmazonCloudTrailConfig() {RegionEndpoint=region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, clientConfig)
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig())
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID and AWS Secret Key
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="region">The region to connect.</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region)
: this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonCloudTrailConfig{RegionEndpoint = region})
{
}
/// <summary>
/// Constructs AmazonCloudTrailClient with AWS Access Key ID, AWS Secret Key and an
/// AmazonCloudTrailClient Configuration object.
/// </summary>
/// <param name="awsAccessKeyId">AWS Access Key ID</param>
/// <param name="awsSecretAccessKey">AWS Secret Access Key</param>
/// <param name="awsSessionToken">AWS Session Token</param>
/// <param name="clientConfig">The AmazonCloudTrailClient Configuration Object</param>
public AmazonCloudTrailClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonCloudTrailConfig clientConfig)
: base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig)
{
}
#endregion
#region Overrides
/// <summary>
/// Creates the signer for the service.
/// </summary>
protected override AbstractAWSSigner CreateSigner()
{
return new AWS4Signer();
}
#endregion
#region Dispose
/// <summary>
/// Disposes the service client.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#endregion
#region CreateTrail
internal CreateTrailResponse CreateTrail(CreateTrailRequest request)
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return Invoke<CreateTrailRequest,CreateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the CreateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<CreateTrailResponse> CreateTrailAsync(CreateTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new CreateTrailRequestMarshaller();
var unmarshaller = CreateTrailResponseUnmarshaller.Instance;
return InvokeAsync<CreateTrailRequest,CreateTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DeleteTrail
internal DeleteTrailResponse DeleteTrail(DeleteTrailRequest request)
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return Invoke<DeleteTrailRequest,DeleteTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the DeleteTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DeleteTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DeleteTrailResponse> DeleteTrailAsync(DeleteTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DeleteTrailRequestMarshaller();
var unmarshaller = DeleteTrailResponseUnmarshaller.Instance;
return InvokeAsync<DeleteTrailRequest,DeleteTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region DescribeTrails
internal DescribeTrailsResponse DescribeTrails()
{
return DescribeTrails(new DescribeTrailsRequest());
}
internal DescribeTrailsResponse DescribeTrails(DescribeTrailsRequest request)
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return Invoke<DescribeTrailsRequest,DescribeTrailsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Retrieves settings for the trail associated with the current region for your account.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeTrails service method, as returned by CloudTrail.</returns>
public Task<DescribeTrailsResponse> DescribeTrailsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
return DescribeTrailsAsync(new DescribeTrailsRequest(), cancellationToken);
}
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrails operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrails operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<DescribeTrailsResponse> DescribeTrailsAsync(DescribeTrailsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new DescribeTrailsRequestMarshaller();
var unmarshaller = DescribeTrailsResponseUnmarshaller.Instance;
return InvokeAsync<DescribeTrailsRequest,DescribeTrailsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region GetTrailStatus
internal GetTrailStatusResponse GetTrailStatus(GetTrailStatusRequest request)
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return Invoke<GetTrailStatusRequest,GetTrailStatusResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the GetTrailStatus operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the GetTrailStatus operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<GetTrailStatusResponse> GetTrailStatusAsync(GetTrailStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new GetTrailStatusRequestMarshaller();
var unmarshaller = GetTrailStatusResponseUnmarshaller.Instance;
return InvokeAsync<GetTrailStatusRequest,GetTrailStatusResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region LookupEvents
internal LookupEventsResponse LookupEvents(LookupEventsRequest request)
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return Invoke<LookupEventsRequest,LookupEventsResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the LookupEvents operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the LookupEvents operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<LookupEventsResponse> LookupEventsAsync(LookupEventsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new LookupEventsRequestMarshaller();
var unmarshaller = LookupEventsResponseUnmarshaller.Instance;
return InvokeAsync<LookupEventsRequest,LookupEventsResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region StartLogging
internal StartLoggingResponse StartLogging(StartLoggingRequest request)
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return Invoke<StartLoggingRequest,StartLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StartLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StartLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<StartLoggingResponse> StartLoggingAsync(StartLoggingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new StartLoggingRequestMarshaller();
var unmarshaller = StartLoggingResponseUnmarshaller.Instance;
return InvokeAsync<StartLoggingRequest,StartLoggingResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region StopLogging
internal StopLoggingResponse StopLogging(StopLoggingRequest request)
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return Invoke<StopLoggingRequest,StopLoggingResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the StopLogging operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the StopLogging operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<StopLoggingResponse> StopLoggingAsync(StopLoggingRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new StopLoggingRequestMarshaller();
var unmarshaller = StopLoggingResponseUnmarshaller.Instance;
return InvokeAsync<StopLoggingRequest,StopLoggingResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#endregion
#region UpdateTrail
internal UpdateTrailResponse UpdateTrail(UpdateTrailRequest request)
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return Invoke<UpdateTrailRequest,UpdateTrailResponse>(request, marshaller, unmarshaller);
}
/// <summary>
/// Initiates the asynchronous execution of the UpdateTrail operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the UpdateTrail operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
public Task<UpdateTrailResponse> UpdateTrailAsync(UpdateTrailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
{
var marshaller = new UpdateTrailRequestMarshaller();
var unmarshaller = UpdateTrailResponseUnmarshaller.Instance;
return InvokeAsync<UpdateTrailRequest,UpdateTrailResponse>(request, marshaller,
unmarshaller, cancellationToken);
}
#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!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>AdScheduleView</c> resource.</summary>
public sealed partial class AdScheduleViewName : gax::IResourceName, sys::IEquatable<AdScheduleViewName>
{
/// <summary>The possible contents of <see cref="AdScheduleViewName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>
/// .
/// </summary>
CustomerCampaignCriterion = 1,
}
private static gax::PathTemplate s_customerCampaignCriterion = new gax::PathTemplate("customers/{customer_id}/adScheduleViews/{campaign_id_criterion_id}");
/// <summary>Creates a <see cref="AdScheduleViewName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="AdScheduleViewName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static AdScheduleViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new AdScheduleViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="AdScheduleViewName"/> with the pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="AdScheduleViewName"/> constructed from the provided ids.</returns>
public static AdScheduleViewName FromCustomerCampaignCriterion(string customerId, string campaignId, string criterionId) =>
new AdScheduleViewName(ResourceNameType.CustomerCampaignCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string criterionId) =>
FormatCustomerCampaignCriterion(customerId, campaignId, criterionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="AdScheduleViewName"/> with pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>.
/// </returns>
public static string FormatCustomerCampaignCriterion(string customerId, string campaignId, string criterionId) =>
s_customerCampaignCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}");
/// <summary>
/// Parses the given resource name string into a new <see cref="AdScheduleViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="AdScheduleViewName"/> if successful.</returns>
public static AdScheduleViewName Parse(string adScheduleViewName) => Parse(adScheduleViewName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="AdScheduleViewName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="AdScheduleViewName"/> if successful.</returns>
public static AdScheduleViewName Parse(string adScheduleViewName, bool allowUnparsed) =>
TryParse(adScheduleViewName, allowUnparsed, out AdScheduleViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdScheduleViewName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdScheduleViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adScheduleViewName, out AdScheduleViewName result) =>
TryParse(adScheduleViewName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="AdScheduleViewName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="adScheduleViewName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="AdScheduleViewName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string adScheduleViewName, bool allowUnparsed, out AdScheduleViewName result)
{
gax::GaxPreconditions.CheckNotNull(adScheduleViewName, nameof(adScheduleViewName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignCriterion.TryParseName(adScheduleViewName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignCriterion(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(adScheduleViewName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private AdScheduleViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string criterionId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CriterionId = criterionId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="AdScheduleViewName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/adScheduleViews/{campaign_id}~{criterion_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param>
public AdScheduleViewName(string customerId, string campaignId, string criterionId) : this(ResourceNameType.CustomerCampaignCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CriterionId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCampaignCriterion: return s_customerCampaignCriterion.Expand(CustomerId, $"{CampaignId}~{CriterionId}");
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as AdScheduleViewName);
/// <inheritdoc/>
public bool Equals(AdScheduleViewName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(AdScheduleViewName a, AdScheduleViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(AdScheduleViewName a, AdScheduleViewName b) => !(a == b);
}
public partial class AdScheduleView
{
/// <summary>
/// <see cref="AdScheduleViewName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal AdScheduleViewName ResourceNameAsAdScheduleViewName
{
get => string.IsNullOrEmpty(ResourceName) ? null : AdScheduleViewName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
}
| |
using System.Collections.Generic;
using Content.Server.Construction.Components;
using Content.Shared.Construction;
using Content.Shared.Construction.Prototypes;
using Content.Shared.Construction.Steps;
using Content.Shared.Examine;
using Content.Shared.Popups;
using Content.Shared.Verbs;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
namespace Content.Server.Construction
{
public sealed partial class ConstructionSystem
{
private readonly Dictionary<ConstructionPrototype, ConstructionGuide> _guideCache = new();
private void InitializeGuided()
{
SubscribeNetworkEvent<RequestConstructionGuide>(OnGuideRequested);
SubscribeLocalEvent<ConstructionComponent, GetVerbsEvent<Verb>>(AddDeconstructVerb);
SubscribeLocalEvent<ConstructionComponent, ExaminedEvent>(HandleConstructionExamined);
}
private void OnGuideRequested(RequestConstructionGuide msg, EntitySessionEventArgs args)
{
if (!_prototypeManager.TryIndex(msg.ConstructionId, out ConstructionPrototype? prototype))
return;
if(GetGuide(prototype) is {} guide)
RaiseNetworkEvent(new ResponseConstructionGuide(msg.ConstructionId, guide), args.SenderSession.ConnectedClient);
}
private void AddDeconstructVerb(EntityUid uid, ConstructionComponent component, GetVerbsEvent<Verb> args)
{
if (!args.CanAccess || !args.CanInteract)
return;
if (component.TargetNode == component.DeconstructionNode ||
component.Node == component.DeconstructionNode)
return;
Verb verb = new();
//verb.Category = VerbCategories.Construction;
//TODO VERBS add more construction verbs? Until then, removing construction category
verb.Text = Loc.GetString("deconstructible-verb-begin-deconstruct");
verb.IconTexture = "/Textures/Interface/hammer_scaled.svg.192dpi.png";
verb.Act = () =>
{
SetPathfindingTarget(uid, component.DeconstructionNode, component);
if (component.TargetNode == null)
{
// Maybe check, but on the flip-side a better solution might be to not make it undeconstructible in the first place, no?
component.Owner.PopupMessage(args.User, Loc.GetString("deconstructible-verb-activate-no-target-text"));
}
else
{
component.Owner.PopupMessage(args.User, Loc.GetString("deconstructible-verb-activate-text"));
}
};
args.Verbs.Add(verb);
}
private void HandleConstructionExamined(EntityUid uid, ConstructionComponent component, ExaminedEvent args)
{
if (GetTargetNode(uid, component) is {} target)
{
args.PushMarkup(Loc.GetString(
"construction-component-to-create-header",
("targetName", target.Name)) + "\n");
}
if (component.EdgeIndex == null && GetTargetEdge(uid, component) is {} targetEdge)
{
var preventStepExamine = false;
foreach (var condition in targetEdge.Conditions)
{
preventStepExamine |= condition.DoExamine(args);
}
if (!preventStepExamine)
targetEdge.Steps[0].DoExamine(args);
return;
}
if (GetCurrentEdge(uid, component) is {} edge)
{
var preventStepExamine = false;
foreach (var condition in edge.Conditions)
{
preventStepExamine |= condition.DoExamine(args);
}
if (!preventStepExamine && component.StepIndex < edge.Steps.Count)
edge.Steps[component.StepIndex].DoExamine(args);
return;
}
}
private ConstructionGuide? GetGuide(ConstructionPrototype construction)
{
// NOTE: This method might be allocate a fair bit, but do not worry!
// This method is specifically designed to generate guides once and cache the results,
// therefore we don't need to worry *too much* about the performance of this.
// If we've generated and cached this guide before, return it.
if (_guideCache.TryGetValue(construction, out var guide))
return guide;
// If the graph doesn't actually exist, do nothing.
if (!_prototypeManager.TryIndex(construction.Graph, out ConstructionGraphPrototype? graph))
return null;
// If either the start node or the target node are missing, do nothing.
if (GetNodeFromGraph(graph, construction.StartNode) is not {} startNode
|| GetNodeFromGraph(graph, construction.TargetNode) is not {} targetNode)
return null;
// If there's no path from start to target, do nothing.
if (graph.Path(construction.StartNode, construction.TargetNode) is not {} path
|| path.Length == 0)
return null;
var step = 1;
var entries = new List<ConstructionGuideEntry>()
{
// Initial construction header.
new()
{
Localization = construction.Type == ConstructionType.Structure
? "construction-presenter-to-build" : "construction-presenter-to-craft",
EntryNumber = step,
}
};
var conditions = new HashSet<string>();
// Iterate until the penultimate node.
var node = startNode;
var index = 0;
while(node != targetNode)
{
// Can't find path, therefore can't generate guide...
if (!node.TryGetEdge(path[index].Name, out var edge))
return null;
// First steps are handled specially.
if (step == 1)
{
foreach (var graphStep in edge.Steps)
{
// This graph is invalid, we only allow insert steps as the initial construction steps.
if (graphStep is not EntityInsertConstructionGraphStep insertStep)
return null;
entries.Add(insertStep.GenerateGuideEntry());
}
// Now actually list the construction conditions.
foreach (var condition in construction.Conditions)
{
if (condition.GenerateGuideEntry() is not {} conditionEntry)
continue;
conditionEntry.Padding += 4;
entries.Add(conditionEntry);
}
step++;
node = path[index++];
// Add a bit of padding if there will be more steps after this.
if(node != targetNode)
entries.Add(new ConstructionGuideEntry());
continue;
}
var old = conditions;
conditions = new HashSet<string>();
foreach (var condition in edge.Conditions)
{
foreach (var conditionEntry in condition.GenerateGuideEntry())
{
conditions.Add(conditionEntry.Localization);
// Okay so if the condition entry had a non-null value here, we take it as a numbered step.
// This is for cases where there is a lot of snowflake behavior, such as machine frames...
// So that the step of inserting a machine board and inserting all of its parts is numbered.
if (conditionEntry.EntryNumber != null)
conditionEntry.EntryNumber = step++;
// To prevent spamming the same stuff over and over again. This is a bit naive, but..ye.
// Also we will only hide this condition *if* it isn't numbered.
else
{
if (old.Contains(conditionEntry.Localization))
continue;
// We only add padding for non-numbered entries.
conditionEntry.Padding += 4;
}
entries.Add(conditionEntry);
}
}
foreach (var graphStep in edge.Steps)
{
var entry = graphStep.GenerateGuideEntry();
entry.EntryNumber = step++;
entries.Add(entry);
}
node = path[index++];
}
guide = new ConstructionGuide(entries.ToArray());
_guideCache[construction] = guide;
return guide;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Mono.Cecil;
using Mono.Collections.Generic;
using Spinner.Fody.Multicasting;
namespace Spinner.Fody
{
internal static class ReferenceExtensions
{
internal static GenericParameter Clone(this GenericParameter genericParameter, MethodDefinition newOwner)
{
return new GenericParameter(newOwner)
{
Name = genericParameter.Name,
Attributes = genericParameter.Attributes
};
}
internal static MethodReference WithGenericDeclaringType(this MethodReference self, GenericInstanceType type)
{
Debug.Assert(type.Module == self.Module);
var reference = new MethodReference(self.Name, self.ReturnType, type)
{
HasThis = self.HasThis,
ExplicitThis = self.ExplicitThis,
CallingConvention = self.CallingConvention
};
if (self.HasParameters)
foreach (ParameterDefinition parameter in self.Parameters)
reference.Parameters.Add(new ParameterDefinition(parameter.ParameterType));
if (self.HasGenericParameters)
foreach (GenericParameter genericParam in self.GenericParameters)
reference.GenericParameters.Add(new GenericParameter(genericParam.Name, reference));
return reference;
}
internal static FieldReference WithGenericDeclaringType(this FieldReference self, GenericInstanceType type)
{
Debug.Assert(type.Module == self.Module);
return new FieldReference(self.Name, self.FieldType, type);
}
internal static IEnumerable<MethodDefinition> GetInheritedMethods(this TypeDefinition type)
{
TypeDefinition current = type;
while (current != null)
{
foreach (MethodDefinition m in current.Methods)
yield return m;
current = current.BaseType?.Resolve();
}
}
/// <summary>
/// Does a fast check if two references are for the same definition.
/// </summary>
internal static bool IsSame(this TypeReference self, TypeReference other)
{
if (ReferenceEquals(self, other))
return true;
if (self.Name != other.Name || self.Namespace != other.Namespace)
return false;
if (self.HasGenericParameters)
{
if (!other.HasGenericParameters)
return false;
if (self.GenericParameters.Count != other.GenericParameters.Count)
return false;
}
else if (other.HasGenericParameters)
{
return false;
}
Debug.Assert(self.Resolve() == other.Resolve());
return true;
}
/// <summary>
/// Does a fast check if two references are for the same definition.
/// </summary>
internal static bool IsSame(this FieldReference self, FieldReference other)
{
if (ReferenceEquals(self, other))
return true;
if (self.Name != other.Name)
return false;
if (!self.FieldType.IsSame(other.FieldType))
return false;
if (!self.DeclaringType.IsSame(other.DeclaringType))
return false;
Debug.Assert(self.Resolve() == other.Resolve());
return true;
}
/// <summary>
/// Shortcut for MetadataResolver.GetMethod() to get a matching method reference.
/// </summary>
internal static MethodDefinition GetMethod(this TypeDefinition self, MethodReference reference, bool inherited)
{
if (!inherited)
return self.HasMethods ? MetadataResolver.GetMethod(self.Methods, reference) : null;
TypeDefinition current = self;
while (current != null)
{
MethodDefinition result;
if (current.HasMethods && (result = MetadataResolver.GetMethod(current.Methods, reference)) != null)
return result;
current = current.BaseType?.Resolve();
}
return null;
}
internal static MethodDefinition GetConstructor(this TypeDefinition self, int argc)
{
if (self.HasMethods)
{
for (int i = 0; i < self.Methods.Count; i++)
{
MethodDefinition m = self.Methods[i];
if (argc == (m.HasParameters ? m.Parameters.Count : 0) && !m.IsStatic && m.IsConstructor)
return m;
}
}
return null;
}
internal static MethodDefinition GetConstructor(this TypeDefinition self, IList<TypeReference> paramTypes)
{
if (self.HasMethods)
{
for (int i = 0; i < self.Methods.Count; i++)
{
MethodDefinition m = self.Methods[i];
if (paramTypes.Count != (m.HasParameters ? m.Parameters.Count : 0) || m.IsStatic || !m.IsConstructor)
continue;
bool typeMatch = true;
for (int t = 0; t < paramTypes.Count; t++)
{
if (!m.Parameters[t].ParameterType.IsSame(paramTypes[t]))
{
typeMatch = false;
break;
}
}
if (!typeMatch)
continue;
return m;
}
}
return null;
}
internal static FieldDefinition GetField(this TypeDefinition self, string name, bool inherited)
{
TypeDefinition current = self;
while (current != null)
{
if (current.HasFields)
{
for (int i = 0; i < current.Fields.Count; i++)
{
if (current.Fields[i].Name == name)
return current.Fields[i];
}
}
if (!inherited)
break;
current = current.BaseType?.Resolve();
}
return null;
}
internal static PropertyDefinition GetProperty(this TypeDefinition self, string name, bool inherited)
{
TypeDefinition current = self;
while (current != null)
{
if (current.HasProperties)
{
for (int i = 0; i < current.Properties.Count; i++)
{
if (current.Properties[i].Name == name)
return current.Properties[i];
}
}
if (!inherited)
break;
current = current.BaseType?.Resolve();
}
return null;
}
internal static EventDefinition GetEvent(this TypeDefinition self, string name, bool inherited)
{
TypeDefinition current = self;
while (current != null)
{
if (current.HasEvents)
{
for (int i = 0; i < current.Events.Count; i++)
{
if (current.Events[i].Name == name)
return current.Events[i];
}
}
if (!inherited)
break;
current = current.BaseType?.Resolve();
}
return null;
}
internal static IMemberDefinition Resolve(this MemberReference self)
{
switch (self.GetProviderType())
{
case ProviderType.Type:
return ((TypeReference) self).Resolve();
case ProviderType.Method:
return ((MethodReference) self).Resolve();
case ProviderType.Property:
return ((PropertyReference) self).Resolve();
case ProviderType.Event:
return ((EventReference) self).Resolve();
case ProviderType.Field:
return ((FieldReference) self).Resolve();
default:
throw new ArgumentOutOfRangeException(nameof(self));
}
}
/// <summary>
/// Check if this type or one of its bases implements an interface. Does not check the interface's own inheritance.
/// </summary>
internal static bool HasInterface(this TypeDefinition self, TypeReference interfaceType, bool inherited)
{
TypeDefinition current = self;
while (current != null)
{
if (current.HasInterfaces)
{
for (int i = 0; i < current.Interfaces.Count; i++)
{
if (current.Interfaces[i].IsSame(interfaceType))
return true;
}
}
if (!inherited)
break;
current = current.BaseType?.Resolve();
}
return false;
}
//internal static bool IsSame(this MethodReference self, MethodReference other)
//{
// if (ReferenceEquals(self, other))
// return true;
// if (self.Name != other.Name)
// return false;
// if (!IsSame(self.DeclaringType, other.DeclaringType))
// return false;
// if (self.HasThis != other.HasThis)
// return false;
// if (self.HasParameters != other.HasParameters)
// return false;
// if (self.HasGenericParameters != other.HasGenericParameters)
// return false;
// if (self.HasParameters && (self.Parameters.Count != other.Parameters.Count))
// return false;
// if (self.HasGenericParameters && (self.GenericParameters.Count != other.GenericParameters.Count))
// return false;
// if (!IsSame(self.ReturnType, other.ReturnType))
// return false;
// for (int i = 0; i < self.Parameters.Count; i++)
// {
// if (!self.Parameters[i].ParameterType.IsSame(other.Parameters[i].ParameterType))
// return false;
// }
// return true;
//}
internal static CustomAttributeArgument? GetNamedArgument(this CustomAttribute self, string name)
{
if (self.HasProperties)
{
foreach (CustomAttributeNamedArgument p in self.Properties)
{
if (p.Name == name)
return p.Argument;
}
}
if (self.HasFields)
{
foreach (CustomAttributeNamedArgument f in self.Fields)
{
if (f.Name == name)
return f.Argument;
}
}
return null;
}
internal static object GetArgumentValue(this CustomAttribute self, int index)
{
return self.HasConstructorArguments && index < self.ConstructorArguments.Count
? self.ConstructorArguments[index].Value
: null;
}
internal static object GetNamedArgumentValue(this CustomAttribute self, string name)
{
return self.GetNamedArgument(name)?.Value;
}
internal static IEnumerable<IMemberDefinition> GetMembers(this TypeDefinition self)
{
if (self.HasFields)
{
foreach (FieldDefinition field in self.Fields)
yield return field;
}
if (self.HasEvents)
{
foreach (EventDefinition evt in self.Events)
yield return evt;
}
if (self.HasProperties)
{
foreach (PropertyDefinition prop in self.Properties)
yield return prop;
}
if (self.HasMethods)
{
foreach (MethodDefinition method in self.Methods)
yield return method;
}
if (self.HasNestedTypes)
{
foreach (TypeDefinition type in self.NestedTypes)
yield return type;
}
}
internal static MethodDefinition GetMethodDefinition(this ParameterDefinition p)
{
return (MethodDefinition) p.Method;
}
internal static MethodDefinition GetMethodDefinition(this MethodReturnType r)
{
return (MethodDefinition) r.Method;
}
internal static bool IsReturnVoid(this MethodReference method)
{
return method.ReturnType.IsSame(method.Module.TypeSystem.Void);
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* 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 halcyon 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.
*/
using OpenSim.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Connection
{
/// <summary>
/// Object representing the whole of an avatar connection. This object
/// encapsulates the CAPS as well as UDP communication object that makes
/// up an avatar's connection to the simulator
/// </summary>
public class AvatarConnection
{
/// <summary>
/// This is the circuit data we get passed from an initial contact from another
/// simulator or the login service
/// </summary>
private AgentCircuitData _circuitData;
/// <summary>
/// Our control over user caps.
/// </summary>
private ICapsControl _capsControl;
/// <summary>
/// The state of this connection
/// </summary>
private AvatarConnectionState _state;
/// <summary>
/// Why this connection is established
/// </summary>
private EstablishedBy _establishedReason;
/// <summary>
/// Our UDP circuit. May be null if not yet set up
/// </summary>
private IClientAPI _udpCircuit;
/// <summary>
/// Whether or not this connection is currently terminating
/// </summary>
private bool _terminating = false;
/// <summary>
/// Delegate called for connection terminations
/// </summary>
/// <param name="conn">The connection that was terminated</param>
public delegate void ConnectionTerminated(AvatarConnection conn);
/// <summary>
/// Event called when a connection is terminated
/// </summary>
public event ConnectionTerminated OnConnectionTerminated;
/// <summary>
/// This is the circuit data we get passed from an initial contact from another
/// simulator or the login service
/// </summary>
public AgentCircuitData CircuitData
{
get
{
return _circuitData;
}
}
/// <summary>
/// The state of this connection
/// </summary>
public AvatarConnectionState State
{
get
{
return _state;
}
}
/// <summary>
/// The udp cicuit attached to this connection
/// </summary>
public IClientAPI UdpCircuit
{
get
{
return _udpCircuit;
}
}
/// <summary>
/// The SP we're connected with
/// </summary>
public Scenes.ScenePresence ScenePresence { get; set; }
public AvatarConnection(AgentCircuitData circuitData, EstablishedBy reason)
{
_circuitData = circuitData;
_state = AvatarConnectionState.UDPCircuitWait;
_establishedReason = reason;
}
/// <summary>
/// Attempts to attach a UDP circuit to this connection.
/// </summary>
/// <param name="udpCircuit">The circuit to attach</param>
/// <exception cref=""
public void AttachUdpCircuit(IClientAPI udpCircuit)
{
if (_udpCircuit != null)
{
var ex = new AttachUdpCircuitException(String.Format("UDP circuit already exists for {0}. New code: {1}, Existing code: {2}",
_circuitData.AgentID, _udpCircuit.CircuitCode, udpCircuit.CircuitCode));
ex.CircuitAlreadyExisted = true;
if (udpCircuit.CircuitCode == _circuitData.CircuitCode &&
udpCircuit.SessionId == _circuitData.SessionID)
{
ex.ExistingCircuitMatched = true;
}
throw ex;
}
if (udpCircuit.CircuitCode != _circuitData.CircuitCode)
{
throw new AttachUdpCircuitException(String.Format("UDP circuit code doesnt match expected code for {0}. Expected: {1}, Actual {2}",
_circuitData.AgentID, _circuitData.CircuitCode, udpCircuit.CircuitCode));
}
if (udpCircuit.SessionId != _circuitData.SessionID)
{
throw new AttachUdpCircuitException(String.Format("UDP session ID doesnt match expected ID for {0}. Expected: {1}, Actual {2}",
_circuitData.AgentID, _circuitData.SessionID, udpCircuit.SessionId));
}
_udpCircuit = udpCircuit;
_udpCircuit.OnConnectionClosed += _udpCircuit_OnConnectionClosed;
_udpCircuit.OnSetThrottles += _udpCircuit_OnSetThrottles;
_state = AvatarConnectionState.Established;
}
void _udpCircuit_OnSetThrottles(int bwMax)
{
//fire this off on a secondary thread. it is not order critical and if
//aperture is hung this can hang
Util.FireAndForget((obj) => { this.SetRootBandwidth(bwMax); });
}
void _udpCircuit_OnConnectionClosed(IClientAPI obj)
{
this.Terminate(false);
}
/// <summary>
/// Called by the transit manager when this avatar has entered a new transit stage
/// </summary>
/// <param name="stage"></param>
public async Task TransitStateChange(AvatarTransit.TransitStage stage, IEnumerable<uint> rideOnPrimIds)
{
if (stage == AvatarTransit.TransitStage.SendBegin)
{
Physics.Manager.PhysicsActor pa = ScenePresence.PhysicsActor;
if (pa != null)
{
ScenePresence.PhysicsActor.Suspend();
}
if (_capsControl != null) _capsControl.PauseTraffic();
await _udpCircuit.PauseUpdatesAndFlush();
}
else if (stage == AvatarTransit.TransitStage.SendCompletedSuccess || stage == AvatarTransit.TransitStage.SendError)
{
if (_capsControl != null) _capsControl.ResumeTraffic();
if (stage == AvatarTransit.TransitStage.SendCompletedSuccess)
_udpCircuit.ResumeUpdates(rideOnPrimIds);
else
_udpCircuit.ResumeUpdates(null); // don't kill object update if not leaving region
if (stage == AvatarTransit.TransitStage.SendError)
{
Physics.Manager.PhysicsActor pa = ScenePresence.PhysicsActor;
if (pa != null)
{
pa.Resume(false, null);
}
}
}
}
/// <summary>
/// Assigns a caps control to this connection
/// </summary>
/// <param name="capsControl"></param>
internal void SetCapsControl(ICapsControl capsControl)
{
_capsControl = capsControl;
}
/// <summary>
/// Terminates this user connection. Terminates UDP and tears down caps handlers and waits for the
/// teardown to complete
/// </summary>
public void Terminate(bool waitForClose)
{
if (!_terminating)
{
_terminating = true;
if (_udpCircuit != null) _udpCircuit.Close();
if (_capsControl != null) _capsControl.Teardown();
if (_udpCircuit != null && waitForClose)
{
_udpCircuit.WaitForClose();
}
var terminatedHandler = OnConnectionTerminated;
if (terminatedHandler != null)
{
terminatedHandler(this);
}
}
else
{
if (_udpCircuit != null && waitForClose)
{
_udpCircuit.WaitForClose();
}
}
}
/// <summary>
/// Sets the bandwidth available. We will assign this number to our caps
/// </summary>
/// <param name="bytesPerSecond"></param>
internal void SetRootBandwidth(int bytesPerSecond)
{
if (_capsControl != null) _capsControl.SetMaxBandwidth(bytesPerSecond);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
internal abstract IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
TObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken);
private partial class Editor
{
private INamedTypeSymbol GenerateNamedType()
{
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
DetermineAccessibility(),
DetermineModifiers(),
DetermineTypeKind(),
DetermineName(),
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: DetermineMembers());
}
private INamedTypeSymbol GenerateNamedType(GenerateTypeOptionsResult options)
{
if (options.TypeKind == TypeKind.Delegate)
{
return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
DetermineReturnType(options),
options.TypeName,
DetermineTypeParameters(options),
DetermineParameters(options));
}
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
options.TypeKind,
options.TypeName,
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: DetermineMembers(options));
}
private ITypeSymbol DetermineReturnType(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol == null ||
_state.DelegateMethodSymbol.ReturnType == null ||
_state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol)
{
// Since we cannot determine the return type, we are returning void
return _state.Compilation.GetSpecialType(SpecialType.System_Void);
}
else
{
return _state.DelegateMethodSymbol.ReturnType;
}
}
private IList<ITypeParameterSymbol> DetermineTypeParameters(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.TypeParameters;
}
// If the delegate symbol cannot be determined then
return DetermineTypeParameters();
}
private IList<IParameterSymbol> DetermineParameters(GenerateTypeOptionsResult options)
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.Parameters;
}
return null;
}
private IList<ISymbol> DetermineMembers(GenerateTypeOptionsResult options = null)
{
var members = new List<ISymbol>();
AddMembers(members, options);
if (_state.IsException)
{
AddExceptionConstructors(members);
}
return members;
}
private void AddMembers(IList<ISymbol> members, GenerateTypeOptionsResult options = null)
{
AddProperties(members);
IList<TArgumentSyntax> argumentList;
if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out argumentList))
{
return;
}
var parameterTypes = GetArgumentTypes(argumentList);
// Don't generate this constructor if it would conflict with a default exception
// constructor. Default exception constructors will be added automatically by our
// caller.
if (_state.IsException &&
_state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any(
c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes)))
{
return;
}
// If there's an accessible base constructor that would accept these types, then
// just call into that instead of generating fields.
if (_state.BaseTypeOrInterfaceOpt != null)
{
if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface && argumentList.Count == 0)
{
// No need to add the default constructor if our base type is going to be
// 'object'. We get that constructor for free.
return;
}
var accessibleInstanceConstructors = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Where(
IsSymbolAccessible).ToSet();
if (accessibleInstanceConstructors.Any())
{
var delegatedConstructor = _service.GetDelegatingConstructor(
_document,
_state.ObjectCreationExpressionOpt,
_state.BaseTypeOrInterfaceOpt,
accessibleInstanceConstructors,
_cancellationToken);
if (delegatedConstructor != null)
{
// There was a best match. Call it directly.
AddBaseDelegatingConstructor(delegatedConstructor, members);
return;
}
}
}
// Otherwise, just generate a normal constructor that assigns any provided
// parameters into fields.
AddFieldDelegatingConstructor(argumentList, members, options);
}
private void AddProperties(IList<ISymbol> members)
{
var typeInference = _document.Project.LanguageServices.GetService<ITypeInferenceService>();
foreach (var property in _state.PropertiesToGenerate)
{
IPropertySymbol generatedProperty;
if (_service.TryGenerateProperty(property, _document.SemanticModel, typeInference, _cancellationToken, out generatedProperty))
{
members.Add(generatedProperty);
}
}
}
private void AddBaseDelegatingConstructor(
IMethodSymbol methodSymbol,
IList<ISymbol> members)
{
// If we're generating a constructor to delegate into the no-param base constructor
// then we can just elide the constructor entirely.
if (methodSymbol.Parameters.Length == 0)
{
return;
}
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
members.Add(factory.CreateBaseDelegatingConstructor(
methodSymbol, DetermineName()));
}
private void AddFieldDelegatingConstructor(
IList<TArgumentSyntax> argumentList, IList<ISymbol> members, GenerateTypeOptionsResult options = null)
{
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
var syntaxFactsService = _document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
var parameterTypes = GetArgumentTypes(argumentList);
var parameterNames = _service.GenerateParameterNames(_document.SemanticModel, argumentList);
var parameters = new List<IParameterSymbol>();
var parameterToExistingFieldMap = new Dictionary<string, ISymbol>();
var parameterToNewFieldMap = new Dictionary<string, string>();
var syntaxFacts = _document.Project.LanguageServices.GetService<ISyntaxFactsService>();
for (var i = 0; i < parameterNames.Count; i++)
{
var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);
var parameterName = parameterNames[i];
var parameterType = parameterTypes[i];
parameterType = parameterType.RemoveUnavailableTypeParameters(
_document.SemanticModel.Compilation, availableTypeParameters);
if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true))
{
if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false))
{
parameterToNewFieldMap[parameterName] = parameterName;
}
}
parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: null,
refKind: refKind,
isParams: false,
type: parameterType,
name: parameterName));
}
// Empty Constructor for Struct is not allowed
if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
{
members.AddRange(factory.CreateFieldDelegatingConstructor(
DetermineName(), null, parameters, parameterToExistingFieldMap, parameterToNewFieldMap, _cancellationToken));
}
}
private void AddExceptionConstructors(IList<ISymbol> members)
{
var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>();
var exceptionType = _document.SemanticModel.Compilation.ExceptionType();
var constructors =
exceptionType.InstanceConstructors
.Where(c => c.DeclaredAccessibility == Accessibility.Public || c.DeclaredAccessibility == Accessibility.Protected)
.Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: null,
accessibility: c.DeclaredAccessibility,
modifiers: default(DeclarationModifiers),
typeName: DetermineName(),
parameters: c.Parameters,
statements: null,
baseConstructorArguments: c.Parameters.Length == 0 ? null : factory.CreateArguments(c.Parameters)));
members.AddRange(constructors);
}
private IList<AttributeData> DetermineAttributes()
{
if (_state.IsException)
{
var serializableType = _document.SemanticModel.Compilation.SerializableAttributeType();
if (serializableType != null)
{
var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType);
return new[] { attribute };
}
}
return null;
}
private Accessibility DetermineAccessibility()
{
return _service.GetAccessibility(_state, _document.SemanticModel, _intoNamespace, _cancellationToken);
}
private DeclarationModifiers DetermineModifiers()
{
return default(DeclarationModifiers);
}
private INamedTypeSymbol DetermineBaseType()
{
if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
return null;
}
return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
}
private IList<INamedTypeSymbol> DetermineInterfaces()
{
if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
if (type != null)
{
return new[] { type };
}
}
return SpecializedCollections.EmptyList<INamedTypeSymbol>();
}
private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type)
{
return type.RemoveUnavailableTypeParameters(
_document.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol;
}
private string DetermineName()
{
return GetTypeName(_state);
}
private IList<ITypeParameterSymbol> DetermineTypeParameters()
{
return _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken);
}
private TypeKind DetermineTypeKind()
{
return _state.IsStruct
? TypeKind.Struct
: _state.IsInterface
? TypeKind.Interface
: TypeKind.Class;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters()
{
var availableInnerTypeParameters = _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken);
var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null
? _state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
}
internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property);
}
}
| |
/* ====================================================================
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.Chart
{
using System;
using System.Text;
using NPOI.Util;
/**
* Defines a legend for a chart.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Andrew C. Oliver (acoliver at apache.org)
*/
public class LegendRecord
: StandardRecord
{
public const short sid = 0x1015;
private int field_1_xAxisUpperLeft;
private int field_2_yAxisUpperLeft;
private int field_3_xSize;
private int field_4_ySize;
private byte field_5_type;
public const byte TYPE_BOTTOM = 0;
public const byte TYPE_CORNER = 1;
public const byte TYPE_TOP = 2;
public const byte TYPE_RIGHT = 3;
public const byte TYPE_LEFT = 4;
public const byte TYPE_UNDOCKED = 7;
private byte field_6_spacing;
public const byte SPACING_CLOSE = 0;
public const byte SPACING_MEDIUM = 1;
public const byte SPACING_OPEN = 2;
private short field_7_options;
private BitField autoPosition = BitFieldFactory.GetInstance(0x1);
private BitField autoSeries = BitFieldFactory.GetInstance(0x2);
private BitField autoXPositioning = BitFieldFactory.GetInstance(0x4);
private BitField autoYPositioning = BitFieldFactory.GetInstance(0x8);
private BitField vertical = BitFieldFactory.GetInstance(0x10);
private BitField dataTable = BitFieldFactory.GetInstance(0x20);
public LegendRecord()
{
}
/**
* Constructs a Legend record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public LegendRecord(RecordInputStream in1)
{
field_1_xAxisUpperLeft = in1.ReadInt();
field_2_yAxisUpperLeft = in1.ReadInt();
field_3_xSize = in1.ReadInt();
field_4_ySize = in1.ReadInt();
field_5_type = (byte)in1.ReadByte();
field_6_spacing = (byte)in1.ReadByte();
field_7_options = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[LEGEND]\n");
buffer.Append(" .xAxisUpperLeft = ")
.Append("0x").Append(HexDump.ToHex(XAxisUpperLeft))
.Append(" (").Append(XAxisUpperLeft).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .yAxisUpperLeft = ")
.Append("0x").Append(HexDump.ToHex(YAxisUpperLeft))
.Append(" (").Append(YAxisUpperLeft).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .xSize = ")
.Append("0x").Append(HexDump.ToHex(XSize))
.Append(" (").Append(XSize).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .ySize = ")
.Append("0x").Append(HexDump.ToHex(YSize))
.Append(" (").Append(YSize).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .type = ")
.Append("0x").Append(HexDump.ToHex(Type))
.Append(" (").Append(Type).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .spacing = ")
.Append("0x").Append(HexDump.ToHex(Spacing))
.Append(" (").Append(Spacing).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .options = ")
.Append("0x").Append(HexDump.ToHex(Options))
.Append(" (").Append(Options).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .autoPosition = ").Append(IsAutoPosition).Append('\n');
buffer.Append(" .autoSeries = ").Append(IsAutoSeries).Append('\n');
buffer.Append(" .autoXPositioning = ").Append(IsAutoXPositioning).Append('\n');
buffer.Append(" .autoYPositioning = ").Append(IsAutoYPositioning).Append('\n');
buffer.Append(" .vertical = ").Append(IsVertical).Append('\n');
buffer.Append(" .dataTable = ").Append(IsDataTable).Append('\n');
buffer.Append("[/LEGEND]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteInt(field_1_xAxisUpperLeft);
out1.WriteInt(field_2_yAxisUpperLeft);
out1.WriteInt(field_3_xSize);
out1.WriteInt(field_4_ySize);
out1.WriteByte(field_5_type);
out1.WriteByte(field_6_spacing);
out1.WriteShort(field_7_options);
}
/**
* Size of record (exluding 4 byte header)
*/
protected override int DataSize
{
get { return 4 + 4 + 4 + 4 + 1 + 1 + 2; }
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
LegendRecord rec = new LegendRecord();
rec.field_1_xAxisUpperLeft = field_1_xAxisUpperLeft;
rec.field_2_yAxisUpperLeft = field_2_yAxisUpperLeft;
rec.field_3_xSize = field_3_xSize;
rec.field_4_ySize = field_4_ySize;
rec.field_5_type = field_5_type;
rec.field_6_spacing = field_6_spacing;
rec.field_7_options = field_7_options;
return rec;
}
/**
* Get the x axis upper left field for the Legend record.
*/
public int XAxisUpperLeft
{
get
{
return field_1_xAxisUpperLeft;
}
set
{
field_1_xAxisUpperLeft = value;
}
}
/**
* Get the y axis upper left field for the Legend record.
*/
public int YAxisUpperLeft
{
get
{
return field_2_yAxisUpperLeft;
}
set
{
field_2_yAxisUpperLeft = value;
}
}
/**
* Get the x size field for the Legend record.
*/
public int XSize
{
get { return field_3_xSize; }
set { this.field_3_xSize = value; }
}
/**
* Get the y size field for the Legend record.
*/
public int YSize
{
get { return field_4_ySize; }
set { this.field_4_ySize = value; }
}
/**
* Get the type field for the Legend record.
*
* @return One of
* TYPE_BOTTOM
* TYPE_CORNER
* TYPE_TOP
* TYPE_RIGHT
* TYPE_LEFT
* TYPE_UNDOCKED
*/
public byte Type
{
get { return field_5_type; }
set { this.field_5_type = value; }
}
/**
* Get the spacing field for the Legend record.
*
* @return One of
* SPACING_CLOSE
* SPACING_MEDIUM
* SPACING_OPEN
*/
public byte Spacing
{
get { return field_6_spacing; }
set { this.field_6_spacing = value; }
}
/**
* Get the options field for the Legend record.
*/
public short Options
{
get { return field_7_options; }
set { this.field_7_options = value; }
}
/**
* automatic positioning (1=docked)
* @return the auto position field value.
*/
public bool IsAutoPosition
{
get { return autoPosition.IsSet(field_7_options); }
set { field_7_options = autoPosition.SetShortBoolean(field_7_options, value); }
}
/**
* excel 5 only (true)
* @return the auto series field value.
*/
public bool IsAutoSeries
{
get { return autoSeries.IsSet(field_7_options); }
set { field_7_options = autoSeries.SetShortBoolean(field_7_options, value); }
}
/**
* position of legend on the x axis is automatic
* @return the auto x positioning field value.
*/
public bool IsAutoXPositioning
{
get{return autoXPositioning.IsSet(field_7_options);}
set { field_7_options = autoXPositioning.SetShortBoolean(field_7_options, value); }
}
/**
* position of legend on the y axis is automatic
* @return the auto y positioning field value.
*/
public bool IsAutoYPositioning
{
get{return autoYPositioning.IsSet(field_7_options);}
set{field_7_options = autoYPositioning.SetShortBoolean(field_7_options, value);}
}
/**
* vertical or horizontal legend (1 or 0 respectively). Always 0 if not automatic.
* @return the vertical field value.
*/
public bool IsVertical
{
get { return vertical.IsSet(field_7_options); }
set { field_7_options = vertical.SetShortBoolean(field_7_options, value); }
}
/**
* 1 if chart Contains data table
* @return the data table field value.
*/
public bool IsDataTable
{
get{return dataTable.IsSet(field_7_options);}
set { field_7_options = dataTable.SetShortBoolean(field_7_options, value); }
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Linq;
using Xunit;
namespace System.IO.FileSystem.Tests
{
public class Directory_Exists : FileSystemTest
{
#region Utilities
public bool Exists(string path)
{
return Directory.Exists(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullAsPath_ReturnsFalse()
{
Assert.False(Exists(null));
}
[Fact]
public void EmptyAsPath_ReturnsFalse()
{
Assert.False(Exists(string.Empty));
}
[Fact]
public void NonExistentValidPath_ReturnsFalse()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (path) =>
{
Assert.False(Exists(path), path);
});
}
[Fact]
public void ValidPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = Path.Combine(TestDirectory, component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
public void PathWithInvalidCharactersAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on paths with impossible to create characters
char[] trimmed = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 };
Assert.All((IOInputs.GetPathsWithInvalidCharacters()), (component) =>
{
Assert.False(Exists(component));
if (!trimmed.Contains(component.ToCharArray()[0]))
Assert.False(Exists(TestDirectory + Path.DirectorySeparatorChar + component));
});
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void PathAlreadyExistsAsDirectory()
{
string path = GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
public void DotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, ".")));
}
[Fact]
public void DirectoryGetCurrentDirectoryAsPath_ReturnsTrue()
{
Assert.True(Exists(Directory.GetCurrentDirectory()));
}
[Fact]
public void DotDotAsPath_ReturnsTrue()
{
Assert.True(Exists(Path.Combine(TestDirectory, GetTestFileName(), "..")));
}
[Fact]
public void DirectoryLongerThanMaxPathAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxPath()), (path) =>
{
Assert.False(Exists(path), path);
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ValidExtendedPathExists_ReturnsTrue()
{
Assert.All((IOInputs.GetValidPathComponentNames()), (component) =>
{
string path = IOInputs.ExtendedPrefix + Path.Combine(TestDirectory, "extended", component);
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsFile()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
File.Create(path).Dispose();
Assert.False(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.False(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathAlreadyExistsAsDirectory()
{
string path = IOInputs.ExtendedPrefix + GetTestFilePath();
DirectoryInfo testDir = Directory.CreateDirectory(path);
Assert.True(Exists(IOServices.RemoveTrailingSlash(path)));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.RemoveTrailingSlash(path))));
Assert.True(Exists(IOServices.RemoveTrailingSlash(IOServices.AddTrailingSlashIfNeeded(path))));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void DirectoryLongerThanMaxDirectoryAsPath_DoesntThrow()
{
Assert.All((IOInputs.GetPathsLongerThanMaxDirectory()), (path) =>
{
Assert.False(Exists(path));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // Unix equivalent tested already in CreateDirectory
public void WindowsWhiteSpaceAsPath_ReturnsFalse()
{
// Checks that errors aren't thrown when calling Exists() on impossible paths
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows | PlatformID.OSX)]
public void DoesCaseInsensitiveInvariantComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.True(Exists(testDir.FullName.ToUpperInvariant()));
Assert.True(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Linux | PlatformID.FreeBSD)]
public void DoesCaseSensitiveComparisons()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.True(Exists(testDir.FullName));
Assert.False(Exists(testDir.FullName.ToUpperInvariant()));
Assert.False(Exists(testDir.FullName.ToLowerInvariant()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // In Windows, trailing whitespace in a path is trimmed appropriately
public void TrailingWhitespaceExistence()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
string path = testDir.FullName + component;
Assert.True(Exists(path), path); // string concat in case Path.Combine() trims whitespace before Exists gets to it
Assert.False(Exists(IOInputs.ExtendedPrefix + path), path);
});
Assert.All(IOInputs.GetSimpleWhiteSpace(), (component) =>
{
string path = GetTestFilePath(memberName: "Extended") + component;
testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + path);
Assert.False(Exists(path), path);
Assert.True(Exists(testDir.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data stream
public void PathWithAlternateDataStreams_ReturnsFalse()
{
Assert.All(IOInputs.GetWhiteSpace(), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device names
public void PathWithReservedDeviceNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithReservedDeviceNames()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC paths
public void UncPathWithoutShareNameAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetUncPathsWithoutShareName()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryEqualToMaxDirectory_ReturnsTrue()
{
// Creates directories up to the maximum directory length all at once
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10);
Directory.CreateDirectory(path.FullPath);
Assert.True(Exists(path.FullPath));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public void DirectoryWithComponentLongerThanMaxComponentAsPath_ReturnsFalse()
{
Assert.All((IOInputs.GetPathsWithComponentLongerThanMaxComponent()), (component) =>
{
Assert.False(Exists(component));
});
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(drive);
Assert.False(result);
}
[Fact]
[ActiveIssue(1221)]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNotReadyDriveAsPath_ReturnsFalse()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
bool result = Exists(Path.Combine(drive, "Subdirectory"));
Assert.False(result);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void NonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(IOServices.GetNonExistentDrive()));
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // drive labels
public void SubdirectoryOnNonExistentDriveAsPath_ReturnsFalse()
{
Assert.False(Exists(Path.Combine(IOServices.GetNonExistentDrive(), "nonexistentsubdir")));
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// In the desktop version of the framework, this file is generated from ProviderBase\DbConnectionHelper.cs
// #line 1 "e:\\fxdata\\src\\ndp\\fx\\src\\data\\system\\data\\providerbase\\dbconnectionhelper.cs"
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Threading;
using System.Transactions;
namespace System.Data.SqlClient
{
public sealed partial class SqlConnection : DbConnection
{
private static readonly DbConnectionFactory s_connectionFactory = SqlConnectionFactory.SingletonInstance;
private DbConnectionOptions _userConnectionOptions;
private DbConnectionPoolGroup _poolGroup;
private DbConnectionInternal _innerConnection;
private int _closeCount;
public SqlConnection() : base()
{
GC.SuppressFinalize(this);
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
internal int CloseCount
{
get
{
return _closeCount;
}
}
internal DbConnectionFactory ConnectionFactory
{
get
{
return s_connectionFactory;
}
}
internal DbConnectionOptions ConnectionOptions
{
get
{
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
return ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
}
}
private string ConnectionString_Get()
{
bool hidePassword = InnerConnection.ShouldHidePassword;
DbConnectionOptions connectionOptions = UserConnectionOptions;
return ((null != connectionOptions) ? connectionOptions.UsersConnectionString(hidePassword) : "");
}
private void ConnectionString_Set(DbConnectionPoolKey key)
{
DbConnectionOptions connectionOptions = null;
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = ConnectionFactory.GetConnectionPoolGroup(key, null, ref connectionOptions);
DbConnectionInternal connectionInternal = InnerConnection;
bool flag = connectionInternal.AllowSetConnectionString;
if (flag)
{
flag = SetInnerConnectionFrom(DbConnectionClosedBusy.SingletonInstance, connectionInternal);
if (flag)
{
_userConnectionOptions = connectionOptions;
_poolGroup = poolGroup;
_innerConnection = DbConnectionClosedNeverOpened.SingletonInstance;
}
}
if (!flag)
{
throw ADP.OpenConnectionPropertySet(nameof(ConnectionString), connectionInternal.State);
}
}
internal DbConnectionInternal InnerConnection
{
get
{
return _innerConnection;
}
}
internal System.Data.ProviderBase.DbConnectionPoolGroup PoolGroup
{
get
{
return _poolGroup;
}
set
{
Debug.Assert(null != value, "null poolGroup");
_poolGroup = value;
}
}
internal DbConnectionOptions UserConnectionOptions
{
get
{
return _userConnectionOptions;
}
}
internal void Abort(Exception e)
{
DbConnectionInternal innerConnection = _innerConnection;
if (ConnectionState.Open == innerConnection.State)
{
Interlocked.CompareExchange(ref _innerConnection, DbConnectionClosedPreviouslyOpened.SingletonInstance, innerConnection);
innerConnection.DoomThisConnection();
}
}
internal void AddWeakReference(object value, int tag)
{
InnerConnection.AddWeakReference(value, tag);
}
protected override DbCommand CreateDbCommand()
{
DbCommand command = null;
DbProviderFactory providerFactory = ConnectionFactory.ProviderFactory;
command = providerFactory.CreateCommand();
command.Connection = this;
return command;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_userConnectionOptions = null;
_poolGroup = null;
Close();
}
DisposeMe(disposing);
base.Dispose(disposing);
}
partial void RepairInnerConnection();
public override void EnlistTransaction(Transaction transaction)
{
// If we're currently enlisted in a transaction and we were called
// on the EnlistTransaction method (Whidbey) we're not allowed to
// enlist in a different transaction.
DbConnectionInternal innerConnection = InnerConnection;
// NOTE: since transaction enlistment involves round trips to the
// server, we don't want to lock here, we'll handle the race conditions
// elsewhere.
Transaction enlistedTransaction = innerConnection.EnlistedTransaction;
if (enlistedTransaction != null)
{
// Allow calling enlist if already enlisted (no-op)
if (enlistedTransaction.Equals(transaction))
{
return;
}
// Allow enlisting in a different transaction if the enlisted transaction has completed.
if (enlistedTransaction.TransactionInformation.Status == TransactionStatus.Active)
{
throw ADP.TransactionPresent();
}
}
RepairInnerConnection();
InnerConnection.EnlistTransaction(transaction);
// NOTE: If this outer connection were to be GC'd while we're
// enlisting, the pooler would attempt to reclaim the inner connection
// while we're attempting to enlist; not sure how likely that is but
// we should consider a GC.KeepAlive(this) here.
GC.KeepAlive(this);
}
internal void NotifyWeakReference(int message)
{
InnerConnection.NotifyWeakReference(message);
}
internal void PermissionDemand()
{
Debug.Assert(DbConnectionClosedConnecting.SingletonInstance == _innerConnection, "not connecting");
System.Data.ProviderBase.DbConnectionPoolGroup poolGroup = PoolGroup;
DbConnectionOptions connectionOptions = ((null != poolGroup) ? poolGroup.ConnectionOptions : null);
if ((null == connectionOptions) || connectionOptions.IsEmpty)
{
throw ADP.NoConnectionString();
}
DbConnectionOptions userConnectionOptions = UserConnectionOptions;
Debug.Assert(null != userConnectionOptions, "null UserConnectionOptions");
}
internal void RemoveWeakReference(object value)
{
InnerConnection.RemoveWeakReference(value);
}
internal void SetInnerConnectionEvent(DbConnectionInternal to)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
ConnectionState originalState = _innerConnection.State & ConnectionState.Open;
ConnectionState currentState = to.State & ConnectionState.Open;
if ((originalState != currentState) && (ConnectionState.Closed == currentState))
{
unchecked { _closeCount++; }
}
_innerConnection = to;
if (ConnectionState.Closed == originalState && ConnectionState.Open == currentState)
{
OnStateChange(DbConnectionInternal.StateChangeOpen);
}
else if (ConnectionState.Open == originalState && ConnectionState.Closed == currentState)
{
OnStateChange(DbConnectionInternal.StateChangeClosed);
}
else
{
Debug.Fail("unexpected state switch");
if (originalState != currentState)
{
OnStateChange(new StateChangeEventArgs(originalState, currentState));
}
}
}
internal bool SetInnerConnectionFrom(DbConnectionInternal to, DbConnectionInternal from)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != from, "from null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
bool result = (from == Interlocked.CompareExchange<DbConnectionInternal>(ref _innerConnection, to, from));
return result;
}
internal void SetInnerConnectionTo(DbConnectionInternal to)
{
Debug.Assert(null != _innerConnection, "null InnerConnection");
Debug.Assert(null != to, "to null InnerConnection");
_innerConnection = to;
}
}
}
| |
// <copyright file="LUTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex32;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Factorization
{
using Numerics;
/// <summary>
/// LU factorization tests for a dense matrix.
/// </summary>
[TestFixture, Category("LAFactorization")]
public class LUTests
{
/// <summary>
/// Can factorize identity matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void CanFactorizeIdentity(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var factorLU = matrixI.LU();
// Check lower triangular part.
var matrixL = factorLU.L;
Assert.AreEqual(matrixI.RowCount, matrixL.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixL.ColumnCount);
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrixL[i, j]);
}
}
// Check upper triangular part.
var matrixU = factorLU.U;
Assert.AreEqual(matrixI.RowCount, matrixU.RowCount);
Assert.AreEqual(matrixI.ColumnCount, matrixU.ColumnCount);
for (var i = 0; i < matrixU.RowCount; i++)
{
for (var j = 0; j < matrixU.ColumnCount; j++)
{
Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrixU[i, j]);
}
}
}
/// <summary>
/// LU factorization fails with a non-square matrix.
/// </summary>
[Test]
public void LUFailsWithNonSquareMatrix()
{
var matrix = new DenseMatrix(3, 1);
Assert.That(() => matrix.LU(), Throws.ArgumentException);
}
/// <summary>
/// Identity determinant is one.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(10)]
[TestCase(100)]
public void IdentityDeterminantIsOne(int order)
{
var matrixI = DenseMatrix.CreateIdentity(order);
var lu = matrixI.LU();
Assert.AreEqual(Complex32.One, lu.Determinant);
}
/// <summary>
/// Can factorize a random square matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanFactorizeRandomMatrix(int order)
{
var matrixX = Matrix<Complex32>.Build.Random(order, order, 1);
var factorLU = matrixX.LU();
var matrixL = factorLU.L;
var matrixU = factorLU.U;
// Make sure the factors have the right dimensions.
Assert.AreEqual(order, matrixL.RowCount);
Assert.AreEqual(order, matrixL.ColumnCount);
Assert.AreEqual(order, matrixU.RowCount);
Assert.AreEqual(order, matrixU.ColumnCount);
// Make sure the L factor is lower triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
Assert.AreEqual(Complex32.One, matrixL[i, i]);
for (var j = i + 1; j < matrixL.ColumnCount; j++)
{
Assert.AreEqual(Complex32.Zero, matrixL[i, j]);
}
}
// Make sure the U factor is upper triangular.
for (var i = 0; i < matrixL.RowCount; i++)
{
for (var j = 0; j < i; j++)
{
Assert.AreEqual(Complex32.Zero, matrixU[i, j]);
}
}
// Make sure the LU factor times it's transpose is the original matrix.
var matrixXfromLU = matrixL * matrixU;
var permutationInverse = factorLU.P.Inverse();
matrixXfromLU.PermuteRows(permutationInverse);
for (var i = 0; i < matrixXfromLU.RowCount; i++)
{
for (var j = 0; j < matrixXfromLU.ColumnCount; j++)
{
Assert.AreEqual(matrixX[i, j].Real, matrixXfromLU[i, j].Real, 1e-3f);
Assert.AreEqual(matrixX[i, j].Imaginary, matrixXfromLU[i, j].Imaginary, 1e-3f);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random vector (Ax=b).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<Complex32>.Build.Random(order, 1);
var resultx = factorLU.Solve(vectorb);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f);
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B).
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixX = factorLU.Solve(matrixB);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f);
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
}
/// <summary>
/// Can solve for a random vector into a result vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomVectorWhenResultVectorGiven(int order)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var vectorb = Vector<Complex32>.Build.Random(order, 1);
var vectorbCopy = vectorb.Clone();
var resultx = new DenseVector(order);
factorLU.Solve(vectorb, resultx);
Assert.AreEqual(vectorb.Count, resultx.Count);
var matrixBReconstruct = matrixA * resultx;
// Check the reconstruction.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-3f);
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-3f);
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure b didn't change.
for (var i = 0; i < vectorb.Count; i++)
{
Assert.AreEqual(vectorbCopy[i], vectorb[i]);
}
}
/// <summary>
/// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix.
/// </summary>
/// <param name="order">Matrix row number.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixB = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixBCopy = matrixB.Clone();
var matrixX = new DenseMatrix(order, order);
factorLU.Solve(matrixB, matrixX);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA * matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1e-3f);
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1e-3f);
}
}
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Make sure B didn't change.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]);
}
}
}
/// <summary>
/// Can inverse a matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(1)]
[TestCase(2)]
[TestCase(5)]
[TestCase(10)]
[TestCase(50)]
[TestCase(100)]
public void CanInverse(int order)
{
var matrixA = Matrix<Complex32>.Build.Random(order, order, 1);
var matrixACopy = matrixA.Clone();
var factorLU = matrixA.LU();
var matrixAInverse = factorLU.Inverse();
// The inverse dimension is equal A
Assert.AreEqual(matrixAInverse.RowCount, matrixAInverse.RowCount);
Assert.AreEqual(matrixAInverse.ColumnCount, matrixAInverse.ColumnCount);
var matrixIdentity = matrixA * matrixAInverse;
// Make sure A didn't change.
for (var i = 0; i < matrixA.RowCount; i++)
{
for (var j = 0; j < matrixA.ColumnCount; j++)
{
Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]);
}
}
// Check if multiplication of A and AI produced identity matrix.
for (var i = 0; i < matrixIdentity.RowCount; i++)
{
Assert.AreEqual(matrixIdentity[i, i].Real, Complex32.One.Real, 1e-3f);
Assert.AreEqual(matrixIdentity[i, i].Imaginary, Complex32.One.Imaginary, 1e-3f);
}
}
}
}
| |
// 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.Reflection;
using System.Text;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.Metadata.NativeFormat;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NativeFormat;
using Internal.TypeSystem.NoMetadata;
namespace Internal.Runtime.TypeLoader
{
internal struct NativeLayoutInfo
{
public uint Offset;
public NativeFormatModuleInfo Module;
public NativeReader Reader;
public NativeLayoutInfoLoadContext LoadContext;
}
//
// TypeBuilder per-Type state. It is attached to each TypeDesc that gets involved in type building.
//
internal class TypeBuilderState
{
internal class VTableLayoutInfo
{
public uint VTableSlot;
public RuntimeSignature MethodSignature;
public bool IsSealedVTableSlot;
}
internal class VTableSlotMapper
{
private int[] _slotMap;
private IntPtr[] _dictionarySlots;
private int _numMappingsAssigned;
public VTableSlotMapper(int numVtableSlotsInTemplateType)
{
_slotMap = new int[numVtableSlotsInTemplateType];
_dictionarySlots = new IntPtr[numVtableSlotsInTemplateType];
_numMappingsAssigned = 0;
for (int i = 0; i < numVtableSlotsInTemplateType; i++)
{
_slotMap[i] = -1;
_dictionarySlots[i] = IntPtr.Zero;
}
}
public void AddMapping(int vtableSlotInTemplateType, int vtableSlotInTargetType, IntPtr dictionaryValueInSlot)
{
Debug.Assert(_numMappingsAssigned < _slotMap.Length);
_slotMap[vtableSlotInTemplateType] = vtableSlotInTargetType;
_dictionarySlots[vtableSlotInTemplateType] = dictionaryValueInSlot;
_numMappingsAssigned++;
}
public int GetVTableSlotInTargetType(int vtableSlotInTemplateType)
{
Debug.Assert(vtableSlotInTemplateType < _slotMap.Length);
return _slotMap[vtableSlotInTemplateType];
}
public bool IsDictionarySlot(int vtableSlotInTemplateType, out IntPtr dictionaryPtrValue)
{
Debug.Assert(vtableSlotInTemplateType < _dictionarySlots.Length);
dictionaryPtrValue = _dictionarySlots[vtableSlotInTemplateType];
return _dictionarySlots[vtableSlotInTemplateType] != IntPtr.Zero;
}
public int NumSlotMappings
{
get { return _numMappingsAssigned; }
}
}
public TypeBuilderState(TypeDesc typeBeingBuilt)
{
TypeBeingBuilt = typeBeingBuilt;
}
public readonly TypeDesc TypeBeingBuilt;
//
// We cache and try to reuse the most recently used TypeSystemContext. The TypeSystemContext is used by not just type builder itself,
// but also in several random other places in reflection. There can be multiple ResolutionContexts in flight at any given moment.
// This check ensures that the RuntimeTypeHandle cache in the current resolution context is refreshed in case there were new
// types built using a different TypeSystemContext in the meantime.
// NOTE: For correctness, this value must be recomputed every time the context is recycled. This requires flushing the TypeBuilderState
// from each type that has one if context is recycled.
//
public bool AttemptedAndFailedToRetrieveTypeHandle = false;
public bool NeedsTypeHandle;
public bool HasBeenPrepared;
public RuntimeTypeHandle HalfBakedRuntimeTypeHandle;
public IntPtr HalfBakedDictionary;
public IntPtr HalfBakedSealedVTable;
private bool _templateComputed;
private bool _nativeLayoutTokenComputed;
private TypeDesc _templateType;
public TypeDesc TemplateType
{
get
{
if (!_templateComputed)
{
// Locate the template type and native layout info
_templateType = TypeBeingBuilt.Context.TemplateLookup.TryGetTypeTemplate(TypeBeingBuilt, ref _nativeLayoutInfo);
Debug.Assert(_templateType == null || !_templateType.RuntimeTypeHandle.IsNull());
_templateTypeLoaderNativeLayout = true;
_templateComputed = true;
if ((_templateType != null) && !_templateType.IsCanonicalSubtype(CanonicalFormKind.Universal))
_nativeLayoutTokenComputed = true;
}
return _templateType;
}
}
private bool _nativeLayoutComputed = false;
private bool _templateTypeLoaderNativeLayout = false;
private bool _readyToRunNativeLayout = false;
private NativeLayoutInfo _nativeLayoutInfo;
private NativeLayoutInfo _r2rnativeLayoutInfo;
private void EnsureNativeLayoutInfoComputed()
{
if (!_nativeLayoutComputed)
{
if (!_nativeLayoutTokenComputed)
{
if (!_templateComputed)
{
// Attempt to compute native layout through as a non-ReadyToRun template
object temp = this.TemplateType;
}
if (!_nativeLayoutTokenComputed)
{
TypeBeingBuilt.Context.TemplateLookup.TryGetMetadataNativeLayout(TypeBeingBuilt, out _r2rnativeLayoutInfo.Module, out _r2rnativeLayoutInfo.Offset);
if (_r2rnativeLayoutInfo.Module != null)
_readyToRunNativeLayout = true;
}
_nativeLayoutTokenComputed = true;
}
if (_nativeLayoutInfo.Module != null)
{
FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _nativeLayoutInfo);
}
if (_r2rnativeLayoutInfo.Module != null)
{
FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _r2rnativeLayoutInfo);
}
_nativeLayoutComputed = true;
}
}
/// <summary>
/// Initialize the Reader and LoadContext fields of the native layout info
/// </summary>
/// <param name="type"></param>
/// <param name="nativeLayoutInfo"></param>
private static void FinishInitNativeLayoutInfo(TypeDesc type, ref NativeLayoutInfo nativeLayoutInfo)
{
var nativeLayoutInfoLoadContext = new NativeLayoutInfoLoadContext();
nativeLayoutInfoLoadContext._typeSystemContext = type.Context;
nativeLayoutInfoLoadContext._module = nativeLayoutInfo.Module;
if (type is DefType)
{
nativeLayoutInfoLoadContext._typeArgumentHandles = ((DefType)type).Instantiation;
}
else if (type is ArrayType)
{
nativeLayoutInfoLoadContext._typeArgumentHandles = new Instantiation(new TypeDesc[] { ((ArrayType)type).ElementType });
}
else
{
Debug.Assert(false);
}
nativeLayoutInfoLoadContext._methodArgumentHandles = new Instantiation(null);
nativeLayoutInfo.Reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutInfo.Module.Handle);
nativeLayoutInfo.LoadContext = nativeLayoutInfoLoadContext;
}
public NativeLayoutInfo NativeLayoutInfo
{
get
{
EnsureNativeLayoutInfoComputed();
return _nativeLayoutInfo;
}
}
public NativeLayoutInfo R2RNativeLayoutInfo
{
get
{
EnsureNativeLayoutInfoComputed();
return _r2rnativeLayoutInfo;
}
}
public NativeParser GetParserForNativeLayoutInfo()
{
EnsureNativeLayoutInfoComputed();
if (_templateTypeLoaderNativeLayout)
return new NativeParser(_nativeLayoutInfo.Reader, _nativeLayoutInfo.Offset);
else
return default(NativeParser);
}
public NativeParser GetParserForReadyToRunNativeLayoutInfo()
{
EnsureNativeLayoutInfoComputed();
if (_readyToRunNativeLayout)
return new NativeParser(_r2rnativeLayoutInfo.Reader, _r2rnativeLayoutInfo.Offset);
else
return default(NativeParser);
}
public NativeParser GetParserForUniversalNativeLayoutInfo(out NativeLayoutInfoLoadContext universalLayoutLoadContext, out NativeLayoutInfo universalLayoutInfo)
{
universalLayoutInfo = new NativeLayoutInfo();
universalLayoutLoadContext = null;
TypeDesc universalTemplate = TypeBeingBuilt.Context.TemplateLookup.TryGetUniversalTypeTemplate(TypeBeingBuilt, ref universalLayoutInfo);
if (universalTemplate == null)
return new NativeParser();
FinishInitNativeLayoutInfo(TypeBeingBuilt, ref universalLayoutInfo);
universalLayoutLoadContext = universalLayoutInfo.LoadContext;
return new NativeParser(universalLayoutInfo.Reader, universalLayoutInfo.Offset);
}
// RuntimeInterfaces is the full list of interfaces that the type implements. It can include private internal implementation
// detail interfaces that nothing is known about.
public DefType[] RuntimeInterfaces
{
get
{
// Generic Type Definitions have no runtime interfaces
if (TypeBeingBuilt.IsGenericDefinition)
return null;
return TypeBeingBuilt.RuntimeInterfaces;
}
}
private bool? _hasDictionarySlotInVTable;
private bool ComputeHasDictionarySlotInVTable()
{
if (!TypeBeingBuilt.IsGeneric() && !(TypeBeingBuilt is ArrayType))
return false;
// Generic interfaces always have a dictionary slot
if (TypeBeingBuilt.IsInterface)
return true;
return TypeBeingBuilt.CanShareNormalGenericCode();
}
public bool HasDictionarySlotInVTable
{
get
{
if (_hasDictionarySlotInVTable == null)
{
_hasDictionarySlotInVTable = ComputeHasDictionarySlotInVTable();
}
return _hasDictionarySlotInVTable.Value;
}
}
private bool? _hasDictionaryInVTable;
private bool ComputeHasDictionaryInVTable()
{
if (!HasDictionarySlotInVTable)
return false;
if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible())
{
// Type was already constructed
return TypeBeingBuilt.RuntimeTypeHandle.GetDictionary() != IntPtr.Zero;
}
else
{
// Type is being newly constructed
if (TemplateType != null)
{
NativeParser parser = GetParserForNativeLayoutInfo();
// Template type loader case
#if GENERICS_FORCE_USG
bool isTemplateUniversalCanon = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup);
if (isTemplateUniversalCanon && type.CanShareNormalGenericCode())
{
TypeBuilderState tempState = new TypeBuilderState();
tempState.NativeLayoutInfo = new NativeLayoutInfo();
tempState.TemplateType = type.Context.TemplateLookup.TryGetNonUniversalTypeTemplate(type, ref tempState.NativeLayoutInfo);
if (tempState.TemplateType != null)
{
Debug.Assert(!tempState.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup));
parser = GetNativeLayoutInfoParser(type, ref tempState.NativeLayoutInfo);
}
}
#endif
var dictionaryLayoutParser = parser.GetParserForBagElementKind(BagElementKind.DictionaryLayout);
return !dictionaryLayoutParser.IsNull;
}
else
{
NativeParser parser = GetParserForReadyToRunNativeLayoutInfo();
// ReadyToRun case
// Dictionary is directly encoded instead of the NativeLayout being a collection of bags
if (parser.IsNull)
return false;
// First unsigned value in the native layout is the number of dictionary entries
return parser.GetUnsigned() != 0;
}
}
}
public bool HasDictionaryInVTable
{
get
{
if (_hasDictionaryInVTable == null)
_hasDictionaryInVTable = ComputeHasDictionaryInVTable();
return _hasDictionaryInVTable.Value;
}
}
private ushort? _numVTableSlots;
private ushort ComputeNumVTableSlots()
{
if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible())
{
unsafe
{
return TypeBeingBuilt.RuntimeTypeHandle.ToEETypePtr()->NumVtableSlots;
}
}
else
{
TypeDesc templateType = TypeBeingBuilt.ComputeTemplate(false);
if (templateType != null)
{
// Template type loader case
if (VTableSlotsMapping != null)
{
return checked((ushort)VTableSlotsMapping.NumSlotMappings);
}
else
{
// This should only happen for non-universal templates
Debug.Assert(TypeBeingBuilt.IsTemplateCanonical());
// Canonical template type loader case
unsafe
{
return templateType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots;
}
}
}
else if (TypeBeingBuilt.IsMdArray || (TypeBeingBuilt.IsSzArray && ((ArrayType)TypeBeingBuilt).ElementType.IsPointer))
{
// MDArray types and pointer arrays have the same vtable as the System.Array type they "derive" from.
// They do not implement the generic interfaces that make this interesting for normal arrays.
unsafe
{
return TypeBeingBuilt.BaseType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots;
}
}
else
{
// Metadata based type loading.
// Generic Type Definitions have no actual vtable entries
if (TypeBeingBuilt.IsGenericDefinition)
return 0;
// We have at least as many slots as exist on the base type.
ushort numVTableSlots = 0;
checked
{
if (TypeBeingBuilt.BaseType != null)
{
numVTableSlots = TypeBeingBuilt.BaseType.GetOrCreateTypeBuilderState().NumVTableSlots;
}
else
{
// Generic interfaces have a dictionary slot
if (TypeBeingBuilt.IsInterface && TypeBeingBuilt.HasInstantiation)
numVTableSlots = 1;
}
// Interfaces have actual vtable slots
if (TypeBeingBuilt.IsInterface)
return numVTableSlots;
foreach (MethodDesc method in TypeBeingBuilt.GetMethods())
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
if (LazyVTableResolver.MethodDefinesVTableSlot(method))
numVTableSlots++;
#else
Environment.FailFast("metadata type loader required");
#endif
}
if (HasDictionarySlotInVTable)
numVTableSlots++;
}
return numVTableSlots;
}
}
}
public ushort NumVTableSlots
{
get
{
if (_numVTableSlots == null)
_numVTableSlots = ComputeNumVTableSlots();
return _numVTableSlots.Value;
}
}
public GenericTypeDictionary Dictionary;
public int NonGcDataSize
{
get
{
DefType defType = TypeBeingBuilt as DefType;
// The NonGCStatic fields hold the class constructor data if it exists in the negative space
// of the memory region. The ClassConstructorOffset is negative, so it must be negated to
// determine the extra space that is used.
if (defType != null)
{
return defType.NonGCStaticFieldSize.AsInt - (HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0);
}
else
{
return -(HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0);
}
}
}
public int GcDataSize
{
get
{
DefType defType = TypeBeingBuilt as DefType;
if (defType != null)
{
return defType.GCStaticFieldSize.AsInt;
}
else
{
return 0;
}
}
}
public int ThreadDataSize
{
get
{
DefType defType = TypeBeingBuilt as DefType;
if (defType != null && !defType.IsGenericDefinition)
{
return defType.ThreadStaticFieldSize.AsInt;
}
else
{
// Non-DefType's and GenericEETypeDefinitions do not have static fields of any form
return 0;
}
}
}
public bool HasStaticConstructor
{
get { return TypeBeingBuilt.HasStaticConstructor; }
}
public IntPtr? ClassConstructorPointer;
public IntPtr GcStaticDesc;
public IntPtr GcStaticEEType;
public IntPtr ThreadStaticDesc;
public bool AllocatedStaticGCDesc;
public bool AllocatedThreadStaticGCDesc;
public uint ThreadStaticOffset;
public uint NumSealedVTableEntries;
public int[] GenericVarianceFlags;
// Sentinel static to allow us to initializae _instanceLayout to something
// and then detect that InstanceGCLayout should return null
private static LowLevelList<bool> s_emptyLayout = new LowLevelList<bool>();
private LowLevelList<bool> _instanceGCLayout;
/// <summary>
/// The instance gc layout of a dynamically laid out type.
/// null if one of the following is true
/// 1) For an array type:
/// - the type is a reference array
/// 2) For a generic type:
/// - the type has no GC instance fields
/// - the type already has a type handle
/// - the type has a non-universal canonical template
/// - the type has already been constructed
///
/// If the type is a valuetype array, this is the layout of the valuetype held in the array if the type has GC reference fields
/// Otherwise, it is the layout of the fields in the type.
/// </summary>
public LowLevelList<bool> InstanceGCLayout
{
get
{
if (_instanceGCLayout == null)
{
LowLevelList<bool> instanceGCLayout = null;
if (TypeBeingBuilt is ArrayType)
{
if (!IsArrayOfReferenceTypes)
{
ArrayType arrayType = (ArrayType)TypeBeingBuilt;
TypeBuilder.GCLayout elementGcLayout = GetFieldGCLayout(arrayType.ElementType);
if (!elementGcLayout.IsNone)
{
instanceGCLayout = new LowLevelList<bool>();
elementGcLayout.WriteToBitfield(instanceGCLayout, 0);
_instanceGCLayout = instanceGCLayout;
}
}
else
{
// Array of reference type returns null
_instanceGCLayout = s_emptyLayout;
}
}
else if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible() ||
TypeBeingBuilt.IsTemplateCanonical() ||
(TypeBeingBuilt is PointerType) ||
(TypeBeingBuilt is ByRefType))
{
_instanceGCLayout = s_emptyLayout;
}
else
{
// Generic Type Definitions have no gc layout
if (!(TypeBeingBuilt.IsGenericDefinition))
{
// Copy in from base type
if (!TypeBeingBuilt.IsValueType && (TypeBeingBuilt.BaseType != null))
{
DefType baseType = TypeBeingBuilt.BaseType;
// Capture the gc layout from the base type
TypeBuilder.GCLayout baseTypeLayout = GetInstanceGCLayout(baseType);
if (!baseTypeLayout.IsNone)
{
instanceGCLayout = new LowLevelList<bool>();
baseTypeLayout.WriteToBitfield(instanceGCLayout, IntPtr.Size /* account for the EEType pointer */);
}
}
foreach (FieldDesc field in GetFieldsForGCLayout())
{
if (field.IsStatic)
continue;
if (field.IsLiteral)
continue;
TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType);
if (!fieldGcLayout.IsNone)
{
if (instanceGCLayout == null)
instanceGCLayout = new LowLevelList<bool>();
fieldGcLayout.WriteToBitfield(instanceGCLayout, field.Offset.AsInt);
}
}
if ((instanceGCLayout != null) && instanceGCLayout.HasSetBits())
{
// When bits are set in the instance GC layout, it implies that the type contains GC refs,
// which implies that the type size is pointer-aligned. In this case consumers assume that
// the type size can be computed by multiplying the bitfield size by the pointer size. If
// necessary, expand the bitfield to ensure that this invariant holds.
// Valuetypes with gc fields must be aligned on at least pointer boundaries
Debug.Assert(!TypeBeingBuilt.IsValueType || (FieldAlignment.Value >= TypeBeingBuilt.Context.Target.PointerSize));
// Valuetypes with gc fields must have a type size which is aligned on an IntPtr boundary.
Debug.Assert(!TypeBeingBuilt.IsValueType || ((TypeSize.Value & (IntPtr.Size - 1)) == 0));
int impliedBitCount = (TypeSize.Value + IntPtr.Size - 1) / IntPtr.Size;
Debug.Assert(instanceGCLayout.Count <= impliedBitCount);
instanceGCLayout.Expand(impliedBitCount);
Debug.Assert(instanceGCLayout.Count == impliedBitCount);
}
}
if (instanceGCLayout == null)
_instanceGCLayout = s_emptyLayout;
else
_instanceGCLayout = instanceGCLayout;
}
}
if (_instanceGCLayout == s_emptyLayout)
return null;
else
return _instanceGCLayout;
}
}
public LowLevelList<bool> StaticGCLayout;
public LowLevelList<bool> ThreadStaticGCLayout;
private bool _staticGCLayoutPrepared;
/// <summary>
/// Prepare the StaticGCLayout/ThreadStaticGCLayout/GcStaticDesc/ThreadStaticDesc fields by
/// reading native layout or metadata as appropriate. This method should only be called for types which
/// are actually to be created.
/// </summary>
public void PrepareStaticGCLayout()
{
if (!_staticGCLayoutPrepared)
{
_staticGCLayoutPrepared = true;
DefType defType = TypeBeingBuilt as DefType;
if (defType == null)
{
// Array/pointer types do not have static fields
}
else if (defType.IsTemplateCanonical())
{
// Canonical templates get their layout directly from the NativeLayoutInfo.
// Parse it and pull that info out here.
NativeParser typeInfoParser = GetParserForNativeLayoutInfo();
BagElementKind kind;
while ((kind = typeInfoParser.GetBagElementKind()) != BagElementKind.End)
{
switch (kind)
{
case BagElementKind.GcStaticDesc:
GcStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
case BagElementKind.ThreadStaticDesc:
ThreadStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
case BagElementKind.GcStaticEEType:
GcStaticEEType = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned());
break;
default:
typeInfoParser.SkipInteger();
break;
}
}
}
else
{
// Compute GC layout boolean array from field information.
IEnumerable<FieldDesc> fields = GetFieldsForGCLayout();
LowLevelList<bool> threadStaticLayout = null;
LowLevelList<bool> gcStaticLayout = null;
foreach (FieldDesc field in fields)
{
if (!field.IsStatic)
continue;
if (field.IsLiteral)
continue;
LowLevelList<bool> gcLayoutInfo = null;
if (field.IsThreadStatic)
{
if (threadStaticLayout == null)
threadStaticLayout = new LowLevelList<bool>();
gcLayoutInfo = threadStaticLayout;
}
else if (field.HasGCStaticBase)
{
if (gcStaticLayout == null)
gcStaticLayout = new LowLevelList<bool>();
gcLayoutInfo = gcStaticLayout;
}
else
{
// Non-GC static no need to record information
continue;
}
TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType);
fieldGcLayout.WriteToBitfield(gcLayoutInfo, field.Offset.AsInt);
}
if (gcStaticLayout != null && gcStaticLayout.Count > 0)
StaticGCLayout = gcStaticLayout;
if (threadStaticLayout != null && threadStaticLayout.Count > 0)
ThreadStaticGCLayout = threadStaticLayout;
}
}
}
/// <summary>
/// Get an enumerable list of the fields used for dynamic gc layout calculation.
/// </summary>
private IEnumerable<FieldDesc> GetFieldsForGCLayout()
{
DefType defType = (DefType)TypeBeingBuilt;
IEnumerable<FieldDesc> fields;
if (defType.ComputeTemplate(false) != null)
{
// we have native layout and a template. Use the NativeLayoutFields as that is the only complete
// description of the fields available. (There may be metadata fields, but those aren't guaranteed
// to be a complete set of fields due to reflection reduction.
NativeLayoutFieldAlgorithm.EnsureFieldLayoutLoadedForGenericType(defType);
fields = defType.NativeLayoutFields;
}
else
{
// The metadata case. We're loading the type from regular metadata, so use the regular metadata fields
fields = defType.GetFields();
}
return fields;
}
// Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases
// Only to be used for getting the instance layout of non-valuetypes.
/// <summary>
/// Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases
/// Only to be used for getting the instance layout of non-valuetypes that are used as base types
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type)
{
Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Any));
Debug.Assert(!type.IsValueType);
if (type.RetrieveRuntimeTypeHandleIfPossible())
{
return new TypeBuilder.GCLayout(type.RuntimeTypeHandle);
}
if (type.IsTemplateCanonical())
{
var templateType = type.ComputeTemplate();
bool success = templateType.RetrieveRuntimeTypeHandleIfPossible();
Debug.Assert(success && !templateType.RuntimeTypeHandle.IsNull());
return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle);
}
else
{
TypeBuilderState state = type.GetOrCreateTypeBuilderState();
if (state.InstanceGCLayout == null)
return TypeBuilder.GCLayout.None;
else
return new TypeBuilder.GCLayout(state.InstanceGCLayout, true);
}
}
/// <summary>
/// Get the GC layout of a type when used as a field.
/// NOTE: if the fieldtype is a reference type, this function will return GCLayout.None
/// Consumers of the api must handle that special case.
/// </summary>
private unsafe TypeBuilder.GCLayout GetFieldGCLayout(TypeDesc fieldType)
{
if (!fieldType.IsValueType)
{
if (fieldType.IsPointer)
return TypeBuilder.GCLayout.None;
else
return TypeBuilder.GCLayout.SingleReference;
}
// Is this a type that already exists? If so, get its gclayout from the EEType directly
if (fieldType.RetrieveRuntimeTypeHandleIfPossible())
{
return new TypeBuilder.GCLayout(fieldType.RuntimeTypeHandle);
}
// The type of the field must be a valuetype that is dynamically being constructed
if (fieldType.IsTemplateCanonical())
{
// Pull the GC Desc from the canonical instantiation
TypeDesc templateType = fieldType.ComputeTemplate();
bool success = templateType.RetrieveRuntimeTypeHandleIfPossible();
Debug.Assert(success);
return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle);
}
else
{
// Use the type builder state's computed InstanceGCLayout
var instanceGCLayout = fieldType.GetOrCreateTypeBuilderState().InstanceGCLayout;
if (instanceGCLayout == null)
return TypeBuilder.GCLayout.None;
return new TypeBuilder.GCLayout(instanceGCLayout, false /* Always represents a valuetype as the reference type case
is handled above with the GCLayout.SingleReference return */);
}
}
public bool IsArrayOfReferenceTypes
{
get
{
ArrayType typeAsArrayType = TypeBeingBuilt as ArrayType;
if (typeAsArrayType != null)
return !typeAsArrayType.ParameterType.IsValueType && !typeAsArrayType.ParameterType.IsPointer;
else
return false;
}
}
// Rank for arrays, -1 is used for an SzArray, and a positive number for a multidimensional array.
public int? ArrayRank
{
get
{
if (!TypeBeingBuilt.IsArray)
return null;
else if (TypeBeingBuilt.IsSzArray)
return -1;
else
{
Debug.Assert(TypeBeingBuilt.IsMdArray);
return ((ArrayType)TypeBeingBuilt).Rank;
}
}
}
public int? BaseTypeSize
{
get
{
if (TypeBeingBuilt.BaseType == null)
{
return null;
}
else
{
return TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt;
}
}
}
public int? TypeSize
{
get
{
DefType defType = TypeBeingBuilt as DefType;
if (defType != null)
{
// Generic Type Definition EETypes do not have size
if (defType.IsGenericDefinition)
return null;
if (defType.IsValueType)
{
return defType.InstanceFieldSize.AsInt;
}
else
{
if (defType.IsInterface)
return IntPtr.Size;
return defType.InstanceByteCountUnaligned.AsInt;
}
}
else if (TypeBeingBuilt is ArrayType)
{
int basicArraySize = TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt;
if (TypeBeingBuilt.IsMdArray)
{
// MD Arrays are arranged like normal arrays, but they also have 2 int's per rank for the individual dimension loBounds and range.
basicArraySize += ((ArrayType)TypeBeingBuilt).Rank * sizeof(int) * 2;
}
return basicArraySize;
}
else
{
return null;
}
}
}
public int? UnalignedTypeSize
{
get
{
DefType defType = TypeBeingBuilt as DefType;
if (defType != null)
{
return defType.InstanceByteCountUnaligned.AsInt;
}
else if (TypeBeingBuilt is ArrayType)
{
// Arrays use the same algorithm for TypeSize as for UnalignedTypeSize
return TypeSize;
}
else
{
return 0;
}
}
}
public int? FieldAlignment
{
get
{
if (TypeBeingBuilt is DefType)
{
return checked((ushort)((DefType)TypeBeingBuilt).InstanceFieldAlignment.AsInt);
}
else if (TypeBeingBuilt is ArrayType)
{
ArrayType arrayType = (ArrayType)TypeBeingBuilt;
if (arrayType.ElementType is DefType)
{
return checked((ushort)((DefType)arrayType.ElementType).InstanceFieldAlignment.AsInt);
}
else
{
return (ushort)arrayType.Context.Target.PointerSize;
}
}
else if (TypeBeingBuilt is PointerType || TypeBeingBuilt is ByRefType)
{
return (ushort)TypeBeingBuilt.Context.Target.PointerSize;
}
else
{
return null;
}
}
}
public ushort? ComponentSize
{
get
{
ArrayType arrayType = TypeBeingBuilt as ArrayType;
if (arrayType != null)
{
if (arrayType.ElementType is DefType)
{
return checked((ushort)((DefType)arrayType.ElementType).InstanceFieldSize.AsInt);
}
else
{
return (ushort)arrayType.Context.Target.PointerSize;
}
}
else
{
return null;
}
}
}
public bool IsHFA
{
get
{
#if ARM
if (TypeBeingBuilt is DefType)
{
return ((DefType)TypeBeingBuilt).IsHfa;
}
else
{
return false;
}
#else
// On Non-ARM platforms, HFA'ness is not encoded in the EEType as it doesn't effect ABI
return false;
#endif
}
}
public VTableLayoutInfo[] VTableMethodSignatures;
public int NumSealedVTableMethodSignatures;
public VTableSlotMapper VTableSlotsMapping;
#if GENERICS_FORCE_USG
public TypeDesc NonUniversalTemplateType;
public int NonUniversalInstanceGCDescSize;
public IntPtr NonUniversalInstanceGCDesc;
public IntPtr NonUniversalStaticGCDesc;
public IntPtr NonUniversalThreadStaticGCDesc;
#endif
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Fabric;
using System.Fabric.Query;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ServiceFabric.Services.Client;
using Orleans.Clustering.ServiceFabric.Models;
namespace Orleans.Clustering.ServiceFabric.Utilities
{
internal class FabricQueryManager : IFabricQueryManager
{
private readonly ConcurrentDictionary<Uri, ConcurrentDictionary<ServicePartitionKey, ResolvedServicePartition>> previousResolves =
new ConcurrentDictionary<Uri, ConcurrentDictionary<ServicePartitionKey, ResolvedServicePartition>>();
private readonly FabricClient fabricClient;
private readonly IServicePartitionResolver resolver;
private readonly TimeSpan timeoutPerAttempt;
private readonly TimeSpan maxBackoffInterval;
public FabricQueryManager(
FabricClient fabricClient,
IServicePartitionResolver resolver)
{
this.fabricClient = fabricClient;
this.resolver = resolver;
this.timeoutPerAttempt = TimeSpan.FromSeconds(30);
this.maxBackoffInterval = TimeSpan.FromSeconds(90);
}
/// <inheritdoc />
public void UnregisterPartitionChangeHandler(long id)
{
this.fabricClient.ServiceManager.UnregisterServicePartitionResolutionChangeHandler(id);
}
/// <inheritdoc />
public long RegisterPartitionChangeHandler(
Uri serviceName,
IResolvedServicePartition servicePartition,
FabricPartitionResolutionChangeHandler handler)
{
var partition = servicePartition as ResolvedServicePartitionWrapper;
if (partition == null)
{
throw new ArgumentException(
string.Format(
"Only partitions of type {0} are supported. Provided type {1} is not supported.",
nameof(ResolvedServicePartitionWrapper),
servicePartition.GetType()),
nameof(servicePartition));
}
// Wrap the provided handler so that it's compatible with Service Fabric.
void ChangeHandler(FabricClient source, long id, ServicePartitionResolutionChange args)
{
ServicePartitionSilos result = null;
if (!args.HasException)
{
result = new ServicePartitionSilos(
new ResolvedServicePartitionWrapper(args.Result),
args.Result.GetPartitionEndpoints());
}
handler(id, new FabricPartitionResolutionChange(result, args.Exception));
}
var sm = this.fabricClient.ServiceManager;
switch (servicePartition.Kind)
{
case ServicePartitionKind.Int64Range:
return sm.RegisterServicePartitionResolutionChangeHandler(
serviceName,
((Int64RangePartitionInformation) partition.Partition.Info).LowKey,
ChangeHandler);
case ServicePartitionKind.Named:
return sm.RegisterServicePartitionResolutionChangeHandler(
serviceName,
((NamedPartitionInformation) partition.Partition.Info).Name,
ChangeHandler);
case ServicePartitionKind.Singleton:
return sm.RegisterServicePartitionResolutionChangeHandler(serviceName, ChangeHandler);
default:
throw new ArgumentOutOfRangeException(
nameof(servicePartition),
$"Partition kind {servicePartition.Kind} is not supported");
}
}
/// <inheritdoc />
public async Task<ServicePartitionSilos[]> ResolveSilos(Uri serviceName)
{
var fabricPartitions = await this.QueryServicePartitions(serviceName);
var resolvedPartitions = new List<ServicePartitionSilos>(fabricPartitions.Count);
foreach (var fabricPartition in fabricPartitions)
{
var partitionKey = fabricPartition.PartitionInformation.GetPartitionKey();
var resolvedPartition = await this.ResolvePartition(serviceName, partitionKey, CancellationToken.None);
resolvedPartitions.Add(resolvedPartition);
}
return resolvedPartitions.ToArray();
}
/// <inheritdoc />
public async Task<ServicePartitionSilos> ResolvePartition(
Uri serviceName,
ServicePartitionKey partitionKey,
CancellationToken cancellationToken)
{
ResolvedServicePartition result;
var cache = this.previousResolves.GetOrAdd(serviceName, CreateCache);
if (cache.TryGetValue(partitionKey, out var previousResult))
{
// Re-resolve the partition and avoid caching.
result = await this.resolver.ResolveAsync(
previousResult,
this.timeoutPerAttempt,
this.maxBackoffInterval,
cancellationToken);
}
else
{
// Perform an initial resolution for the partition.
result = await this.resolver.ResolveAsync(
serviceName,
partitionKey,
this.timeoutPerAttempt,
this.maxBackoffInterval,
cancellationToken);
}
// Cache the results of this resolution to provide to the next resolution call.
cache.AddOrUpdate(
partitionKey,
_ => result,
(key, existing) => existing.CompareVersion(result) < 0 ? result : existing);
return new ServicePartitionSilos(
new ResolvedServicePartitionWrapper(result),
result.GetPartitionEndpoints());
ConcurrentDictionary<ServicePartitionKey, ResolvedServicePartition> CreateCache(Uri uri)
{
return new ConcurrentDictionary<ServicePartitionKey, ResolvedServicePartition>(ServicePartitionKeyComparer.Instance);
}
}
/// <summary>
/// Returns the list of Service Fabric partitions for the given service.
/// </summary>
/// <returns>The list of Service Fabric partitions for the given service.</returns>
private async Task<List<Partition>> QueryServicePartitions(Uri serviceName)
{
var partitions = new List<Partition>();
var continuationToken = default(string);
do
{
var batch = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceName, continuationToken);
if (batch.Count > 0) partitions.AddRange(batch);
continuationToken = batch.ContinuationToken;
} while (!string.IsNullOrWhiteSpace(continuationToken));
partitions.Sort(
(partition1, partition2) =>
partition1.PartitionInformation.Id.CompareTo(partition2.PartitionInformation.Id));
return partitions;
}
private class ResolvedServicePartitionWrapper : IResolvedServicePartition
{
public ResolvedServicePartitionWrapper(ResolvedServicePartition partition)
{
this.Partition = partition;
}
public ResolvedServicePartition Partition { get; }
public Guid Id => this.Partition.Info.Id;
public ServicePartitionKind Kind => this.Partition.Info.Kind;
public bool IsSamePartitionAs(IResolvedServicePartition other)
{
if (other is ResolvedServicePartitionWrapper otherWrapper)
{
return this.Partition.IsSamePartitionAs(otherWrapper.Partition);
}
return false;
}
public override string ToString() => this.Partition.ToPartitionString();
}
/// <summary>
/// Equality comparer for <see cref="ServicePartitionKey"/>.
/// </summary>
private struct ServicePartitionKeyComparer : IEqualityComparer<ServicePartitionKey>
{
/// <summary>
/// Gets a singleton instance of this class.
/// </summary>
public static ServicePartitionKeyComparer Instance { get; } = new ServicePartitionKeyComparer();
/// <inheritdoc />
public bool Equals(ServicePartitionKey x, ServicePartitionKey y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(x, null)) return false;
if (ReferenceEquals(y, null)) return false;
if (x.Kind != y.Kind) return false;
switch (x.Kind)
{
case ServicePartitionKind.Int64Range:
return (long) x.Value == (long) y.Value;
case ServicePartitionKind.Named:
return string.Equals(x.Value as string, y.Value as string, StringComparison.Ordinal);
case ServicePartitionKind.Singleton:
return true;
default:
ThrowKindOutOfRange(x);
return false;
}
}
/// <inheritdoc />
public int GetHashCode(ServicePartitionKey obj)
{
switch (obj.Kind)
{
case ServicePartitionKind.Int64Range:
return ((long) obj.Value).GetHashCode();
case ServicePartitionKind.Named:
return ((string) obj.Value).GetHashCode();
case ServicePartitionKind.Singleton:
return 0;
default:
ThrowKindOutOfRange(obj);
return -1;
}
}
private static void ThrowKindOutOfRange(ServicePartitionKey x)
{
throw new ArgumentOutOfRangeException(nameof(x), $"Partition kind {x.Kind} is not supported");
}
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace MahApps.Metro.Controls
{
/// <summary>
/// enumeration for the different transition types
/// </summary>
public enum TransitionType
{
/// <summary>
/// Use the VisualState DefaultTransition
/// </summary>
Default,
/// <summary>
/// Use the VisualState Normal
/// </summary>
Normal,
/// <summary>
/// Use the VisualState UpTransition
/// </summary>
Up,
/// <summary>
/// Use the VisualState DownTransition
/// </summary>
Down,
/// <summary>
/// Use the VisualState RightTransition
/// </summary>
Right,
/// <summary>
/// Use the VisualState RightReplaceTransition
/// </summary>
RightReplace,
/// <summary>
/// Use the VisualState LeftTransition
/// </summary>
Left,
/// <summary>
/// Use the VisualState LeftReplaceTransition
/// </summary>
LeftReplace,
/// <summary>
/// Use a custom VisualState, the name must be set using CustomVisualStatesName property
/// </summary>
Custom
}
/// <summary>
/// A ContentControl that animates content as it loads and unloads.
/// </summary>
public class TransitioningContentControl : ContentControl
{
internal const string PresentationGroup = "PresentationStates";
internal const string NormalState = "Normal";
internal const string PreviousContentPresentationSitePartName = "PreviousContentPresentationSite";
internal const string CurrentContentPresentationSitePartName = "CurrentContentPresentationSite";
private ContentPresenter CurrentContentPresentationSite { get; set; }
private ContentPresenter PreviousContentPresentationSite { get; set; }
private bool _allowIsTransitioningWrite;
private Storyboard _currentTransition;
public event RoutedEventHandler TransitionCompleted;
public const TransitionType DefaultTransitionState = TransitionType.Default;
public static readonly DependencyProperty IsTransitioningProperty = DependencyProperty.Register("IsTransitioning", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(OnIsTransitioningPropertyChanged));
public static readonly DependencyProperty TransitionProperty = DependencyProperty.Register("Transition", typeof(TransitionType), typeof(TransitioningContentControl), new FrameworkPropertyMetadata(TransitionType.Default, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.Inherits, OnTransitionPropertyChanged));
public static readonly DependencyProperty RestartTransitionOnContentChangeProperty = DependencyProperty.Register("RestartTransitionOnContentChange", typeof(bool), typeof(TransitioningContentControl), new PropertyMetadata(false, OnRestartTransitionOnContentChangePropertyChanged));
public static readonly DependencyProperty CustomVisualStatesProperty = DependencyProperty.Register("CustomVisualStates", typeof(ObservableCollection<VisualState>), typeof(TransitioningContentControl), new PropertyMetadata(null));
public static readonly DependencyProperty CustomVisualStatesNameProperty = DependencyProperty.Register("CustomVisualStatesName", typeof(string), typeof(TransitioningContentControl), new PropertyMetadata("CustomTransition"));
public ObservableCollection<VisualState> CustomVisualStates
{
get { return (ObservableCollection<VisualState>)this.GetValue(CustomVisualStatesProperty); }
set { this.SetValue(CustomVisualStatesProperty, value); }
}
/// <summary>
/// Gets or sets the name of the custom transition visual state.
/// </summary>
public string CustomVisualStatesName
{
get { return (string)this.GetValue(CustomVisualStatesNameProperty); }
set { this.SetValue(CustomVisualStatesNameProperty, value); }
}
/// <summary>
/// Gets/sets if the content is transitioning.
/// </summary>
public bool IsTransitioning
{
get { return (bool)GetValue(IsTransitioningProperty); }
private set
{
_allowIsTransitioningWrite = true;
SetValue(IsTransitioningProperty, value);
_allowIsTransitioningWrite = false;
}
}
public TransitionType Transition
{
get { return (TransitionType)GetValue(TransitionProperty); }
set { SetValue(TransitionProperty, value); }
}
public bool RestartTransitionOnContentChange
{
get { return (bool)GetValue(RestartTransitionOnContentChangeProperty); }
set { SetValue(RestartTransitionOnContentChangeProperty, value); }
}
private static void OnIsTransitioningPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
if (!source._allowIsTransitioningWrite)
{
source.IsTransitioning = (bool)e.OldValue;
throw new InvalidOperationException();
}
}
private Storyboard CurrentTransition
{
get { return _currentTransition; }
set
{
// decouple event
if (_currentTransition != null)
{
_currentTransition.Completed -= OnTransitionCompleted;
}
_currentTransition = value;
if (_currentTransition != null)
{
_currentTransition.Completed += OnTransitionCompleted;
}
}
}
private static void OnTransitionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var source = (TransitioningContentControl)d;
var oldTransition = (TransitionType)e.OldValue;
var newTransition = (TransitionType)e.NewValue;
if (source.IsTransitioning)
{
source.AbortTransition();
}
// find new transition
Storyboard newStoryboard = source.GetStoryboard(newTransition);
// unable to find the transition.
if (newStoryboard == null)
{
// could be during initialization of xaml that presentationgroups was not yet defined
if (VisualStates.TryGetVisualStateGroup(source, PresentationGroup) == null)
{
// will delay check
source.CurrentTransition = null;
}
else
{
// revert to old value
source.SetValue(TransitionProperty, oldTransition);
throw new ArgumentException(
string.Format(CultureInfo.CurrentCulture, "Temporary removed exception message", newTransition));
}
}
else
{
source.CurrentTransition = newStoryboard;
}
}
private static void OnRestartTransitionOnContentChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((TransitioningContentControl)d).OnRestartTransitionOnContentChangeChanged((bool)e.OldValue, (bool)e.NewValue);
}
protected virtual void OnRestartTransitionOnContentChangeChanged(bool oldValue, bool newValue)
{
}
public TransitioningContentControl()
{
this.CustomVisualStates = new ObservableCollection<VisualState>();
DefaultStyleKey = typeof(TransitioningContentControl);
}
public override void OnApplyTemplate()
{
if (IsTransitioning)
{
AbortTransition();
}
if (this.CustomVisualStates != null && this.CustomVisualStates.Any())
{
var presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
if (presentationGroup != null)
{
foreach (var state in this.CustomVisualStates)
{
presentationGroup.States.Add(state);
}
}
}
base.OnApplyTemplate();
PreviousContentPresentationSite = GetTemplateChild(PreviousContentPresentationSitePartName) as ContentPresenter;
CurrentContentPresentationSite = GetTemplateChild(CurrentContentPresentationSitePartName) as ContentPresenter;
if (CurrentContentPresentationSite != null)
{
if (ContentTemplateSelector != null)
CurrentContentPresentationSite.ContentTemplate = ContentTemplateSelector.SelectTemplate(Content, this);
CurrentContentPresentationSite.Content = Content;
}
// hookup currenttransition
Storyboard transition = GetStoryboard(Transition);
CurrentTransition = transition;
if (transition == null)
{
var invalidTransition = Transition;
// revert to default
Transition = DefaultTransitionState;
throw new ArgumentException(string.Format("'{0}' Transition could not be found!", invalidTransition), "Transition");
}
VisualStateManager.GoToState(this, NormalState, false);
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
StartTransition(oldContent, newContent);
}
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "newContent", Justification = "Should be used in the future.")]
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed -= OnTransitionCompleted;
}
if (ContentTemplateSelector != null)
{
PreviousContentPresentationSite.ContentTemplate = ContentTemplateSelector.SelectTemplate(oldContent, this);
CurrentContentPresentationSite.ContentTemplate = ContentTemplateSelector.SelectTemplate(newContent, this);
}
CurrentContentPresentationSite.Content = newContent;
PreviousContentPresentationSite.Content = oldContent;
// and start a new transition
if (!IsTransitioning || RestartTransitionOnContentChange)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed += OnTransitionCompleted;
}
IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, GetTransitionName(Transition), true);
}
}
}
/// <summary>
/// Reload the current transition if the content is the same.
/// </summary>
public void ReloadTransition()
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed -= OnTransitionCompleted;
}
if (!IsTransitioning || RestartTransitionOnContentChange)
{
if (RestartTransitionOnContentChange)
{
CurrentTransition.Completed += OnTransitionCompleted;
}
IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, GetTransitionName(Transition), true);
}
}
}
private void OnTransitionCompleted(object sender, EventArgs e)
{
AbortTransition();
RoutedEventHandler handler = TransitionCompleted;
if (handler != null)
{
handler(this, new RoutedEventArgs());
}
}
public void AbortTransition()
{
// go to normal state and release our hold on the old content.
VisualStateManager.GoToState(this, NormalState, false);
IsTransitioning = false;
if (PreviousContentPresentationSite != null)
{
PreviousContentPresentationSite.Content = null;
}
}
private Storyboard GetStoryboard(TransitionType newTransition)
{
VisualStateGroup presentationGroup = VisualStates.TryGetVisualStateGroup(this, PresentationGroup);
Storyboard newStoryboard = null;
if (presentationGroup != null)
{
var transitionName = GetTransitionName(newTransition);
newStoryboard = presentationGroup.States
.OfType<VisualState>()
.Where(state => state.Name == transitionName)
.Select(state => state.Storyboard)
.FirstOrDefault();
}
return newStoryboard;
}
private string GetTransitionName(TransitionType transition)
{
switch (transition) {
default:
case TransitionType.Default:
return "DefaultTransition";
case TransitionType.Normal:
return "Normal";
case TransitionType.Up:
return "UpTransition";
case TransitionType.Down:
return "DownTransition";
case TransitionType.Right:
return "RightTransition";
case TransitionType.RightReplace:
return "RightReplaceTransition";
case TransitionType.Left:
return "LeftTransition";
case TransitionType.LeftReplace:
return "LeftReplaceTransition";
case TransitionType.Custom:
return CustomVisualStatesName;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
namespace AutoMapper
{
public class PropertyMap
{
private readonly LinkedList<IValueResolver> _sourceValueResolvers = new LinkedList<IValueResolver>();
private readonly IList<Type> _valueFormattersToSkip = new List<Type>();
private readonly IList<IValueFormatter> _valueFormatters = new List<IValueFormatter>();
private bool _ignored;
private int _mappingOrder;
private bool _hasCustomValueResolver;
private IValueResolver _customResolver;
private IValueResolver _customMemberResolver;
private object _nullSubstitute;
private bool _sealed;
private IValueResolver[] _cachedResolvers;
private Func<ResolutionContext, bool> _condition;
private MemberInfo _sourceMember;
public PropertyMap(IMemberAccessor destinationProperty)
{
DestinationProperty = destinationProperty;
}
public IMemberAccessor DestinationProperty { get; private set; }
public LambdaExpression CustomExpression { get; private set; }
public MemberInfo SourceMember
{
get
{
if (_sourceMember == null)
{
var sourceMemberGetter = GetSourceValueResolvers()
.OfType<IMemberGetter>().LastOrDefault();
return sourceMemberGetter == null ? null : sourceMemberGetter.MemberInfo;
}
else
{
return _sourceMember;
}
}
internal set
{
_sourceMember = value;
}
}
public bool CanBeSet
{
get
{
return !(DestinationProperty is PropertyAccessor) ||
((PropertyAccessor)DestinationProperty).HasSetter;
}
}
public bool UseDestinationValue { get; set; }
internal bool HasCustomValueResolver
{
get { return _hasCustomValueResolver; }
}
public IEnumerable<IValueResolver> GetSourceValueResolvers()
{
if (_customMemberResolver != null)
yield return _customMemberResolver;
if (_customResolver != null)
yield return _customResolver;
foreach (var resolver in _sourceValueResolvers)
{
yield return resolver;
}
if (_nullSubstitute != null)
yield return new NullReplacementMethod(_nullSubstitute);
}
public void RemoveLastResolver()
{
_sourceValueResolvers.RemoveLast();
}
public ResolutionResult ResolveValue(ResolutionContext context)
{
Seal();
var result = new ResolutionResult(context);
return _cachedResolvers.Aggregate(result, (current, resolver) => resolver.Resolve(current));
}
internal void Seal()
{
if (_sealed)
{
return;
}
_cachedResolvers = GetSourceValueResolvers().ToArray();
_sealed = true;
}
public void ChainResolver(IValueResolver IValueResolver)
{
_sourceValueResolvers.AddLast(IValueResolver);
}
public void AddFormatterToSkip<TValueFormatter>() where TValueFormatter : IValueFormatter
{
_valueFormattersToSkip.Add(typeof(TValueFormatter));
}
public bool FormattersToSkipContains(Type valueFormatterType)
{
return _valueFormattersToSkip.Contains(valueFormatterType);
}
public void AddFormatter(IValueFormatter valueFormatter)
{
_valueFormatters.Add(valueFormatter);
}
public IValueFormatter[] GetFormatters()
{
return _valueFormatters.ToArray();
}
public void AssignCustomValueResolver(IValueResolver valueResolver)
{
_ignored = false;
_customResolver = valueResolver;
ResetSourceMemberChain();
_hasCustomValueResolver = true;
}
public void ChainTypeMemberForResolver(IValueResolver valueResolver)
{
ResetSourceMemberChain();
_customMemberResolver = valueResolver;
}
public void ChainConstructorForResolver(IValueResolver valueResolver)
{
_customResolver = valueResolver;
}
public void Ignore()
{
_ignored = true;
}
public bool IsIgnored()
{
return _ignored;
}
public void SetMappingOrder(int mappingOrder)
{
_mappingOrder = mappingOrder;
}
public int GetMappingOrder()
{
return _mappingOrder;
}
public bool IsMapped()
{
return _sourceValueResolvers.Count > 0 || _hasCustomValueResolver || _ignored;
}
public bool CanResolveValue()
{
return (_sourceValueResolvers.Count > 0 || _hasCustomValueResolver || UseDestinationValue) && !_ignored;
}
public void RemoveLastFormatter()
{
_valueFormatters.RemoveAt(_valueFormatters.Count - 1);
}
public void SetNullSubstitute(object nullSubstitute)
{
_nullSubstitute = nullSubstitute;
}
private void ResetSourceMemberChain()
{
_sourceValueResolvers.Clear();
}
public bool Equals(PropertyMap other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.DestinationProperty, DestinationProperty);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(PropertyMap)) return false;
return Equals((PropertyMap)obj);
}
public override int GetHashCode()
{
return DestinationProperty.GetHashCode();
}
public void ApplyCondition(Func<ResolutionContext, bool> condition)
{
_condition = condition;
}
public bool ShouldAssignValue(ResolutionContext context)
{
return _condition == null || _condition(context);
}
public void SetCustomValueResolverExpression<TSource, TMember>(Expression<Func<TSource, TMember>> sourceMember)
{
if (sourceMember.Body is MemberExpression)
{
SourceMember = ((MemberExpression) sourceMember.Body).Member;
}
CustomExpression = sourceMember;
AssignCustomValueResolver(new DelegateBasedResolver<TSource, TMember>(sourceMember.Compile()));
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 C5;
using NUnit.Framework;
using SCG = System.Collections.Generic;
namespace C5UnitTests
{
class SC : SCG.IComparer<string>
{
public int Compare(string a, string b)
{
return a.CompareTo(b);
}
public void appl(String s)
{
System.Console.WriteLine("--{0}", s);
}
}
class TenEqualityComparer : SCG.IEqualityComparer<int>, SCG.IComparer<int>
{
TenEqualityComparer() { }
public static TenEqualityComparer Default { get { return new TenEqualityComparer(); } }
public int GetHashCode(int item) { return (item / 10).GetHashCode(); }
public bool Equals(int item1, int item2) { return item1 / 10 == item2 / 10; }
public int Compare(int a, int b) { return (a / 10).CompareTo(b / 10); }
}
class IC : SCG.IComparer<int>, IComparable<int>, SCG.IComparer<IC>, IComparable<IC>
{
public int Compare(int a, int b)
{
return a > b ? 1 : a < b ? -1 : 0;
}
public int Compare(IC a, IC b)
{
return a._i > b._i ? 1 : a._i < b._i ? -1 : 0;
}
private int _i;
public int i
{
get { return _i; }
set { _i = value; }
}
public IC() { }
public IC(int i) { _i = i; }
public int CompareTo(int that) { return _i > that ? 1 : _i < that ? -1 : 0; }
public bool Equals(int that) { return _i == that; }
public int CompareTo(IC that) { return _i > that._i ? 1 : _i < that._i ? -1 : 0; }
public bool Equals(IC that) { return _i == that._i; }
public static bool eq(SCG.IEnumerable<int> me, params int[] that)
{
int i = 0, maxind = that.Length - 1;
foreach (int item in me)
if (i > maxind || item != that[i++])
return false;
return i == maxind + 1;
}
public static bool seteq(ICollectionValue<int> me, params int[] that)
{
int[] me2 = me.ToArray();
Array.Sort(me2);
int i = 0, maxind = that.Length - 1;
foreach (int item in me2)
if (i > maxind || item != that[i++])
return false;
return i == maxind + 1;
}
public static bool seteq(ICollectionValue<KeyValuePair<int, int>> me, params int[] that)
{
ArrayList<KeyValuePair<int, int>> first = new ArrayList<KeyValuePair<int, int>>();
first.AddAll(me);
ArrayList<KeyValuePair<int, int>> other = new ArrayList<KeyValuePair<int, int>>();
for (int i = 0; i < that.Length; i += 2)
{
other.Add(new KeyValuePair<int, int>(that[i], that[i + 1]));
}
return other.UnsequencedEquals(first);
}
}
class RevIC : SCG.IComparer<int>
{
public int Compare(int a, int b)
{
return a > b ? -1 : a < b ? 1 : 0;
}
}
public class FunEnumerable : SCG.IEnumerable<int>
{
int size;
Fun<int, int> f;
public FunEnumerable(int size, Fun<int, int> f)
{
this.size = size; this.f = f;
}
public SCG.IEnumerator<int> GetEnumerator()
{
for (int i = 0; i < size; i++)
yield return f(i);
}
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
public class BadEnumerableException : Exception { }
public class BadEnumerable<T> : CollectionValueBase<T>, ICollectionValue<T>
{
T[] contents;
Exception exception;
public BadEnumerable(Exception exception, params T[] contents)
{
this.contents = (T[])contents.Clone();
this.exception = exception;
}
public override SCG.IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < contents.Length; i++)
yield return contents[i];
throw exception;
}
public override bool IsEmpty { get { return false; } }
public override int Count { get { return contents.Length + 1; } }
public override Speed CountSpeed { get { return Speed.Constant; } }
public override T Choose() { throw exception; }
}
public class CollectionEventList<T>
{
ArrayList<CollectionEvent<T>> happened;
EventTypeEnum listenTo;
SCG.IEqualityComparer<T> itemequalityComparer;
public CollectionEventList(SCG.IEqualityComparer<T> itemequalityComparer)
{
happened = new ArrayList<CollectionEvent<T>>();
this.itemequalityComparer = itemequalityComparer;
}
public void Listen(ICollectionValue<T> list, EventTypeEnum listenTo)
{
this.listenTo = listenTo;
if ((listenTo & EventTypeEnum.Changed) != 0)
list.CollectionChanged += new CollectionChangedHandler<T>(changed);
if ((listenTo & EventTypeEnum.Cleared) != 0)
list.CollectionCleared += new CollectionClearedHandler<T>(cleared);
if ((listenTo & EventTypeEnum.Removed) != 0)
list.ItemsRemoved += new ItemsRemovedHandler<T>(removed);
if ((listenTo & EventTypeEnum.Added) != 0)
list.ItemsAdded += new ItemsAddedHandler<T>(added);
if ((listenTo & EventTypeEnum.Inserted) != 0)
list.ItemInserted += new ItemInsertedHandler<T>(inserted);
if ((listenTo & EventTypeEnum.RemovedAt) != 0)
list.ItemRemovedAt += new ItemRemovedAtHandler<T>(removedAt);
}
public void Add(CollectionEvent<T> e) { happened.Add(e); }
/// <summary>
/// Check that we have seen exactly the events in expected that match listenTo.
/// </summary>
/// <param name="expected"></param>
public void Check(SCG.IEnumerable<CollectionEvent<T>> expected)
{
int i = 0;
foreach (CollectionEvent<T> expectedEvent in expected)
{
if ((expectedEvent.Act & listenTo) == 0)
continue;
if (i >= happened.Count)
Assert.Fail(string.Format("Event number {0} did not happen:\n expected {1}", i, expectedEvent));
if (!expectedEvent.Equals(happened[i], itemequalityComparer))
Assert.Fail(string.Format("Event number {0}:\n expected {1}\n but saw {2}", i, expectedEvent, happened[i]));
i++;
}
if (i < happened.Count)
Assert.Fail(string.Format("Event number {0} seen but no event expected:\n {1}", i, happened[i]));
happened.Clear();
}
public void Clear() { happened.Clear(); }
public void Print(System.IO.TextWriter writer)
{
happened.Apply(delegate(CollectionEvent<T> e) { writer.WriteLine(e); });
}
void changed(object sender)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.Changed, new EventArgs(), sender));
}
void cleared(object sender, ClearedEventArgs eventArgs)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.Cleared, eventArgs, sender));
}
void added(object sender, ItemCountEventArgs<T> eventArgs)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.Added, eventArgs, sender));
}
void removed(object sender, ItemCountEventArgs<T> eventArgs)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.Removed, eventArgs, sender));
}
void inserted(object sender, ItemAtEventArgs<T> eventArgs)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.Inserted, eventArgs, sender));
}
void removedAt(object sender, ItemAtEventArgs<T> eventArgs)
{
happened.Add(new CollectionEvent<T>(EventTypeEnum.RemovedAt, eventArgs, sender));
}
}
public sealed class CollectionEvent<T>
{
public readonly EventTypeEnum Act;
public readonly EventArgs Args;
public readonly object Sender;
public CollectionEvent(EventTypeEnum act, EventArgs args, object sender)
{
this.Act = act;
this.Args = args;
this.Sender = sender;
}
public bool Equals(CollectionEvent<T> otherEvent, SCG.IEqualityComparer<T> itemequalityComparer)
{
if (otherEvent == null || Act != otherEvent.Act || !object.ReferenceEquals(Sender, otherEvent.Sender))
return false;
switch (Act)
{
case EventTypeEnum.None:
break;
case EventTypeEnum.Changed:
return true;
case EventTypeEnum.Cleared:
if (Args is ClearedRangeEventArgs)
{
ClearedRangeEventArgs a = Args as ClearedRangeEventArgs, o = otherEvent.Args as ClearedRangeEventArgs;
if (o == null)
return false;
return a.Full == o.Full && a.Start == o.Start && a.Count == o.Count;
}
else
{
if (otherEvent.Args is ClearedRangeEventArgs)
return false;
ClearedEventArgs a = Args as ClearedEventArgs, o = otherEvent.Args as ClearedEventArgs;
return a.Full == o.Full && a.Count == o.Count;
}
case EventTypeEnum.Added:
{
ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>;
return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count;
}
case EventTypeEnum.Removed:
{
ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>;
return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count;
}
case EventTypeEnum.Inserted:
{
ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>;
return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item);
}
case EventTypeEnum.RemovedAt:
{
ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>;
return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item);
}
}
throw new ApplicationException("Illegat Act: " + Act);
}
public override string ToString()
{
return string.Format("Act: {0}, Args : {1}, Source : {2}", Act, Args, Sender);
}
}
public class CHC
{
static public int unsequencedhashcode(params int[] a)
{
int h = 0;
foreach (int i in a)
{
h += (int)(((uint)i * 1529784657 + 1) ^ ((uint)i * 2912831877) ^ ((uint)i * 1118771817 + 2));
}
return h;
}
static public int sequencedhashcode(params int[] a)
{
int h = 0;
foreach (int i in a) { h = h * 31 + i; }
return h;
}
}
//This class is a modified sample from VS2005 beta1 documentation
public class RadixFormatProvider : IFormatProvider
{
RadixFormatter _radixformatter;
public RadixFormatProvider(int radix)
{
if (radix < 2 || radix > 36)
throw new ArgumentException(String.Format(
"The radix \"{0}\" is not in the range 2..36.",
radix));
_radixformatter = new RadixFormatter(radix);
}
public object GetFormat(Type argType)
{
if (argType == typeof(ICustomFormatter))
return _radixformatter;
else
return null;
}
}
//This class is a modified sample from VS2005 beta1 documentation
public class RadixFormatter : ICustomFormatter
{
int radix;
public RadixFormatter(int radix)
{
if (radix < 2 || radix > 36)
throw new ArgumentException(String.Format(
"The radix \"{0}\" is not in the range 2..36.",
radix));
this.radix = radix;
}
// The value to be formatted is returned as a signed string
// of digits from the rDigits array.
private static char[] rDigits = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };
public string Format(string formatString,
object argToBeFormatted, IFormatProvider provider)
{
/*switch (Type.GetTypeCode(argToBeFormatted.GetType()))
{
case TypeCode.Boolean:
break;
case TypeCode.Byte:
break;
case TypeCode.Char:
break;
case TypeCode.DBNull:
break;
case TypeCode.DateTime:
break;
case TypeCode.Decimal:
break;
case TypeCode.Double:
break;
case TypeCode.Empty:
break;
case TypeCode.Int16:
break;
case TypeCode.Int32:
break;
case TypeCode.Int64:
break;
case TypeCode.Object:
break;
case TypeCode.SByte:
break;
case TypeCode.Single:
break;
case TypeCode.String:
break;
case TypeCode.UInt16:
break;
case TypeCode.UInt32:
break;
case TypeCode.UInt64:
break;
}*/
int intToBeFormatted;
try
{
intToBeFormatted = (int)argToBeFormatted;
}
catch (Exception)
{
if (argToBeFormatted is IFormattable)
return ((IFormattable)argToBeFormatted).
ToString(formatString, provider);
else
return argToBeFormatted.ToString();
}
return formatInt(intToBeFormatted);
}
private string formatInt(int intToBeFormatted)
{
// The formatting is handled here.
if (intToBeFormatted == 0)
return "0";
int digitIndex = 0;
int intPositive;
char[] outDigits = new char[31];
// Verify that the argument can be converted to a int integer.
// Extract the magnitude for conversion.
intPositive = Math.Abs(intToBeFormatted);
// Convert the magnitude to a digit string.
for (digitIndex = 0; digitIndex <= 32; digitIndex++)
{
if (intPositive == 0) break;
outDigits[outDigits.Length - digitIndex - 1] =
rDigits[intPositive % radix];
intPositive /= radix;
}
// Add a minus sign if the argument is negative.
if (intToBeFormatted < 0)
outDigits[outDigits.Length - digitIndex++ - 1] =
'-';
return new string(outDigits,
outDigits.Length - digitIndex, digitIndex);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SE.DSP.Pop.Web.WebHost.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(int), index => (int)(index % int.MaxValue) },
{ typeof(long), index => (long)index },
{ typeof(object), index => new object() },
{ typeof(sbyte), index => (sbyte)64 },
{ typeof(float), index => (float)(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(ulong), index => (ulong)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.Text;
using System.Web;
namespace ShareDB.RichText
{
internal static class TextUtil
{
/// <summary>
/// Determine the common prefix of two strings as the number of characters common to the start of each string.
/// </summary>
/// <param name="text1"></param>
/// <param name="text2"></param>
/// <param name="i1">start index of substring in text1</param>
/// <param name="i2">start index of substring in text2</param>
/// <returns>The number of characters common to the start of each string.</returns>
internal static int CommonPrefix(string text1, string text2, int i1= 0, int i2 = 0)
{
var l1 = text1.Length - i1;
var l2 = text2.Length - i2;
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var n = Math.Min(l1, l2);
for (var i = 0; i < n; i++)
{
if (text1[i+i1] != text2[i+i2])
{
return i;
}
}
return n;
}
internal static int CommonPrefix(StringBuilder text1, StringBuilder text2)
{
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var n = Math.Min(text1.Length, text2.Length);
for (var i = 0; i < n; i++)
{
if (text1[i] != text2[i])
{
return i;
}
}
return n;
}
/// <summary>
/// Determine the common suffix of two strings as the number of characters common to the end of each string.
/// </summary>
/// <param name="text1"></param>
/// <param name="text2"></param>
/// <param name="l1">maximum length to consider for text1</param>
/// <param name="l2">maximum length to consider for text2</param>
/// <returns>The number of characters common to the end of each string.</returns>
internal static int CommonSuffix(string text1, string text2, int? l1 = null, int? l2 = null)
{
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var text1Length = l1 ?? text1.Length;
var text2Length = l2 ?? text2.Length;
var n = Math.Min(text1Length, text2Length);
for (var i = 1; i <= n; i++)
{
if (text1[text1Length - i] != text2[text2Length - i])
{
return i - 1;
}
}
return n;
}
internal static int CommonSuffix(StringBuilder text1, StringBuilder text2)
{
// Performance analysis: http://neil.fraser.name/news/2007/10/09/
var text1Length = text1.Length;
var text2Length = text2.Length;
var n = Math.Min(text1Length, text2Length);
for (var i = 1; i <= n; i++)
{
if (text1[text1Length - i] != text2[text2Length - i])
{
return i - 1;
}
}
return n;
}
/// <summary>
/// Determine if the suffix of one string is the prefix of another. Returns
/// the number of characters common to the end of the first
/// string and the start of the second string.
/// </summary>
/// <param name="text1"></param>
/// <param name="text2"></param>
/// <returns>The number of characters common to the end of the first
/// string and the start of the second string.</returns>
internal static int CommonOverlap(string text1, string text2)
{
// Cache the text lengths to prevent multiple calls.
var text1Length = text1.Length;
var text2Length = text2.Length;
// Eliminate the null case.
if (text1Length == 0 || text2Length == 0)
{
return 0;
}
// Truncate the longer string.
if (text1Length > text2Length)
{
text1 = text1.Substring(text1Length - text2Length);
}
else if (text1Length < text2Length)
{
text2 = text2.Substring(0, text1Length);
}
var textLength = Math.Min(text1Length, text2Length);
// Quick check for the worst case.
if (text1 == text2)
{
return textLength;
}
// Start by looking for a single character match
// and increase length until no match is found.
// Performance analysis: http://neil.fraser.name/news/2010/11/04/
var best = 0;
var length = 1;
while (true)
{
var pattern = text1.Substring(textLength - length);
var found = text2.IndexOf(pattern, StringComparison.Ordinal);
if (found == -1)
{
return best;
}
length += found;
if (found == 0 || text1.Substring(textLength - length) ==
text2.Substring(0, length))
{
best = length;
length++;
}
}
}
/// <summary>
/// Does a Substring of shorttext exist within longtext such that the
/// Substring is at least half the length of longtext?
/// </summary>
/// <param name="longtext">Longer string.</param>
/// <param name="shorttext">Shorter string.</param>
/// <param name="i">Start index of quarter length Substring within longtext.</param>
/// <returns></returns>
private static HalfMatchResult HalfMatchI(string longtext, string shorttext, int i)
{
// Start with a 1/4 length Substring at position i as a seed.
var seed = longtext.Substring(i, longtext.Length / 4);
var j = -1;
var bestCommon = string.Empty;
string bestLongtextA = string.Empty, bestLongtextB = string.Empty;
string bestShorttextA = string.Empty, bestShorttextB = string.Empty;
while (j < shorttext.Length && (j = shorttext.IndexOf(seed, j + 1, StringComparison.Ordinal)) != -1)
{
var prefixLength = CommonPrefix(longtext, shorttext, i, j);
var suffixLength = CommonSuffix(longtext, shorttext, i, j);
if (bestCommon.Length < suffixLength + prefixLength)
{
bestCommon = shorttext.Substring(j - suffixLength, suffixLength) + shorttext.Substring(j, prefixLength);
bestLongtextA = longtext.Substring(0, i - suffixLength);
bestLongtextB = longtext.Substring(i + prefixLength);
bestShorttextA = shorttext.Substring(0, j - suffixLength);
bestShorttextB = shorttext.Substring(j + prefixLength);
}
}
return bestCommon.Length * 2 >= longtext.Length
? new HalfMatchResult(bestLongtextA, bestLongtextB, bestShorttextA, bestShorttextB, bestCommon)
: HalfMatchResult.Empty;
}
/// <summary>
/// Do the two texts share a Substring which is at least half the length of
/// the longer text?
/// This speedup can produce non-minimal Diffs.
/// </summary>
/// <param name="text1"></param>
/// <param name="text2"></param>
/// <returns>Data structure containing the prefix and suffix of string1,
/// the prefix and suffix of string 2, and the common middle. Null if there was no match.</returns>
internal static HalfMatchResult HalfMatch(string text1, string text2)
{
var longtext = text1.Length > text2.Length ? text1 : text2;
var shorttext = text1.Length > text2.Length ? text2 : text1;
if (longtext.Length < 4 || shorttext.Length*2 < longtext.Length)
{
return HalfMatchResult.Empty; // Pointless.
}
// First check if the second quarter is the seed for a half-match.
var hm1 = HalfMatchI(longtext, shorttext, (longtext.Length+3)/4);
// Check again based on the third quarter.
var hm2 = HalfMatchI(longtext, shorttext, (longtext.Length+1)/2);
if (hm1.IsEmpty && hm2.IsEmpty)
return hm1;
HalfMatchResult hm;
if (hm2.IsEmpty)
hm = hm1;
else if (hm1.IsEmpty)
hm = hm2;
else
hm = hm1 > hm2 ? hm1 : hm2;
if (text1.Length > text2.Length)
return hm;
else
return hm.Reverse();
}
/// <summary>
/// Unescape selected chars for compatability with JavaScript's encodeURI.
/// In speed critical applications this could be dropped since the
/// receiving application will certainly decode these fine.
/// Note that this function is case-sensitive. Thus "%3F" would not be
/// unescaped. But this is ok because it is only called with the output of
/// HttpUtility.UrlEncode which returns lowercase hex.
///
/// Example: "%3f" -> "?", "%24" -> "$", etc.</summary>
/// <param name="str"></param>
/// <returns></returns>
internal static string UnescapeForEncodeUriCompatability(this string str)
{
return str.Replace("%21", "!").Replace("%7e", "~")
.Replace("%27", "'").Replace("%28", "(").Replace("%29", ")")
.Replace("%3b", ";").Replace("%2f", "/").Replace("%3f", "?")
.Replace("%3a", ":").Replace("%40", "@").Replace("%26", "&")
.Replace("%3d", "=").Replace("%2b", "+").Replace("%24", "$")
.Replace("%2c", ",").Replace("%23", "#");
}
internal static string UrlEncoded(this string str)
{
return HttpUtility.UrlEncode(str, new UTF8Encoding());
}
internal static string UrlDecoded(this string str)
{
return HttpUtility.UrlDecode(str, new UTF8Encoding(false, true));
}
// MATCH FUNCTIONS
/// <summary>
/// Locate the best instance of 'pattern' in 'text' near 'loc'.
/// Returns -1 if no match found.
/// </summary>
/// <param name="text">Text to search</param>
/// <param name="pattern">pattern to search for</param>
/// <param name="loc">location to search around</param>
/// <returns>Best match index, -1 if not found</returns>
internal static int FindBestMatchIndex(this string text, string pattern, int loc)
{
return FindBestMatchIndex(text, pattern, loc, MatchSettings.Default);
}
internal static int FindBestMatchIndex(this string text, string pattern, int loc, MatchSettings settings)
{
// Check for null inputs not needed since null can't be passed in C#.
loc = Math.Max(0, Math.Min(loc, text.Length));
if (text == pattern)
{
// Shortcut (potentially not guaranteed by the algorithm)
return 0;
}
if (text.Length == 0)
{
// Nothing to match.
return -1;
}
if (loc + pattern.Length <= text.Length
&& text.Substring(loc, pattern.Length) == pattern)
{
// Perfect match at the perfect spot! (Includes case of null pattern)
return loc;
}
// Do a fuzzy compare.
var bitap = new BitapAlgorithm(settings);
return bitap.Match(text, pattern, loc);
}
}
}
| |
//
// PrimarySource.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 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 System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Jobs;
using Hyena.Data;
using Hyena.Query;
using Hyena.Data.Sqlite;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Configuration;
using Banshee.Sources;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Query;
namespace Banshee.Sources
{
public class TrackEventArgs : EventArgs
{
private DateTime when;
public DateTime When {
get { return when; }
}
private QueryField [] changed_fields;
public QueryField [] ChangedFields {
get { return changed_fields; }
}
public TrackEventArgs ()
{
when = DateTime.Now;
}
public TrackEventArgs (params QueryField [] fields) : this ()
{
changed_fields = fields;
}
}
public delegate bool TrackEqualHandler (DatabaseTrackInfo a, TrackInfo b);
public delegate object TrackExternalObjectHandler (DatabaseTrackInfo a);
public delegate string TrackArtworkIdHandler (DatabaseTrackInfo a);
public abstract class PrimarySource : DatabaseSource, IDisposable
{
#region Functions that let us override some behavior of our DatabaseTrackInfos
public TrackEqualHandler TrackEqualHandler { get; protected set; }
public TrackInfo.IsPlayingHandler TrackIsPlayingHandler { get; protected set; }
public TrackExternalObjectHandler TrackExternalObjectHandler { get; protected set; }
public TrackArtworkIdHandler TrackArtworkIdHandler { get; protected set; }
#endregion
protected ErrorSource error_source;
protected bool error_source_visible = false;
protected string remove_range_sql = @"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, " + BansheeQuery.UriField.Column + @"
FROM CoreTracks WHERE TrackID IN (SELECT {0});
DELETE FROM CoreTracks WHERE TrackID IN (SELECT {0})";
protected HyenaSqliteCommand remove_list_command = new HyenaSqliteCommand (String.Format (@"
INSERT INTO CoreRemovedTracks (DateRemovedStamp, TrackID, Uri)
SELECT ?, TrackID, {0} FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?);
DELETE FROM CoreTracks WHERE TrackID IN (SELECT ItemID FROM CoreCache WHERE ModelID = ?)
", BansheeQuery.UriField.Column));
protected HyenaSqliteCommand prune_artists_albums_command = new HyenaSqliteCommand (@"
DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT AlbumID FROM CoreTracks);
DELETE FROM CoreArtists WHERE
NOT EXISTS (SELECT 1 FROM CoreTracks WHERE CoreTracks.ArtistID = CoreArtists.ArtistID)
AND NOT EXISTS (SELECT 1 FROM CoreAlbums WHERE CoreAlbums.ArtistID = CoreArtists.ArtistID)
");
protected HyenaSqliteCommand purge_tracks_command = new HyenaSqliteCommand (@"
DELETE FROM CoreTracks WHERE PrimarySourceId = ?
");
private SchemaEntry<bool> expanded_schema;
public SchemaEntry<bool> ExpandedSchema {
get { return expanded_schema; }
}
private long dbid;
public long DbId {
get {
if (dbid > 0) {
return dbid;
}
dbid = ServiceManager.DbConnection.Query<long> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = ?", UniqueId);
if (dbid == 0) {
dbid = ServiceManager.DbConnection.Execute ("INSERT INTO CorePrimarySources (StringID, IsTemporary) VALUES (?, ?)", UniqueId, IsTemporary);
} else {
SavedCount = ServiceManager.DbConnection.Query<int> ("SELECT CachedCount FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
IsTemporary = ServiceManager.DbConnection.Query<bool> ("SELECT IsTemporary FROM CorePrimarySources WHERE PrimarySourceID = ?", dbid);
}
if (dbid == 0) {
throw new ApplicationException ("dbid could not be resolved, this should never happen");
}
return dbid;
}
}
private bool supports_playlists = true;
public virtual bool SupportsPlaylists {
get { return supports_playlists; }
protected set { supports_playlists = value; }
}
public virtual bool PlaylistsReadOnly {
get { return false; }
}
public ErrorSource ErrorSource {
get {
if (error_source == null) {
error_source = new ErrorSource (Catalog.GetString ("Errors"));
ErrorSource.Updated += OnErrorSourceUpdated;
OnErrorSourceUpdated (null, null);
}
return error_source;
}
}
private bool is_local = false;
public bool IsLocal {
get { return is_local; }
protected set { is_local = value; }
}
private static SourceSortType[] sort_types = new SourceSortType[] {
SortNameAscending,
SortSizeAscending,
SortSizeDescending
};
public override SourceSortType[] ChildSortTypes {
get { return sort_types; }
}
public override SourceSortType DefaultChildSort {
get { return SortNameAscending; }
}
public delegate void TrackEventHandler (Source sender, TrackEventArgs args);
public event TrackEventHandler TracksAdded;
public event TrackEventHandler TracksChanged;
public event TrackEventHandler TracksDeleted;
private static Dictionary<long, PrimarySource> primary_sources = new Dictionary<long, PrimarySource> ();
public static PrimarySource GetById (long id)
{
return (primary_sources.ContainsKey (id)) ? primary_sources[id] : null;
}
public virtual string BaseDirectory {
get { return null; }
protected set { base_dir_with_sep = null; }
}
private string base_dir_with_sep;
public string BaseDirectoryWithSeparator {
get { return base_dir_with_sep ?? (base_dir_with_sep = BaseDirectory + System.IO.Path.DirectorySeparatorChar); }
}
protected PrimarySource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, false)
{
}
protected PrimarySource (string generic_name, string name, string id, int order, bool is_temp) : base (generic_name, name, id, order)
{
Properties.SetString ("SortChildrenActionLabel", Catalog.GetString ("Sort Playlists By"));
IsTemporary = is_temp;
PrimarySourceInitialize ();
}
protected PrimarySource () : base ()
{
}
// Translators: this is a noun, referring to the harddisk
private string storage_name = Catalog.GetString ("Drive");
public string StorageName {
get { return storage_name; }
protected set { storage_name = value; }
}
public override bool? AutoExpand {
get { return ExpandedSchema.Get (); }
}
public override bool Expanded {
get { return ExpandedSchema.Get (); }
set {
ExpandedSchema.Set (value);
base.Expanded = value;
}
}
public PathPattern PathPattern { get; private set; }
protected void SetFileNamePattern (PathPattern pattern)
{
PathPattern = pattern;
var file_system = PreferencesPage.FindOrAdd (new Section ("file-system", Catalog.GetString ("File Organization"), 5));
file_system.Add (new SchemaPreference<string> (pattern.FolderSchema, Catalog.GetString ("Folder hie_rarchy")));
file_system.Add (new SchemaPreference<string> (pattern.FileSchema, Catalog.GetString ("File _name")));
}
public virtual void Dispose ()
{
PurgeSelfIfTemporary ();
if (Application.ShuttingDown)
return;
DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo;
if (track != null && track.PrimarySourceId == this.DbId) {
ServiceManager.PlayerEngine.Close ();
}
ClearChildSources ();
Remove ();
}
protected override void Initialize ()
{
base.Initialize ();
PrimarySourceInitialize ();
}
private void PrimarySourceInitialize ()
{
// Scope the tracks to this primary source
DatabaseTrackModel.AddCondition (String.Format ("CoreTracks.PrimarySourceID = {0}", DbId));
primary_sources[DbId] = this;
// If there was a crash, tracks can be left behind, for example in DaapSource.
// Temporary playlists are cleaned up by the PlaylistSource.LoadAll call below
if (IsTemporary && SavedCount > 0) {
PurgeTracks ();
}
// Load our playlists and smart playlists
foreach (PlaylistSource pl in PlaylistSource.LoadAll (this)) {
AddChildSource (pl);
}
int sp_count = 0;
foreach (SmartPlaylistSource pl in SmartPlaylistSource.LoadAll (this)) {
AddChildSource (pl);
sp_count++;
}
// Create default smart playlists if we haven't done it ever before, and if the
// user has zero smart playlists.
if (!HaveCreatedSmartPlaylists) {
if (sp_count == 0) {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists) {
SmartPlaylistSource pl = def.ToSmartPlaylistSource (this);
pl.Save ();
AddChildSource (pl);
pl.RefreshAndReload ();
sp_count++;
}
}
// Only save it if we already had some smart playlists, or we actually created some (eg not
// if we didn't have any and the list of default ones is empty atm).
if (sp_count > 0)
HaveCreatedSmartPlaylists = true;
}
expanded_schema = new SchemaEntry<bool> (
String.Format ("sources.{0}", ParentConfigurationId), "expanded", true, "Is source expanded", "Is source expanded"
);
}
private bool HaveCreatedSmartPlaylists {
get { return DatabaseConfigurationClient.Client.Get<bool> ("HaveCreatedSmartPlaylists", UniqueId, false); }
set { DatabaseConfigurationClient.Client.Set<bool> ("HaveCreatedSmartPlaylists", UniqueId, value); }
}
public override void Save ()
{
ServiceManager.DbConnection.Execute (
"UPDATE CorePrimarySources SET CachedCount = ? WHERE PrimarySourceID = ?",
Count, DbId
);
}
public virtual void UpdateMetadata (DatabaseTrackInfo track)
{
}
public virtual void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job)
{
Log.WarningFormat ("CopyTrackTo not implemented for source {0}", this);
}
internal void NotifyTracksAdded ()
{
OnTracksAdded ();
}
internal void NotifyTracksChanged (params QueryField [] fields)
{
OnTracksChanged (fields);
}
// TODO replace this public method with a 'transaction'-like system
public void NotifyTracksChanged ()
{
OnTracksChanged ();
}
public void NotifyTracksDeleted ()
{
OnTracksDeleted ();
}
protected void OnErrorSourceUpdated (object o, EventArgs args)
{
lock (error_source) {
if (error_source.Count > 0 && !error_source_visible) {
error_source_visible = true;
AddChildSource (error_source);
} else if (error_source.Count <= 0 && error_source_visible) {
error_source_visible = false;
RemoveChildSource (error_source);
}
}
}
public virtual IEnumerable<SmartPlaylistDefinition> DefaultSmartPlaylists {
get { yield break; }
}
public virtual IEnumerable<SmartPlaylistDefinition> NonDefaultSmartPlaylists {
get { yield break; }
}
public IEnumerable<SmartPlaylistDefinition> PredefinedSmartPlaylists {
get {
foreach (SmartPlaylistDefinition def in DefaultSmartPlaylists)
yield return def;
foreach (SmartPlaylistDefinition def in NonDefaultSmartPlaylists)
yield return def;
}
}
public override bool CanSearch {
get { return true; }
}
protected override void OnTracksAdded ()
{
ThreadAssist.SpawnFromMain (delegate {
Reload ();
TrackEventHandler handler = TracksAdded;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
});
}
protected override void OnTracksChanged (params QueryField [] fields)
{
ThreadAssist.SpawnFromMain (delegate {
if (NeedsReloadWhenFieldsChanged (fields)) {
Reload ();
} else {
InvalidateCaches ();
}
System.Threading.Thread.Sleep (150);
TrackEventHandler handler = TracksChanged;
if (handler != null) {
handler (this, new TrackEventArgs (fields));
}
});
}
protected override void OnTracksDeleted ()
{
ThreadAssist.SpawnFromMain (delegate {
PruneArtistsAlbums ();
Reload ();
TrackEventHandler handler = TracksDeleted;
if (handler != null) {
handler (this, new TrackEventArgs ());
}
SkipTrackIfRemoved ();
});
}
protected override void OnTracksRemoved ()
{
OnTracksDeleted ();
}
protected virtual void PurgeSelfIfTemporary ()
{
if (!IsTemporary) {
return;
}
PlaylistSource.ClearTemporary (this);
PurgeTracks ();
ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
DELETE FROM CorePrimarySources WHERE PrimarySourceId = ?"),
DbId);
}
protected virtual void PurgeTracks ()
{
ServiceManager.DbConnection.Execute (purge_tracks_command, DbId);
}
protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
ServiceManager.DbConnection.Execute (
String.Format (remove_range_sql, model.TrackIdsSql),
DateTime.Now,
model.CacheId, range.Start, range.End - range.Start + 1,
model.CacheId, range.Start, range.End - range.Start + 1
);
}
public void DeleteAllTracks (AbstractPlaylistSource source)
{
if (source.PrimarySource != this) {
Log.WarningFormat ("Cannot delete all tracks from {0} via primary source {1}", source, this);
return;
}
if (source.Count < 1)
return;
var list = CachedList<DatabaseTrackInfo>.CreateFromModel (source.DatabaseTrackModel);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
public override void DeleteTracks (DatabaseTrackListModel model, Selection selection)
{
if (model == null || model.Count < 1) {
return;
}
var list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
ThreadAssist.SpawnFromMain (delegate {
DeleteTrackList (list);
});
}
protected virtual void DeleteTrackList (CachedList<DatabaseTrackInfo> list)
{
is_deleting = true;
DeleteTrackJob.Total += list.Count;
var skip_deletion = new List<DatabaseTrackInfo> ();
// Remove from file system
foreach (DatabaseTrackInfo track in list) {
if (track == null) {
DeleteTrackJob.Completed++;
continue;
}
if (DeleteTrackJob.IsCancelRequested) {
skip_deletion.Add (track);
continue;
}
try {
DeleteTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
if (!DeleteTrack (track)) {
skip_deletion.Add (track);
}
} catch (Exception e) {
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
DeleteTrackJob.Completed++;
if (DeleteTrackJob.Completed % 10 == 0 && !DeleteTrackJob.IsFinished) {
OnTracksDeleted ();
}
}
if (!DeleteTrackJob.IsFinished || DeleteTrackJob.IsCancelRequested) {
delete_track_job.Finish ();
}
delete_track_job = null;
is_deleting = false;
if (skip_deletion.Count > 0) {
list.Remove (skip_deletion);
skip_deletion.Clear ();
}
// Remove from database
if (list.Count > 0) {
ServiceManager.DbConnection.Execute (remove_list_command, DateTime.Now, list.CacheId, list.CacheId);
}
ThreadAssist.ProxyToMain (delegate {
OnTracksDeleted ();
OnUserNotifyUpdated ();
OnUpdated ();
});
}
protected virtual bool DeleteTrack (DatabaseTrackInfo track)
{
if (!track.Uri.IsLocalPath)
throw new Exception ("Cannot delete a non-local resource: " + track.Uri.Scheme);
try {
Banshee.IO.Utilities.DeleteFileTrimmingParentDirectories (track.Uri);
} catch (System.IO.FileNotFoundException) {
} catch (System.IO.DirectoryNotFoundException) {
}
return true;
}
public override bool AcceptsInputFromSource (Source source)
{
return base.AcceptsInputFromSource (source) && source.Parent != this
&& (source.Parent is PrimarySource || source is PrimarySource)
&& !(source.Parent is Banshee.Library.LibrarySource);
}
public override bool AddSelectedTracks (Source source, Selection selection)
{
if (!AcceptsInputFromSource (source))
return false;
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
// Store a snapshot of the current selection
CachedList<DatabaseTrackInfo> cached_list = CachedList<DatabaseTrackInfo>.CreateFromModelAndSelection (model, selection);
if (ThreadAssist.InMainThread) {
System.Threading.ThreadPool.QueueUserWorkItem (AddTrackList, cached_list);
} else {
AddTrackList (cached_list);
}
return true;
}
public long GetTrackIdForUri (string uri)
{
return DatabaseTrackInfo.GetTrackIdForUri (new SafeUri (uri), DbId);
}
private bool is_adding;
public bool IsAdding {
get { return is_adding; }
}
private bool is_deleting;
public bool IsDeleting {
get { return is_deleting; }
}
protected virtual void AddTrackAndIncrementCount (DatabaseTrackInfo track)
{
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrack (track);
IncrementAddedTracks ();
}
protected virtual void AddTrackList (object cached_list)
{
CachedList<DatabaseTrackInfo> list = cached_list as CachedList<DatabaseTrackInfo>;
is_adding = true;
AddTrackJob.Total += list.Count;
foreach (DatabaseTrackInfo track in list) {
if (AddTrackJob.IsCancelRequested) {
AddTrackJob.Finish ();
IncrementAddedTracks ();
break;
}
if (track == null) {
IncrementAddedTracks ();
continue;
}
try {
AddTrackJob.Status = String.Format ("{0} - {1}", track.ArtistName, track.TrackTitle);
AddTrackAndIncrementCount (track);
} catch (Exception e) {
IncrementAddedTracks ();
Log.Exception (e);
ErrorSource.AddMessage (e.Message, track.Uri.ToString ());
}
}
if (!AddTrackJob.IsFinished) {
AddTrackJob.Finish ();
}
add_track_job = null;
is_adding = false;
}
protected void IncrementAddedTracks ()
{
bool finished = false, notify = false;
lock (this) {
AddTrackJob.Completed++;
if (add_track_job.IsFinished) {
finished = true;
} else {
if (add_track_job.Completed % 10 == 0)
notify = true;
}
}
if (finished) {
is_adding = false;
}
if (notify || finished) {
OnTracksAdded ();
if (finished) {
ThreadAssist.ProxyToMain (OnUserNotifyUpdated);
}
}
}
private bool delay_add_job = true;
protected bool DelayAddJob {
get { return delay_add_job; }
set { delay_add_job = value; }
}
private bool delay_delete_job = true;
protected bool DelayDeleteJob {
get { return delay_delete_job; }
set { delay_delete_job = value; }
}
private BatchUserJob add_track_job;
protected BatchUserJob AddTrackJob {
get {
lock (this) {
if (add_track_job == null) {
add_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Adding {0} of {1} to {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
add_track_job.SetResources (Resource.Cpu, Resource.Database, Resource.Disk);
add_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
add_track_job.DelayShow = DelayAddJob;
add_track_job.CanCancel = true;
add_track_job.Register ();
}
}
return add_track_job;
}
}
private BatchUserJob delete_track_job;
protected BatchUserJob DeleteTrackJob {
get {
lock (this) {
if (delete_track_job == null) {
delete_track_job = new BatchUserJob (String.Format (Catalog.GetString (
"Deleting {0} of {1} From {2}"), "{0}", "{1}", Name),
Properties.GetStringList ("Icon.Name"));
delete_track_job.SetResources (Resource.Cpu, Resource.Database);
delete_track_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped;
delete_track_job.DelayShow = DelayDeleteJob;
delete_track_job.CanCancel = true;
delete_track_job.Register ();
}
}
return delete_track_job;
}
}
protected override void PruneArtistsAlbums ()
{
ServiceManager.DbConnection.Execute (prune_artists_albums_command);
base.PruneArtistsAlbums ();
DatabaseAlbumInfo.Reset ();
DatabaseArtistInfo.Reset ();
}
}
}
| |
// 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.ComponentModel; //Component
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
// todo:
// There may be two ways to improve performance:
// 1. pool statements on the connection object
// 2. Do not create a datareader object for non-datareader returning command execution.
//
// We do not want to do the effort unless we have to squeze performance.
namespace System.Data.Odbc
{
[
DefaultEvent("RecordsAffected"),
ToolboxItem(true),
Designer("Microsoft.VSDesigner.Data.VS.OdbcCommandDesigner, " + AssemblyRef.MicrosoftVSDesigner)
]
public sealed class OdbcCommand : DbCommand, ICloneable
{
private static int s_objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
private string _commandText;
private CommandType _commandType;
private int _commandTimeout = ADP.DefaultCommandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
private bool _isPrepared; // true if the command is prepared
private OdbcConnection _connection;
private OdbcTransaction _transaction;
private WeakReference _weakDataReaderReference;
private CMDWrapper _cmdWrapper;
private OdbcParameterCollection _parameterCollection; // Parameter collection
private ConnectionState _cmdState;
public OdbcCommand() : base()
{
GC.SuppressFinalize(this);
}
public OdbcCommand(string cmdText) : this()
{
// note: arguments are assigned to properties so we do not have to trace them.
// We still need to include them into the argument list of the definition!
CommandText = cmdText;
}
public OdbcCommand(string cmdText, OdbcConnection connection) : this()
{
CommandText = cmdText;
Connection = connection;
}
public OdbcCommand(string cmdText, OdbcConnection connection, OdbcTransaction transaction) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
private void DisposeDeadDataReader()
{
if (ConnectionState.Fetching == _cmdState)
{
if (null != _weakDataReaderReference && !_weakDataReaderReference.IsAlive)
{
if (_cmdWrapper != null)
{
_cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE);
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.CLOSE);
}
CloseFromDataReader();
}
}
}
private void DisposeDataReader()
{
if (null != _weakDataReaderReference)
{
IDisposable reader = (IDisposable)_weakDataReaderReference.Target;
if ((null != reader) && _weakDataReaderReference.IsAlive)
{
((IDisposable)reader).Dispose();
}
CloseFromDataReader();
}
}
internal void DisconnectFromDataReaderAndConnection()
{
// get a reference to the datareader if it is alive
OdbcDataReader liveReader = null;
if (_weakDataReaderReference != null)
{
OdbcDataReader reader;
reader = (OdbcDataReader)_weakDataReaderReference.Target;
if (_weakDataReaderReference.IsAlive)
{
liveReader = reader;
}
}
// remove reference to this from the live datareader
if (liveReader != null)
{
liveReader.Command = null;
}
_transaction = null;
if (null != _connection)
{
_connection.RemoveWeakReference(this);
_connection = null;
}
// if the reader is dead we have to dismiss the statement
if (liveReader == null)
{
CloseCommandWrapper();
}
// else DataReader now has exclusive ownership
_cmdWrapper = null;
}
override protected void Dispose(bool disposing)
{ // MDAC 65459
if (disposing)
{
// release mananged objects
// in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset
this.DisconnectFromDataReaderAndConnection();
_parameterCollection = null;
CommandText = null;
}
_cmdWrapper = null; // let go of the CommandWrapper
_isPrepared = false;
base.Dispose(disposing); // notify base classes
}
internal bool Canceling
{
get
{
return _cmdWrapper.Canceling;
}
}
[
ResCategoryAttribute(Res.DataCategory_Data),
DefaultValue(""),
RefreshProperties(RefreshProperties.All), // MDAC 67707
ResDescriptionAttribute(Res.DbCommand_CommandText),
Editor("Microsoft.VSDesigner.Data.Odbc.Design.OdbcCommandTextEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing)
]
override public string CommandText
{
get
{
string value = _commandText;
return ((null != value) ? value : ADP.StrEmpty);
}
set
{
if (Bid.TraceOn)
{
Bid.Trace("<odbc.OdbcCommand.set_CommandText|API> %d#, '", ObjectID);
Bid.PutStr(value); // Use PutStr to write out entire string
Bid.Trace("'\n");
}
if (0 != ADP.SrcCompare(_commandText, value))
{
PropertyChanging();
_commandText = value;
}
}
}
[
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandTimeout),
]
override public int CommandTimeout
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _commandTimeout;
}
set
{
Bid.Trace("<odbc.OdbcCommand.set_CommandTimeout|API> %d#, %d\n", ObjectID, value);
if (value < 0)
{
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout)
{
PropertyChanging();
_commandTimeout = value;
}
}
}
public void ResetCommandTimeout()
{ // V1.2.3300
if (ADP.DefaultCommandTimeout != _commandTimeout)
{
PropertyChanging();
_commandTimeout = ADP.DefaultCommandTimeout;
}
}
private bool ShouldSerializeCommandTimeout()
{ // V1.2.3300
return (ADP.DefaultCommandTimeout != _commandTimeout);
}
[
DefaultValue(System.Data.CommandType.Text),
RefreshProperties(RefreshProperties.All),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_CommandType),
]
override public CommandType CommandType
{
get
{
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case CommandType.Text:
case CommandType.StoredProcedure:
PropertyChanging();
_commandType = value;
break;
case CommandType.TableDirect:
throw ODBC.NotSupportedCommandType(value);
default:
throw ADP.InvalidCommandType(value);
}
}
}
// This will establish a relationship between the command and the connection
[
DefaultValue(null),
ResCategoryAttribute(Res.DataCategory_Behavior),
ResDescriptionAttribute(Res.DbCommand_Connection),
Editor("Microsoft.VSDesigner.Data.Design.DbConnectionEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing),
]
new public OdbcConnection Connection
{
get
{
return _connection;
}
set
{
if (value != _connection)
{
PropertyChanging();
this.DisconnectFromDataReaderAndConnection();
Debug.Assert(null == _cmdWrapper, "has CMDWrapper when setting connection");
_connection = value;
//OnSchemaChanged();
}
}
}
override protected DbConnection DbConnection
{ // V1.2.3300
get
{
return Connection;
}
set
{
Connection = (OdbcConnection)value;
}
}
override protected DbParameterCollection DbParameterCollection
{ // V1.2.3300
get
{
return Parameters;
}
}
override protected DbTransaction DbTransaction
{ // V1.2.3300
get
{
return Transaction;
}
set
{
Transaction = (OdbcTransaction)value;
}
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsableAttribute(EditorBrowsableState.Never),
]
public override bool DesignTimeVisible
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return !_designTimeInvisible;
}
set
{
_designTimeInvisible = !value;
TypeDescriptor.Refresh(this); // VS7 208845
}
}
internal bool HasParameters
{
get
{
return (null != _parameterCollection);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
ResCategoryAttribute(Res.DataCategory_Data),
ResDescriptionAttribute(Res.DbCommand_Parameters),
]
new public OdbcParameterCollection Parameters
{
get
{
if (null == _parameterCollection)
{
_parameterCollection = new OdbcParameterCollection();
}
return _parameterCollection;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
ResDescriptionAttribute(Res.DbCommand_Transaction),
]
new public OdbcTransaction Transaction
{
get
{
if ((null != _transaction) && (null == _transaction.Connection))
{
_transaction = null; // Dawn of the Dead
}
return _transaction;
}
set
{
if (_transaction != value)
{
PropertyChanging(); // fire event before value is validated
_transaction = value;
}
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both),
ResCategoryAttribute(Res.DataCategory_Update),
ResDescriptionAttribute(Res.DbCommand_UpdatedRowSource),
]
override public UpdateRowSource UpdatedRowSource
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _updatedRowSource;
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
}
}
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
return _cmdWrapper.GetDescriptorHandle(attribute);
}
// GetStatementHandle
// ------------------
// Try to return a cached statement handle.
//
// Creates a CmdWrapper object if necessary
// If no handle is available a handle will be allocated.
// Bindings will be unbound if a handle is cached and the bindings are invalid.
//
internal CMDWrapper GetStatementHandle()
{
// update the command wrapper object, allocate buffer
// create reader object
//
if (_cmdWrapper == null)
{
_cmdWrapper = new CMDWrapper(_connection);
Debug.Assert(null != _connection, "GetStatementHandle without connection?");
_connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag);
}
if (_cmdWrapper._dataReaderBuf == null)
{
_cmdWrapper._dataReaderBuf = new CNativeBuffer(4096);
}
// if there is already a statement handle we need to do some cleanup
//
if (null == _cmdWrapper.StatementHandle)
{
_isPrepared = false;
_cmdWrapper.CreateStatementHandle();
}
else if ((null != _parameterCollection) && _parameterCollection.RebindCollection)
{
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.RESET_PARAMS);
}
return _cmdWrapper;
}
// OdbcCommand.Cancel()
//
// In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all
// (ODBC Programmer's Reference ...)
//
override public void Cancel()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
wrapper.Canceling = true;
OdbcStatementHandle stmt = wrapper.StatementHandle;
if (null != stmt)
{
lock (stmt)
{
// Cancel the statement
ODBC32.RetCode retcode = stmt.Cancel();
// copy of StatementErrorHandler, because stmt may become null
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
// don't fire info message events on cancel
break;
default:
throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode);
}
}
}
}
}
object ICloneable.Clone()
{
OdbcCommand clone = new OdbcCommand();
Bid.Trace("<odbc.OdbcCommand.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID);
clone.CommandText = CommandText;
clone.CommandTimeout = this.CommandTimeout;
clone.CommandType = CommandType;
clone.Connection = this.Connection;
clone.Transaction = this.Transaction;
clone.UpdatedRowSource = UpdatedRowSource;
if ((null != _parameterCollection) && (0 < Parameters.Count))
{
OdbcParameterCollection parameters = clone.Parameters;
foreach (ICloneable parameter in Parameters)
{
parameters.Add(parameter.Clone());
}
}
return clone;
}
internal bool RecoverFromConnection()
{
DisposeDeadDataReader();
return (ConnectionState.Closed == _cmdState);
}
private void CloseCommandWrapper()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
try
{
wrapper.Dispose();
if (null != _connection)
{
_connection.RemoveWeakReference(this);
}
}
finally
{
_cmdWrapper = null;
}
}
}
internal void CloseFromConnection()
{
if (null != _parameterCollection)
{
_parameterCollection.RebindCollection = true;
}
DisposeDataReader();
CloseCommandWrapper();
_isPrepared = false;
_transaction = null;
}
internal void CloseFromDataReader()
{
_weakDataReaderReference = null;
_cmdState = ConnectionState.Closed;
}
new public OdbcParameter CreateParameter()
{
return new OdbcParameter();
}
override protected DbParameter CreateDbParameter()
{
return CreateParameter();
}
override protected DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
override public int ExecuteNonQuery()
{
OdbcConnection.ExecutePermission.Demand();
using (OdbcDataReader reader = ExecuteReaderObject(0, ADP.ExecuteNonQuery, false))
{
reader.Close();
return reader.RecordsAffected;
}
}
new public OdbcDataReader ExecuteReader()
{
return ExecuteReader(0/*CommandBehavior*/);
}
new public OdbcDataReader ExecuteReader(CommandBehavior behavior)
{
OdbcConnection.ExecutePermission.Demand();
return ExecuteReaderObject(behavior, ADP.ExecuteReader, true);
}
internal OdbcDataReader ExecuteReaderFromSQLMethod(object[] methodArguments,
ODBC32.SQL_API method)
{
return ExecuteReaderObject(CommandBehavior.Default, method.ToString(), true, methodArguments, method);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader)
{ // MDAC 68324
if ((CommandText == null) || (CommandText.Length == 0))
{
throw (ADP.CommandTextRequired(method));
}
// using all functions to tell ExecuteReaderObject that
return ExecuteReaderObject(behavior, method, needReader, null, ODBC32.SQL_API.SQLEXECDIRECT);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior,
string method,
bool needReader,
object[] methodArguments,
ODBC32.SQL_API odbcApiMethod)
{ // MDAC 68324
OdbcDataReader localReader = null;
try
{
DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching
ValidateConnectionAndTransaction(method); // cmdState will change to Executing
if (0 != (CommandBehavior.SingleRow & behavior))
{
// CommandBehavior.SingleRow implies CommandBehavior.SingleResult
behavior |= CommandBehavior.SingleResult;
}
ODBC32.RetCode retcode;
OdbcStatementHandle stmt = GetStatementHandle().StatementHandle;
_cmdWrapper.Canceling = false;
if (null != _weakDataReaderReference)
{
if (_weakDataReaderReference.IsAlive)
{
object target = _weakDataReaderReference.Target;
if (null != target && _weakDataReaderReference.IsAlive)
{
if (!((OdbcDataReader)target).IsClosed)
{
throw ADP.OpenReaderExists(); // MDAC 66411
}
}
}
}
localReader = new OdbcDataReader(this, _cmdWrapper, behavior);
//Set command properties
//Not all drivers support timeout. So fail silently if error
if (!Connection.ProviderInfo.NoQueryTimeout)
{
TrySetStatementAttribute(stmt,
ODBC32.SQL_ATTR.QUERY_TIMEOUT,
(IntPtr)this.CommandTimeout);
}
// todo: If we remember the state we can omit a lot of SQLSetStmtAttrW calls ...
// if we do not create a reader we do not even need to do that
if (needReader)
{
if (Connection.IsV3Driver)
{
if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns)
{
// Need to get the metadata information
//SQLServer actually requires browse info turned on ahead of time...
//Note: We ignore any failures, since this is SQLServer specific
//We won't specialcase for SQL Server but at least for non-V3 drivers
if (localReader.IsBehavior(CommandBehavior.KeyInfo))
{
if (!_cmdWrapper._ssKeyInfoModeOn)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.ON);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.ON);
_cmdWrapper._ssKeyInfoModeOff = false;
_cmdWrapper._ssKeyInfoModeOn = true;
}
}
else
{
if (!_cmdWrapper._ssKeyInfoModeOff)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.OFF);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.OFF);
_cmdWrapper._ssKeyInfoModeOff = true;
_cmdWrapper._ssKeyInfoModeOn = false;
}
}
}
}
}
if (localReader.IsBehavior(CommandBehavior.KeyInfo) ||
localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
}
bool mustRelease = false;
CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
//Handle Parameters
//Note: We use the internal variable as to not instante a new object collection,
//for the common case of using no parameters.
if ((null != _parameterCollection) && (0 < _parameterCollection.Count))
{
int parameterBufferSize = _parameterCollection.CalcParameterBufferSize(this);
if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize)
{
if (null != parameterBuffer)
{
parameterBuffer.Dispose();
}
parameterBuffer = new CNativeBuffer(parameterBufferSize);
_cmdWrapper._nativeParameterBuffer = parameterBuffer;
}
else
{
parameterBuffer.ZeroMemory();
}
parameterBuffer.DangerousAddRef(ref mustRelease);
_parameterCollection.Bind(this, _cmdWrapper, parameterBuffer);
}
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
// Can't get the KeyInfo after command execution (SQL Server only since it does not support multiple
// results on the same connection). Stored procedures (SP) do not return metadata before actual execution
// Need to check the column count since the command type may not be set to SP for a SP.
if ((localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly))
&& (CommandType != CommandType.StoredProcedure))
{
Int16 cColsAffected;
retcode = stmt.NumberOfResultColumns(out cColsAffected);
if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)
{
if (cColsAffected > 0)
{
localReader.GetSchemaTable();
}
}
else if (retcode == ODBC32.RetCode.NO_DATA)
{
// do nothing
}
else
{
// any other returncode indicates an error
_connection.HandleError(stmt, retcode);
}
}
switch (odbcApiMethod)
{
case ODBC32.SQL_API.SQLEXECDIRECT:
if (localReader.IsBehavior(CommandBehavior.KeyInfo) || _isPrepared)
{
//Already prepared, so use SQLExecute
retcode = stmt.Execute();
// Build metadata here
// localReader.GetSchemaTable();
}
else
{
#if DEBUG
//if (AdapterSwitches.OleDbTrace.TraceInfo) {
// ADP.DebugWriteLine("SQLExecDirectW: " + CommandText);
//}
#endif
//SQLExecDirect
retcode = stmt.ExecuteDirect(CommandText);
}
break;
case ODBC32.SQL_API.SQLTABLES:
retcode = stmt.Tables((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema,
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //TableType
break;
case ODBC32.SQL_API.SQLCOLUMNS:
retcode = stmt.Columns((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //ColumnName
break;
case ODBC32.SQL_API.SQLPROCEDURES:
retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2]); //procedureName
break;
case ODBC32.SQL_API.SQLPROCEDURECOLUMNS:
retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2], //procedureName
(string)methodArguments[3]); //columnName
break;
case ODBC32.SQL_API.SQLSTATISTICS:
retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(Int16)methodArguments[3], //IndexTrpe
(Int16)methodArguments[4]); //Accuracy
break;
case ODBC32.SQL_API.SQLGETTYPEINFO:
retcode = stmt.GetTypeInfo((Int16)methodArguments[0]); //SQL Type
break;
default:
// this should NEVER happen
Debug.Assert(false, "ExecuteReaderObjectcalled with unsupported ODBC API method.");
throw ADP.InvalidOperation(method.ToString());
}
//Note: Execute will return NO_DATA for Update/Delete non-row returning queries
if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode))
{
_connection.HandleError(stmt, retcode);
}
} // end SchemaOnly
}
finally
{
if (mustRelease)
{
parameterBuffer.DangerousRelease();
}
}
_weakDataReaderReference = new WeakReference(localReader);
// XXXCommand.Execute should position reader on first row returning result
// any exceptions in the initial non-row returning results should be thrown
// from from ExecuteXXX not the DataReader
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
localReader.FirstResult();
}
_cmdState = ConnectionState.Fetching;
}
finally
{
if (ConnectionState.Fetching != _cmdState)
{
if (null != localReader)
{
// clear bindings so we don't grab output parameters on a failed execute
if (null != _parameterCollection)
{
_parameterCollection.ClearBindings();
}
((IDisposable)localReader).Dispose();
}
if (ConnectionState.Closed != _cmdState)
{
_cmdState = ConnectionState.Closed;
}
}
}
return localReader;
}
override public object ExecuteScalar()
{
OdbcConnection.ExecutePermission.Demand();
object value = null;
using (IDataReader reader = ExecuteReaderObject(0, ADP.ExecuteScalar, false))
{
if (reader.Read() && (0 < reader.FieldCount))
{
value = reader.GetValue(0);
}
reader.Close();
}
return value;
}
internal string GetDiagSqlState()
{
return _cmdWrapper.GetDiagSqlState();
}
private void PropertyChanging()
{
_isPrepared = false;
}
// Prepare
//
// if the CommandType property is set to TableDirect Prepare does nothing.
// if the CommandType property is set to StoredProcedure Prepare should succeed but result
// in a no-op
//
// throw InvalidOperationException
// if the connection is not set
// if the connection is not open
//
override public void Prepare()
{
OdbcConnection.ExecutePermission.Demand();
ODBC32.RetCode retcode;
ValidateOpenConnection(ADP.Prepare);
if (0 != (ConnectionState.Fetching & _connection.InternalState))
{
throw ADP.OpenReaderExists();
}
if (CommandType == CommandType.TableDirect)
{
return; // do nothing
}
DisposeDeadDataReader();
GetStatementHandle();
OdbcStatementHandle stmt = _cmdWrapper.StatementHandle;
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
_isPrepared = true;
}
private void TrySetStatementAttribute(OdbcStatementHandle stmt, ODBC32.SQL_ATTR stmtAttribute, IntPtr value)
{
ODBC32.RetCode retcode = stmt.SetStatementAttribute(
stmtAttribute,
value,
ODBC32.SQL_IS.UINTEGER);
if (retcode == ODBC32.RetCode.ERROR)
{
string sqlState;
stmt.GetDiagnosticField(out sqlState);
if ((sqlState == "HYC00") || (sqlState == "HY092"))
{
Connection.FlagUnsupportedStmtAttr(stmtAttribute);
}
else
{
// now what? Should we throw?
}
}
}
private void ValidateOpenConnection(string methodName)
{
// see if we have a connection
OdbcConnection connection = Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(methodName);
}
// must have an open and available connection
ConnectionState state = connection.State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(methodName, state);
}
}
private void ValidateConnectionAndTransaction(string method)
{
if (null == _connection)
{
throw ADP.ConnectionRequired(method);
}
_transaction = _connection.SetStateExecuting(method, Transaction);
_cmdState = ConnectionState.Executing;
}
}
internal sealed class CMDWrapper
{
private OdbcStatementHandle _stmt; // hStmt
private OdbcStatementHandle _keyinfostmt; // hStmt for keyinfo
internal OdbcDescriptorHandle _hdesc; // hDesc
internal CNativeBuffer _nativeParameterBuffer; // Native memory for internal memory management
// (Performance optimization)
internal CNativeBuffer _dataReaderBuf; // Reusable DataReader buffer
private readonly OdbcConnection _connection; // Connection
private bool _canceling; // true if the command is canceling
internal bool _hasBoundColumns;
internal bool _ssKeyInfoModeOn; // tells us if the SqlServer specific options are on
internal bool _ssKeyInfoModeOff; // a tri-state value would be much better ...
internal CMDWrapper(OdbcConnection connection)
{
_connection = connection;
}
internal bool Canceling
{
get
{
return _canceling;
}
set
{
_canceling = value;
}
}
internal OdbcConnection Connection
{
get
{
return _connection;
}
}
internal bool HasBoundColumns
{
// get {
// return _hasBoundColumns;
// }
set
{
_hasBoundColumns = value;
}
}
internal OdbcStatementHandle StatementHandle
{
get { return _stmt; }
}
internal OdbcStatementHandle KeyInfoStatement
{
get
{
return _keyinfostmt;
}
}
internal void CreateKeyInfoStatementHandle()
{
DisposeKeyInfoStatementHandle();
_keyinfostmt = _connection.CreateStatementHandle();
}
internal void CreateStatementHandle()
{
DisposeStatementHandle();
_stmt = _connection.CreateStatementHandle();
}
internal void Dispose()
{
if (null != _dataReaderBuf)
{
_dataReaderBuf.Dispose();
_dataReaderBuf = null;
}
DisposeStatementHandle();
CNativeBuffer buffer = _nativeParameterBuffer;
_nativeParameterBuffer = null;
if (null != buffer)
{
buffer.Dispose();
}
_ssKeyInfoModeOn = false;
_ssKeyInfoModeOff = false;
}
private void DisposeDescriptorHandle()
{
OdbcDescriptorHandle handle = _hdesc;
if (null != handle)
{
_hdesc = null;
handle.Dispose();
}
}
internal void DisposeStatementHandle()
{
DisposeKeyInfoStatementHandle();
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
_stmt = null;
handle.Dispose();
}
}
internal void DisposeKeyInfoStatementHandle()
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
_keyinfostmt = null;
handle.Dispose();
}
}
internal void FreeStatementHandle(ODBC32.STMT stmt)
{
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
try
{
ODBC32.RetCode retcode;
retcode = handle.FreeStatement(stmt);
StatementErrorHandler(retcode);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_stmt = null;
handle.Dispose();
}
throw;
}
}
}
internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt)
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
try
{
handle.FreeStatement(stmt);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_keyinfostmt = null;
handle.Dispose();
}
throw;
}
}
}
// Get the Descriptor Handle for the current statement
//
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
OdbcDescriptorHandle hdesc = _hdesc;
if (null == _hdesc)
{
_hdesc = hdesc = new OdbcDescriptorHandle(_stmt, attribute);
}
return hdesc;
}
internal string GetDiagSqlState()
{
string sqlstate;
_stmt.GetDiagnosticField(out sqlstate);
return sqlstate;
}
internal void StatementErrorHandler(ODBC32.RetCode retcode)
{
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_connection.HandleErrorNoThrow(_stmt, retcode);
break;
default:
throw _connection.HandleErrorNoThrow(_stmt, retcode);
}
}
internal void UnbindStmtColumns()
{
if (_hasBoundColumns)
{
FreeStatementHandle(ODBC32.STMT.UNBIND);
_hasBoundColumns = false;
}
}
}
}
| |
/*
* 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.
*/
/* Generated By:JavaCC: Do not edit this line. HTMLParser.java */
using System;
namespace Lucene.Net.Demo.Html
{
public class HTMLParser : HTMLParserConstants_Fields
{
private void InitBlock()
{
jj_2_rtns = new JJCalls[2];
jj_ls = new LookaheadSuccess();
}
public static int SUMMARY_LENGTH = 200;
internal System.Text.StringBuilder title = new System.Text.StringBuilder(SUMMARY_LENGTH);
internal System.Text.StringBuilder summary = new System.Text.StringBuilder(SUMMARY_LENGTH * 2);
internal System.Collections.Specialized.NameValueCollection metaTags = new System.Collections.Specialized.NameValueCollection();
internal System.String currentMetaTag = null;
internal System.String currentMetaContent = null;
internal int length = 0;
internal bool titleComplete = false;
internal bool summaryComplete = false;
internal bool inTitle = false;
internal bool inMetaTag = false;
internal bool inStyle = false;
internal bool afterTag = false;
internal bool afterSpace = false;
internal System.String eol = System.Environment.NewLine;
internal System.IO.StreamReader pipeIn = null;
internal System.IO.StreamWriter pipeOut;
private MyPipedInputStream pipeInStream = null;
private System.IO.StreamWriter pipeOutStream = null;
private class MyPipedInputStream : System.IO.MemoryStream
{
long _readPtr = 0;
long _writePtr = 0;
public System.IO.Stream BaseStream
{
get
{
return this;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
lock (this)
{
base.Seek(_readPtr, System.IO.SeekOrigin.Begin);
int x = base.Read(buffer, offset, count);
_readPtr += x;
return x;
}
}
public override void Write(byte[] buffer, int offset, int count)
{
lock (this)
{
base.Seek(_writePtr, System.IO.SeekOrigin.Begin);
base.Write(buffer, offset, count);
_writePtr += count;
}
}
public override void Close()
{
}
public virtual bool Full()
{
return false;
}
}
/// <deprecated> Use HTMLParser(FileInputStream) instead
/// </deprecated>
public HTMLParser(System.IO.FileInfo file):this(new System.IO.FileStream(file.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
}
public virtual System.String GetTitle()
{
if (pipeIn == null)
GetReader(); // spawn parsing thread
while (true)
{
lock (this)
{
if (titleComplete || pipeInStream.Full())
break;
System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(10));
}
}
return title.ToString().Trim();
}
public virtual System.Collections.Specialized.NameValueCollection GetMetaTags()
{
if (pipeIn == null)
GetReader(); // spawn parsing thread
while (true)
{
lock (this)
{
if (titleComplete || pipeInStream.Full())
break;
System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(10));
}
}
return metaTags;
}
public virtual System.String GetSummary()
{
if (pipeIn == null)
GetReader(); // spawn parsing thread
while (true)
{
lock (this)
{
if (summary.Length >= SUMMARY_LENGTH || pipeInStream.Full())
break;
System.Threading.Monitor.Wait(this, TimeSpan.FromMilliseconds(10));
}
}
if (summary.Length > SUMMARY_LENGTH)
summary.Length = SUMMARY_LENGTH;
System.String sum = summary.ToString().Trim();
System.String tit = GetTitle();
if (sum.StartsWith(tit) || sum.Equals(""))
return tit;
else
return sum;
}
public virtual System.IO.StreamReader GetReader()
{
if (pipeIn == null)
{
pipeInStream = new MyPipedInputStream();
pipeOutStream = new System.IO.StreamWriter(pipeInStream.BaseStream);
pipeIn = new System.IO.StreamReader(pipeInStream.BaseStream, System.Text.Encoding.GetEncoding("UTF-16BE"));
pipeOut = new System.IO.StreamWriter(pipeOutStream.BaseStream, System.Text.Encoding.GetEncoding("UTF-16BE"));
SupportClass.ThreadClass thread = new ParserThread(this);
thread.Start(); // start parsing
}
return pipeIn;
}
internal virtual void AddToSummary(System.String text)
{
if (summary.Length < SUMMARY_LENGTH)
{
summary.Append(text);
if (summary.Length >= SUMMARY_LENGTH)
{
lock (this)
{
summaryComplete = true;
System.Threading.Monitor.PulseAll(this);
}
}
}
}
internal virtual void AddText(System.String text)
{
if (inStyle)
return ;
if (inTitle)
title.Append(text);
else
{
AddToSummary(text);
if (!titleComplete && !(title.Length == 0))
{
// finished title
lock (this)
{
titleComplete = true; // tell waiting threads
System.Threading.Monitor.PulseAll(this);
}
}
}
length += text.Length;
pipeOut.Write(text);
afterSpace = false;
}
internal virtual void AddMetaTag()
{
metaTags[currentMetaTag] = currentMetaContent;
currentMetaTag = null;
currentMetaContent = null;
return ;
}
internal virtual void AddSpace()
{
if (!afterSpace)
{
if (inTitle)
title.Append(" ");
else
AddToSummary(" ");
System.String space = afterTag?eol:" ";
length += space.Length;
pipeOut.Write(space);
afterSpace = true;
}
}
public void HTMLDocument()
{
Token t;
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptStart:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.TagName:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.DeclName:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment1:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment2:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Word:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Entity:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Space:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Punct:
;
break;
default:
jj_la1[0] = jj_gen;
goto label_1_brk;
}
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.TagName:
Tag();
afterTag = true;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.DeclName:
t = Decl();
afterTag = true;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment1:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment2:
CommentTag();
afterTag = true;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptStart:
ScriptTag();
afterTag = true;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Word:
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Word);
AddText(t.image); afterTag = false;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Entity:
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Entity);
AddText(Entities.Decode(t.image)); afterTag = false;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Punct:
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Punct);
AddText(t.image); afterTag = false;
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Space:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Space);
AddSpace(); afterTag = false;
break;
default:
jj_la1[1] = jj_gen;
Jj_consume_token(- 1);
throw new ParseException();
}
}
label_1_brk: ;
Jj_consume_token(0);
}
public void Tag()
{
Token t1, t2;
bool inImg = false;
t1 = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.TagName);
System.String tagName = t1.image.ToLower();
if (Tags.WS_ELEMS.Contains(tagName))
{
AddSpace();
}
inTitle = tagName.ToUpper().Equals("<title".ToUpper()); // keep track if in <TITLE>
inMetaTag = tagName.ToUpper().Equals("<META".ToUpper()); // keep track if in <META>
inStyle = tagName.ToUpper().Equals("<STYLE".ToUpper()); // keep track if in <STYLE>
inImg = tagName.ToUpper().Equals("<img".ToUpper()); // keep track if in <IMG>
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgName:
;
break;
default:
jj_la1[2] = jj_gen;
goto label_2_brk;
}
t1 = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgName);
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgEquals:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgEquals);
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgValue:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2:
t2 = ArgValue();
if (inImg && t1.image.ToUpper().Equals("alt".ToUpper()) && t2 != null)
AddText("[" + t2.image + "]");
if (inMetaTag && (t1.image.ToUpper().Equals("name".ToUpper()) || t1.image.ToUpper().Equals("HTTP-EQUIV".ToUpper())) && t2 != null)
{
currentMetaTag = t2.image.ToLower();
if (currentMetaTag != null && currentMetaContent != null)
{
AddMetaTag();
}
}
if (inMetaTag && t1.image.ToUpper().Equals("content".ToUpper()) && t2 != null)
{
currentMetaContent = t2.image.ToLower();
if (currentMetaTag != null && currentMetaContent != null)
{
AddMetaTag();
}
}
break;
default:
jj_la1[3] = jj_gen;
;
break;
}
break;
default:
jj_la1[4] = jj_gen;
;
break;
}
}
label_2_brk: ;
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.TagEnd);
}
public Token ArgValue()
{
Token t = null;
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgValue:
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgValue);
{
if (true)
return t;
}
break;
default:
jj_la1[5] = jj_gen;
if (Jj_2_1(2))
{
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1);
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote1);
{
if (true)
return t;
}
}
else
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1);
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Quote1Text);
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote1);
{
if (true)
return t;
}
break;
default:
jj_la1[6] = jj_gen;
if (Jj_2_2(2))
{
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2);
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote2);
{
if (true)
return t;
}
}
else
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2);
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Quote2Text);
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote2);
{
if (true)
return t;
}
break;
default:
jj_la1[7] = jj_gen;
Jj_consume_token(- 1);
throw new ParseException();
}
}
break;
}
}
break;
}
throw new System.ApplicationException("Missing return statement in function");
}
public Token Decl()
{
Token t;
t = Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.DeclName);
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgName:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgEquals:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgValue:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2:
;
break;
default:
jj_la1[8] = jj_gen;
goto label_3_brk;
}
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgName:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgName);
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgValue:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1:
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2:
ArgValue();
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgEquals:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgEquals);
break;
default:
jj_la1[9] = jj_gen;
Jj_consume_token(- 1);
throw new ParseException();
}
}
label_3_brk: ;
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.TagEnd);
{
if (true)
return t;
}
throw new System.ApplicationException("Missing return statement in function");
}
public void CommentTag()
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment1:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment1);
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentText1:
;
break;
default:
jj_la1[10] = jj_gen;
goto label_4_brk;
}
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentText1);
}
label_4_brk: ;
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentEnd1);
break;
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment2:
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.Comment2);
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentText2:
;
break;
default:
jj_la1[11] = jj_gen;
goto label_5_brk;
}
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentText2);
}
label_5_brk: ;
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CommentEnd2);
break;
default:
jj_la1[12] = jj_gen;
Jj_consume_token(- 1);
throw new ParseException();
}
}
public void ScriptTag()
{
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptStart);
while (true)
{
switch ((jj_ntk == - 1)?Jj_ntk():jj_ntk)
{
case Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptText:
;
break;
default:
jj_la1[13] = jj_gen;
goto label_6_brk;
}
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptText);
}
label_6_brk: ;
Jj_consume_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ScriptEnd);
}
private bool Jj_2_1(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try
{
return !Jj_3_1();
}
catch (LookaheadSuccess ls)
{
return true;
}
finally
{
Jj_save(0, xla);
}
}
private bool Jj_2_2(int xla)
{
jj_la = xla; jj_lastpos = jj_scanpos = token;
try
{
return !Jj_3_2();
}
catch (LookaheadSuccess ls)
{
return true;
}
finally
{
Jj_save(1, xla);
}
}
private bool Jj_3_1()
{
if (Jj_scan_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote1))
return true;
if (Jj_scan_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote1))
return true;
return false;
}
private bool Jj_3_2()
{
if (Jj_scan_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.ArgQuote2))
return true;
if (Jj_scan_token(Lucene.Net.Demo.Html.HTMLParserConstants_Fields.CloseQuote2))
return true;
return false;
}
public HTMLParserTokenManager token_source;
internal SimpleCharStream jj_input_stream;
public Token token, jj_nt;
private int jj_ntk;
private Token jj_scanpos, jj_lastpos;
private int jj_la;
public bool lookingAhead = false;
private bool jj_semLA;
private int jj_gen;
private int[] jj_la1 = new int[14];
private static int[] jj_la1_0;
private static void Jj_la1_0()
{
jj_la1_0 = new int[]{0x2c7e, 0x2c7e, 0x10000, 0x380000, 0x20000, 0x80000, 0x100000, 0x200000, 0x3b0000, 0x3b0000, 0x8000000, 0x20000000, 0x30, 0x4000};
}
private JJCalls[] jj_2_rtns;
private bool jj_rescan = false;
private int jj_gc = 0;
public HTMLParser(System.IO.Stream stream):this(stream, null)
{
}
public HTMLParser(System.IO.Stream stream, System.String encoding)
{
InitBlock();
try
{
jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1);
}
catch (System.IO.IOException e)
{
throw new System.Exception(e.Message, e);
}
token_source = new HTMLParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
public virtual void ReInit(System.IO.Stream stream)
{
ReInit(stream, null);
}
public virtual void ReInit(System.IO.Stream stream, System.String encoding)
{
try
{
jj_input_stream.ReInit(stream, encoding, 1, 1);
}
catch (System.IO.IOException e)
{
throw new System.Exception(e.Message, e);
}
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
public HTMLParser(System.IO.StreamReader stream)
{
InitBlock();
jj_input_stream = new SimpleCharStream(stream, 1, 1);
token_source = new HTMLParserTokenManager(jj_input_stream);
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
public virtual void ReInit(System.IO.StreamReader stream)
{
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
public HTMLParser(HTMLParserTokenManager tm)
{
InitBlock();
token_source = tm;
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
public virtual void ReInit(HTMLParserTokenManager tm)
{
token_source = tm;
token = new Token();
jj_ntk = - 1;
jj_gen = 0;
for (int i = 0; i < 14; i++)
jj_la1[i] = - 1;
for (int i = 0; i < jj_2_rtns.Length; i++)
jj_2_rtns[i] = new JJCalls();
}
private Token Jj_consume_token(int kind)
{
Token oldToken;
if ((oldToken = token).next != null)
token = token.next;
else
token = token.next = token_source.GetNextToken();
jj_ntk = - 1;
if (token.kind == kind)
{
jj_gen++;
if (++jj_gc > 100)
{
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.Length; i++)
{
JJCalls c = jj_2_rtns[i];
while (c != null)
{
if (c.gen < jj_gen)
c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw GenerateParseException();
}
[Serializable]
private sealed class LookaheadSuccess:System.ApplicationException
{
}
private LookaheadSuccess jj_ls;
private bool Jj_scan_token(int kind)
{
if (jj_scanpos == jj_lastpos)
{
jj_la--;
if (jj_scanpos.next == null)
{
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.GetNextToken();
}
else
{
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
}
else
{
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan)
{
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos)
{
i++; tok = tok.next;
}
if (tok != null)
Jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind)
return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos)
throw jj_ls;
return false;
}
public Token GetNextToken()
{
if (token.next != null)
token = token.next;
else
token = token.next = token_source.GetNextToken();
jj_ntk = - 1;
jj_gen++;
return token;
}
public Token GetToken(int index)
{
Token t = lookingAhead?jj_scanpos:token;
for (int i = 0; i < index; i++)
{
if (t.next != null)
t = t.next;
else
t = t.next = token_source.GetNextToken();
}
return t;
}
private int Jj_ntk()
{
if ((jj_nt = token.next) == null)
return (jj_ntk = (token.next = token_source.GetNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private System.Collections.ArrayList jj_expentries = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
private int[] jj_expentry;
private int jj_kind = - 1;
private int[] jj_lasttokens = new int[100];
private int jj_endpos;
private void Jj_add_error_token(int kind, int pos)
{
if (pos >= 100)
return ;
if (pos == jj_endpos + 1)
{
jj_lasttokens[jj_endpos++] = kind;
}
else if (jj_endpos != 0)
{
jj_expentry = new int[jj_endpos];
for (int i = 0; i < jj_endpos; i++)
{
jj_expentry[i] = jj_lasttokens[i];
}
bool exists = false;
for (System.Collections.IEnumerator e = jj_expentries.GetEnumerator(); e.MoveNext(); )
{
int[] oldentry = (int[]) (e.Current);
if (oldentry.Length == jj_expentry.Length)
{
exists = true;
for (int i = 0; i < jj_expentry.Length; i++)
{
if (oldentry[i] != jj_expentry[i])
{
exists = false;
break;
}
}
if (exists)
break;
}
}
if (!exists)
jj_expentries.Add(jj_expentry);
if (pos != 0)
jj_lasttokens[(jj_endpos = pos) - 1] = kind;
}
}
public virtual ParseException GenerateParseException()
{
jj_expentries.Clear();
bool[] la1tokens = new bool[31];
for (int i = 0; i < 31; i++)
{
la1tokens[i] = false;
}
if (jj_kind >= 0)
{
la1tokens[jj_kind] = true;
jj_kind = - 1;
}
for (int i = 0; i < 14; i++)
{
if (jj_la1[i] == jj_gen)
{
for (int j = 0; j < 32; j++)
{
if ((jj_la1_0[i] & (1 << j)) != 0)
{
la1tokens[j] = true;
}
}
}
}
for (int i = 0; i < 31; i++)
{
if (la1tokens[i])
{
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.Add(jj_expentry);
}
}
jj_endpos = 0;
Jj_rescan_token();
Jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.Count][];
for (int i = 0; i < jj_expentries.Count; i++)
{
exptokseq[i] = (int[]) jj_expentries[i];
}
return new ParseException(token, exptokseq, Lucene.Net.Demo.Html.HTMLParserConstants_Fields.tokenImage);
}
public void Enable_tracing()
{
}
public void Disable_tracing()
{
}
private void Jj_rescan_token()
{
jj_rescan = true;
for (int i = 0; i < 2; i++)
{
try
{
JJCalls p = jj_2_rtns[i];
do
{
if (p.gen > jj_gen)
{
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i)
{
case 0: Jj_3_1(); break;
case 1: Jj_3_2(); break;
}
}
p = p.next;
}
while (p != null);
}
catch (LookaheadSuccess ls)
{
}
}
jj_rescan = false;
}
private void Jj_save(int index, int xla)
{
JJCalls p = jj_2_rtns[index];
while (p.gen > jj_gen)
{
if (p.next == null)
{
p = p.next = new JJCalls(); break;
}
p = p.next;
}
p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
}
internal sealed class JJCalls
{
internal int gen;
internal Token first;
internal int arg;
internal JJCalls next;
}
// void handleException(Exception e) {
// System.out.println(e.toString()); // print the error message
// System.out.println("Skipping...");
// Token t;
// do {
// t = getNextToken();
// } while (t.kind != TagEnd);
// }
static HTMLParser()
{
{
Jj_la1_0();
}
}
}
}
| |
/* ====================================================================
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 NPOI.POIFS.Common;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
using System.Collections.Generic;
using System;
using NPOI.Util;
namespace NPOI.POIFS.FileSystem
{
/**
* This class handles the MiniStream (small block store)
* in the NIO case for {@link NPOIFSFileSystem}
*/
public class NPOIFSMiniStore : BlockStore
{
private NPOIFSFileSystem _filesystem;
private NPOIFSStream _mini_stream;
private List<BATBlock> _sbat_blocks;
private HeaderBlock _header;
private RootProperty _root;
public NPOIFSMiniStore(NPOIFSFileSystem filesystem, RootProperty root,
List<BATBlock> sbats, HeaderBlock header)
{
this._filesystem = filesystem;
this._sbat_blocks = sbats;
this._header = header;
this._root = root;
this._mini_stream = new NPOIFSStream(filesystem, root.StartBlock);
}
/**
* Load the block at the given offset, optionally throwing an exception if the offset is beyond the limit of the buffer.
*/
private ByteBuffer GetBlockAt(int offset, bool throwIfNotFound)
{
// Which big block is this?
int byteOffset = offset * POIFSConstants.SMALL_BLOCK_SIZE;
int bigBlockNumber = byteOffset / _filesystem.GetBigBlockSize();
int bigBlockOffset = byteOffset % _filesystem.GetBigBlockSize();
// Now locate the data block for it
NPOIFSStream.StreamBlockByteBufferIterator it = _mini_stream.GetBlockIterator() as NPOIFSStream.StreamBlockByteBufferIterator;
for (int i = 0; i < bigBlockNumber; i++)
{
it.Next();
}
if (!it.HasNext())
{
if(throwIfNotFound)
throw new IndexOutOfRangeException("Big block " + bigBlockNumber + " outside stream");
return null;
}
// Position ourselves, and take a slice
ByteBuffer dataBlock = it.Next();
dataBlock.Position = dataBlock.Position + bigBlockOffset;
ByteBuffer miniBuffer = dataBlock.Slice();
miniBuffer.Limit = POIFSConstants.SMALL_BLOCK_SIZE;
return miniBuffer;
}
/**
* Load the block at the given offset.
*/
public override ByteBuffer GetBlockAt(int offset)
{
return GetBlockAt(offset, true);
}
/**
* Try to load the block at the given offset, and if the offset is beyond the end of the buffer, return false.
*/
public override bool TryGetBlockAt(int offset, out ByteBuffer byteBuffer)
{
byteBuffer = null;
try
{
byteBuffer = GetBlockAt(offset, false);
return byteBuffer!=null;
}
catch(IndexOutOfRangeException)
{
// Try to avoid getting here. A point of having this TryDoSomething is to avoid the expense of exception handling.
return false;
}
}
/**
* Load the block, extending the underlying stream if needed
*/
public override ByteBuffer CreateBlockIfNeeded(int offset)
{
bool firstInStore = false;
// If we are the first block to be allocated, initialise the stream
if (_mini_stream.GetStartBlock() == POIFSConstants.END_OF_CHAIN)
{
firstInStore = true;
}
// Try to Get it without extending the stream
if (!firstInStore && TryGetBlockAt(offset, out var result))
return result;
// Need to extend the stream
// TODO Replace this with proper append support
// For now, do the extending by hand...
// Ask for another block
int newBigBlock = _filesystem.GetFreeBlock();
_filesystem.CreateBlockIfNeeded(newBigBlock);
// If we are the first block to be allocated, initialise the stream
if (firstInStore)
{
_filesystem.PropertyTable.Root.StartBlock = (newBigBlock);
_mini_stream = new NPOIFSStream(_filesystem, newBigBlock);
}
else
{
// Tack it onto the end of our chain
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int block = _mini_stream.GetStartBlock();
while (true)
{
loopDetector.Claim(block);
int next = _filesystem.GetNextBlock(block);
if (next == POIFSConstants.END_OF_CHAIN)
{
break;
}
block = next;
}
_filesystem.SetNextBlock(block, newBigBlock);
}
_filesystem.SetNextBlock(newBigBlock, POIFSConstants.END_OF_CHAIN);
// Now try again, to get the real small block
return CreateBlockIfNeeded(offset);
}
/**
* Returns the BATBlock that handles the specified offset,
* and the relative index within it
*/
public override BATBlockAndIndex GetBATBlockAndIndex(int offset)
{
return BATBlock.GetSBATBlockAndIndex(
offset, _header, _sbat_blocks);
}
/**
* Works out what block follows the specified one.
*/
public override int GetNextBlock(int offset)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
return bai.Block.GetValueAt(bai.Index);
}
/**
* Changes the record of what block follows the specified one.
*/
public override void SetNextBlock(int offset, int nextBlock)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
bai.Block.SetValueAt(bai.Index, nextBlock);
}
/**
* Finds a free block, and returns its offset.
* This method will extend the file if needed, and if doing
* so, allocate new FAT blocks to Address the extra space.
*/
public override int GetFreeBlock()
{
int sectorsPerSBAT = _filesystem.GetBigBlockSizeDetails().GetBATEntriesPerBlock();
// First up, do we have any spare ones?
int offset = 0;
for (int i = 0; i < _sbat_blocks.Count; i++)
{
// Check this one
BATBlock sbat = _sbat_blocks[i];
if (sbat.HasFreeSectors)
{
// Claim one of them and return it
for (int j = 0; j < sectorsPerSBAT; j++)
{
int sbatValue = sbat.GetValueAt(j);
if (sbatValue == POIFSConstants.UNUSED_BLOCK)
{
// Bingo
return offset + j;
}
}
}
// Move onto the next SBAT
offset += sectorsPerSBAT;
}
// If we Get here, then there aren't any
// free sectors in any of the SBATs
// So, we need to extend the chain and add another
// Create a new BATBlock
BATBlock newSBAT = BATBlock.CreateEmptyBATBlock(_filesystem.GetBigBlockSizeDetails(), false);
int batForSBAT = _filesystem.GetFreeBlock();
newSBAT.OurBlockIndex = batForSBAT;
// Are we the first SBAT?
if (_header.SBATCount == 0)
{
// Tell the header that we've got our first SBAT there
_header.SBATStart = batForSBAT;
_header.SBATBlockCount = 1;
}
else
{
// Find the end of the SBAT stream, and add the sbat in there
ChainLoopDetector loopDetector = _filesystem.GetChainLoopDetector();
int batOffset = _header.SBATStart;
while (true)
{
loopDetector.Claim(batOffset);
int nextBat = _filesystem.GetNextBlock(batOffset);
if (nextBat == POIFSConstants.END_OF_CHAIN)
{
break;
}
batOffset = nextBat;
}
// Add it in at the end
_filesystem.SetNextBlock(batOffset, batForSBAT);
// And update the count
_header.SBATBlockCount = _header.SBATCount + 1;
}
// Finish allocating
_filesystem.SetNextBlock(batForSBAT, POIFSConstants.END_OF_CHAIN);
_sbat_blocks.Add(newSBAT);
// Return our first spot
return offset;
}
public override ChainLoopDetector GetChainLoopDetector()
{
return new ChainLoopDetector(_root.Size, this);
}
public override int GetBlockStoreBlockSize()
{
return POIFSConstants.SMALL_BLOCK_SIZE;
}
/// <summary>
/// Writes the SBATs to their backing blocks, and updates
/// the mini-stream size in the properties. Stream size is
/// based on full blocks used, not the data within the streams
/// </summary>
public void SyncWithDataSource()
{
int blocksUsed = 0;
foreach (BATBlock sbat in _sbat_blocks)
{
ByteBuffer block = _filesystem.GetBlockAt(sbat.OurBlockIndex);
BlockAllocationTableWriter.WriteBlock(sbat, block);
if (!sbat.HasFreeSectors)
{
blocksUsed += _filesystem.GetBigBlockSizeDetails().GetBATEntriesPerBlock();
}
else
{
blocksUsed += sbat.GetUsedSectors(false);
}
}
// Set the size on the root in terms of the number of SBAT blocks
// RootProperty.setSize does the sbat -> bytes conversion for us
_filesystem.PropertyTable.Root.Size = (blocksUsed);
}
}
}
| |
using System;
using System.Linq;
using CoreFoundation;
using Foundation;
using HomeKit;
using UIKit;
namespace HomeKitCatalog
{
// Represents the sections in the `ModifyAccessoryViewController`.
public enum AddAccessoryTableViewSection
{
Name,
Rooms,
Identify
}
public interface IModifyAccessoryDelegate
{
void AccessoryViewControllerDidSaveAccessory (ModifyAccessoryViewController accessoryViewController, HMAccessory accessory);
}
// A view controller that allows for renaming, reassigning, and identifying accessories before and after they've been added to a home.
public partial class ModifyAccessoryViewController : HMCatalogViewController, IHMAccessoryDelegate
{
static readonly NSString RoomCell = (NSString)"RoomCell";
// Update this if the acessory failed in any way.
bool didEncounterError;
bool editingExistingAccessory;
HMRoom selectedRoom;
UIActivityIndicatorView activityIndicator;
UIActivityIndicatorView ActivityIndicator {
get {
activityIndicator = activityIndicator ?? new UIActivityIndicatorView (UIActivityIndicatorViewStyle.Gray);
return activityIndicator;
}
}
// returns: The `nameField`'s text, trimmed of newline and whitespace characters.
string TrimmedName {
get {
return NameField.Text.Trim ();
}
}
readonly DispatchGroup saveAccessoryGroup = DispatchGroup.Create ();
public IModifyAccessoryDelegate Delegate { get; set; }
public HMAccessory Accessory { get; set; }
[Outlet ("nameField")]
UITextField NameField { get; set; }
[Outlet ("addButton")]
UIBarButtonItem AddButton { get; set; }
#region ctors
public ModifyAccessoryViewController (IntPtr handle)
: base (handle)
{
}
[Export ("initWithCoder:")]
public ModifyAccessoryViewController (NSCoder coder)
: base (coder)
{
}
#endregion
// Configures the table view and initializes view elements.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
TableView.EstimatedRowHeight = 44;
TableView.RowHeight = UITableView.AutomaticDimension;
selectedRoom = Accessory.Room ?? Home.GetRoomForEntireHome ();
// If the accessory belongs to the home already, we are in 'edit' mode.
editingExistingAccessory = AccessoryHasBeenAddedToHome ();
// Show 'save' instead of 'add.'
// If we're not editing an existing accessory, then let the back button show in the left.
if (editingExistingAccessory)
AddButton.Title = "Save";
else
NavigationItem.LeftBarButtonItem = null;
// Put the accessory's name in the 'name' field.
ResetNameField ();
// Register a cell for the rooms.
TableView.RegisterClassForCellReuse (typeof(UITableViewCell), RoomCell);
}
// Registers as the delegate for the current home and the accessory.
protected override void RegisterAsDelegate ()
{
base.RegisterAsDelegate ();
Accessory.Delegate = this;
}
// Replaces the activity indicator with the 'Add' or 'Save' button.
void HideActivityIndicator ()
{
ActivityIndicator.StopAnimating ();
NavigationItem.RightBarButtonItem = AddButton;
}
// Temporarily replaces the 'Add' or 'Save' button with an activity indicator.
void ShowActivityIndicator ()
{
NavigationItem.RightBarButtonItem = new UIBarButtonItem (ActivityIndicator);
ActivityIndicator.StartAnimating ();
}
// Called whenever the user taps the 'add' button.
//
// This method:
// 1. Adds the accessory to the home, if not already added.
// 2. Updates the accessory's name, if necessary.
// 3. Assigns the accessory to the selected room, if necessary.
[Export ("didTapAddButton")]
void DidTapAddButton ()
{
var name = TrimmedName;
ShowActivityIndicator ();
if (editingExistingAccessory) {
AssignAccessory (Home, Accessory, selectedRoom);
UpdateName (name, Accessory);
} else {
saveAccessoryGroup.Enter ();
Home.AddAccessory (Accessory, error => {
if (error != null) {
HideActivityIndicator ();
DisplayError (error);
didEncounterError = true;
} else {
// Once it's successfully added to the home, add it to the room that's selected.
AssignAccessory (Home, Accessory, selectedRoom);
UpdateName (name, Accessory);
}
saveAccessoryGroup.Leave ();
});
}
saveAccessoryGroup.Notify (DispatchQueue.MainQueue, () => {
HideActivityIndicator ();
if (!didEncounterError)
Dismiss (null);
});
}
// Informs the delegate that the accessory has been saved, and
// dismisses the view controller.
[Export ("dismiss:")]
void Dismiss (NSObject sender)
{
if (Delegate != null)
Delegate.AccessoryViewControllerDidSaveAccessory (this, Accessory);
if (editingExistingAccessory)
PresentingViewController.DismissViewController (true, null);
else
NavigationController.PopViewController (true);
}
// returns: `true` if the accessory has already been added to the home; `false` otherwise.
bool AccessoryHasBeenAddedToHome ()
{
return Home.Accessories.Contains (Accessory);
}
// Updates the accessories name. This function will enter and leave the saved dispatch group.
// If the accessory's name is already equal to the passed-in name, this method does nothing.
void UpdateName (string name, HMAccessory accessory)
{
if (accessory.Name == name)
return;
saveAccessoryGroup.Enter ();
accessory.UpdateName (name, error => {
if (error != null) {
DisplayError (error);
didEncounterError = true;
}
saveAccessoryGroup.Leave ();
});
}
// Assigns the given accessory to the provided room. This method will enter and leave the saved dispatch group.
void AssignAccessory (HMHome home, HMAccessory accessory, HMRoom room)
{
if (accessory.Room == room)
return;
saveAccessoryGroup.Enter ();
home.AssignAccessory (accessory, room, error => {
if (error != null) {
DisplayError (error);
didEncounterError = true;
}
saveAccessoryGroup.Leave ();
});
}
// Tells the current accessory to identify itself.
void IdentifyAccessory ()
{
Accessory.Identify (error => {
if (error != null)
DisplayError (error);
});
}
// Enables the name field if the accessory's name changes.
void ResetNameField ()
{
string action;
action = editingExistingAccessory ? "Edit {0}" : "Add {0}";
NavigationItem.Title = string.Format (action, Accessory.Name);
NameField.Text = Accessory.Name;
NameField.Enabled = Home.IsAdmin ();
EnableAddButtonIfApplicable ();
}
// Enables the save button if the name field is not empty.
void EnableAddButtonIfApplicable ()
{
AddButton.Enabled = Home.IsAdmin () && !string.IsNullOrEmpty (TrimmedName);
}
// Enables or disables the add button.
[Export ("nameFieldDidChange:")]
void NameFieldDidChange (NSObject sender)
{
EnableAddButtonIfApplicable ();
}
#region Table View Methods
public override nint NumberOfSections (UITableView tableView)
{
return Enum.GetNames (typeof(AddAccessoryTableViewSection)).Length;
}
public override nint RowsInSection (UITableView tableView, nint section)
{
switch ((AddAccessoryTableViewSection)(int)section) {
case AddAccessoryTableViewSection.Rooms:
return Home.GetAllRooms ().Length;
case AddAccessoryTableViewSection.Identify:
case AddAccessoryTableViewSection.Name:
return base.RowsInSection (tableView, section);
default:
throw new InvalidOperationException ("Unexpected `AddAccessoryTableViewSection` value.");
}
}
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath)
{
switch ((AddAccessoryTableViewSection)indexPath.Section) {
case AddAccessoryTableViewSection.Rooms:
return UITableView.AutomaticDimension;
case AddAccessoryTableViewSection.Identify:
case AddAccessoryTableViewSection.Name:
return base.GetHeightForRow (tableView, indexPath);
default:
throw new InvalidOperationException ("Unexpected `AddAccessoryTableViewSection` value.");
}
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
switch ((AddAccessoryTableViewSection)indexPath.Section) {
case AddAccessoryTableViewSection.Rooms:
return GetCellForRoom (tableView, indexPath);
case AddAccessoryTableViewSection.Identify:
case AddAccessoryTableViewSection.Name:
return base.GetCell (tableView, indexPath);
default:
throw new InvalidOperationException ("Unexpected `AddAccessoryTableViewSection` value.");
}
}
UITableViewCell GetCellForRoom (UITableView tableView, NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell (RoomCell, indexPath);
var room = Home.GetAllRooms () [indexPath.Row];
cell.TextLabel.Text = Home.GetNameForRoom (room);
// Put a checkmark on the selected room.
cell.Accessory = (room == selectedRoom) ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None;
if (!Home.IsAdmin ())
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
return cell;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
tableView.DeselectRow (indexPath, true);
switch ((AddAccessoryTableViewSection)indexPath.Section) {
case AddAccessoryTableViewSection.Rooms:
if (!Home.IsAdmin ())
return;
selectedRoom = Home.GetAllRooms () [indexPath.Row];
var sections = NSIndexSet.FromIndex ((nint)(int)AddAccessoryTableViewSection.Rooms);
tableView.ReloadSections (sections, UITableViewRowAnimation.Automatic);
break;
case AddAccessoryTableViewSection.Identify:
IdentifyAccessory ();
break;
case AddAccessoryTableViewSection.Name:
break;
default:
throw new InvalidOperationException ("Unexpected `AddAccessoryTableViewSection` value.");
}
}
public override nint IndentationLevel (UITableView tableView, NSIndexPath indexPath)
{
return base.IndentationLevel (tableView, NSIndexPath.FromRowSection (0, indexPath.Section));
}
#endregion
#region HMHomeDelegate Methods
// All home changes reload the view.
[Export ("home:didUpdateNameForRoom:")]
public void DidUpdateNameForRoom (HMHome home, HMRoom room)
{
TableView.ReloadData ();
}
[Export ("home:didAddRoom:")]
public void DidAddRoom (HMHome home, HMRoom room)
{
TableView.ReloadData ();
}
[Export ("home:didRemoveRoom:")]
public void DidRemoveRoom (HMHome home, HMRoom room)
{
// Reset the selected room if ours was deleted.
if (selectedRoom == room)
selectedRoom = HomeStore.Home.GetRoomForEntireHome ();
TableView.ReloadData ();
}
[Export ("home:didAddAccessory:")]
public void DidAddAccessory (HMHome home, HMAccessory accessory)
{
// Bridged accessories don't call the original completion handler if their
// bridges are added to the home. We must respond to `HMHomeDelegate`'s
// `home:didAddAccessory:` and assign bridged accessories properly.
if (selectedRoom != null)
AssignAccessory (home, accessory, selectedRoom);
}
[Export ("home:didUnblockAccessory:")]
public void DidUnblockAccessory (HMHome home, HMAccessory accessory)
{
TableView.ReloadData ();
}
#endregion
#region HMAccessoryDelegate Methods
[Export ("accessoryDidUpdateName:")]
public void DidUpdateName (HMAccessory accessory)
{
ResetNameField ();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using nJocLogic.data;
using nJocLogic.gameContainer;
using Wintellect.PowerCollections;
namespace nJocLogic.util.gdl.model
{
public class SentenceDomainModelOptimizer
{
///<summary>
/// Given a SentenceDomainModel, returns an ImmutableSentenceDomainModel with Cartesian domains that tries to
/// minimize the domains of sentence forms without impacting the game rules. In particular, when sentences are
/// restricted to these domains, the answers to queries about terminal, legal, goal, next, and init sentences
/// will not change.
///
/// Note that if a sentence form is not used in a meaningful way by the game, it may end up with an empty domain.
///
/// The description for the game must have had the <see cref="VariableConstrainer"/> applied to it.
///</summary>
public static ImmutableSentenceDomainModel RestrictDomainsToUsefulValues(ISentenceDomainModel oldModel)
{
// Start with everything from the current domain model.
var neededAndPossibleConstantsByForm = new Dictionary<ISentenceForm, MultiDictionary<int, TermObject>>();
foreach (ISentenceForm form in oldModel.SentenceForms)
{
neededAndPossibleConstantsByForm[form] = new MultiDictionary<int, TermObject>(false);
AddDomain(neededAndPossibleConstantsByForm[form], oldModel.GetDomain(form), form);
}
MinimizeDomains(oldModel, neededAndPossibleConstantsByForm);
return ToSentenceDomainModel(neededAndPossibleConstantsByForm, oldModel);
}
/// <summary>
/// To minimize the contents of the domains, we repeatedly go through two processes to reduce the domain:
///
/// 1) We remove unneeded constants from the domain. These are constants which (in their position) do not
/// contribute to any sentences with a GDL keyword as its name; that is, it never matters whether a
/// sentence with that constant in that position is true or false.
/// 2) We remove impossible constants from the domain. These are constants which cannot end up in their
/// position via any rule or sentence in the game description, given the current domain.
///
/// Constants removed because of one type of pass or the other may cause other constants in other sentence
/// forms to become unneeded or impossible, so we make multiple passes until everything is stable.
/// </summary>
/// <param name="oldModel"></param>
/// <param name="neededAndPossibleConstantsByForm"></param>
public static void MinimizeDomains(ISentenceDomainModel oldModel, Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededAndPossibleConstantsByForm)
{
bool somethingChanged = true;
while (somethingChanged)
{
somethingChanged = RemoveUnneededConstants(neededAndPossibleConstantsByForm, oldModel);
somethingChanged |= RemoveImpossibleConstants(neededAndPossibleConstantsByForm, oldModel);
}
}
private static void AddDomain(IDictionary<int, ICollection<TermObject>> setMultimap, ISentenceFormDomain domain, ISentenceForm form)
{
for (int i = 0; i < form.TupleSize; i++)
setMultimap[i] = domain.GetDomainForSlot(i);
}
private static bool RemoveImpossibleConstants(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
var newPossibleConstantsByForm = new Dictionary<ISentenceForm, MultiDictionary<int, TermObject>>();
foreach (ISentenceForm form in curDomains.Keys)
newPossibleConstantsByForm[form] = new MultiDictionary<int, TermObject>(false);
PopulateInitialPossibleConstants(newPossibleConstantsByForm, curDomains, model);
bool somethingChanged = true;
while (somethingChanged)
somethingChanged = PropagatePossibleConstants(newPossibleConstantsByForm, curDomains, model);
return RetainNewDomains(curDomains, newPossibleConstantsByForm);
}
private static void PopulateInitialPossibleConstants(IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newPossibleConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
//Add anything in the head of a rule...
foreach (Implication rule in GetRules(model.Description))
AddConstantsFromSentenceIfInOldDomain(newPossibleConstantsByForm, curDomains, model, rule.Consequent);
//... and any true sentences
foreach (ISentenceForm form in model.SentenceForms)
foreach (Fact sentence in model.GetSentencesListedAsTrue(form))
AddConstantsFromSentenceIfInOldDomain(newPossibleConstantsByForm, curDomains, model, sentence);
}
private static bool PropagatePossibleConstants(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> newPossibleConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomain, ISentenceFormModel model)
{
//Injection: Go from the intersections of variable values in rules to the
//values in their heads
bool somethingChanged = false;
foreach (Implication rule in GetRules(model.Description))
{
Fact head = rule.Consequent;
var domainsOfHeadVars = new Dictionary<TermVariable, ISet<TermObject>>();
foreach (TermVariable varInHead in rule.Consequent.VariablesOrEmpty.ToImmutableHashSet())
{
ISet<TermObject> domain = GetVarDomainInRuleBody(varInHead, rule, newPossibleConstantsByForm, curDomain, model);
domainsOfHeadVars[varInHead] = domain;
somethingChanged |= AddPossibleValuesToSentence(domain, head, varInHead, newPossibleConstantsByForm, model);
}
}
var parser = GameContainer.Parser;
//Language-based injections
somethingChanged |= ApplyLanguageBasedInjections(parser.TokInit, parser.TokTrue, newPossibleConstantsByForm);
somethingChanged |= ApplyLanguageBasedInjections(parser.TokNext, parser.TokTrue, newPossibleConstantsByForm);
somethingChanged |= ApplyLanguageBasedInjections(parser.TokLegal, parser.TokDoes, newPossibleConstantsByForm);
return somethingChanged;
}
private static bool ApplyLanguageBasedInjections(int curName, int resultingName,
Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> newPossibleConstantsByForm)
{
bool somethingChanged = false;
foreach (ISentenceForm form in newPossibleConstantsByForm.Keys)
{
//ConcurrencyUtils.checkForInterruption();
if (form.Name == curName)
{
ISentenceForm resultingForm = form.WithName(resultingName);
MultiDictionary<int, TermObject> curFormDomain = newPossibleConstantsByForm[form];
MultiDictionary<int, TermObject> resultingFormDomain = newPossibleConstantsByForm[resultingForm];
var before = resultingFormDomain.Count;
foreach (KeyValuePair<int, ICollection<TermObject>> domain in curFormDomain)
resultingFormDomain.Add(domain);
somethingChanged |= before != resultingFormDomain.Count;
}
}
return somethingChanged;
}
private static ISet<TermObject> GetVarDomainInRuleBody(TermVariable varInHead, Implication rule,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newPossibleConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomain, ISentenceFormModel model)
{
try
{
var domains = new List<ISet<TermObject>>();
foreach (Fact conjunct in GetPositiveConjuncts(rule.Antecedents.Conjuncts.ToList()))
if (conjunct.VariablesOrEmpty.Contains(varInHead))
domains.Add(GetVarDomainInSentence(varInHead, conjunct, newPossibleConstantsByForm, curDomain, model));
return GetIntersection(domains);
}
catch (Exception e)
{
throw new Exception("Error in rule " + rule + " for variable " + varInHead, e);
}
}
private static ISet<TermObject> GetVarDomainInSentence(TermVariable var1, Fact conjunct,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newPossibleConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomain, ISentenceFormModel model)
{
ISentenceForm form = model.GetSentenceForm(conjunct);
List<Term> tuple = conjunct.NestedTerms.ToList();
var domains = new List<ISet<TermObject>>();
for (int i = 0; i < tuple.Count; i++)
if (Equals(tuple[i], var1))
{
domains.Add(new HashSet<TermObject>(newPossibleConstantsByForm[form][i]));
domains.Add(new HashSet<TermObject>(curDomain[form][i]));
}
return GetIntersection(domains);
}
private static ISet<TermObject> GetIntersection(IReadOnlyList<ISet<TermObject>> domains)
{
if (!domains.Any())
throw new Exception("Unsafe rule has no positive conjuncts");
ISet<TermObject> intersection = new HashSet<TermObject>(domains[0]);
for (int i = 1; i < domains.Count; i++)
intersection.IntersectWith(domains[i]);
return intersection;
}
private static bool RemoveUnneededConstants(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
var newNeededConstantsByForm = new Dictionary<ISentenceForm, MultiDictionary<int, TermObject>>();
foreach (ISentenceForm form in curDomains.Keys)
newNeededConstantsByForm[form] = new MultiDictionary<int, TermObject>(false);
PopulateInitialNeededConstants(newNeededConstantsByForm, curDomains, model);
bool somethingChanged = true;
while (somethingChanged)
somethingChanged = PropagateNeededConstants(newNeededConstantsByForm, curDomains, model);
return RetainNewDomains(curDomains, newNeededConstantsByForm);
}
private static bool RetainNewDomains(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains,
IReadOnlyDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newDomains)
{
bool somethingChanged = false;
foreach (ISentenceForm form in curDomains.Keys.ToList())
{
MultiDictionary<int, TermObject> newDomain = newDomains[form];
//int before = curDomains[form].Count;
var newCurDomain = new MultiDictionary<int, TermObject>(false);
foreach (var mainEntry in curDomains[form].ToImmutableDictionary())
foreach (TermObject entry in mainEntry.Value)
if (newDomain.Contains(mainEntry.Key, entry))
newCurDomain.Add(mainEntry.Key, entry);
somethingChanged |= curDomains[form].Count != newCurDomain.Count;
curDomains[form] = newCurDomain;
}
return somethingChanged;
}
private static bool PropagateNeededConstants(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededConstantsByForm,
Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
bool somethingChanged = ApplyRuleHeadPropagation(neededConstantsByForm, curDomains, model);
return somethingChanged | ApplyRuleBodyOnlyPropagation(neededConstantsByForm, curDomains, model);
}
private static bool ApplyRuleBodyOnlyPropagation(IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededConstantsByForm,
Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
bool somethingChanged = false;
//If a variable does not appear in the head of a variable, then all the values that are in the intersections of all the
//domains from the positive conjuncts containing the variable become needed.
foreach (Implication rule in GetRules(model.Description))
{
Fact head = rule.Consequent;
ISet<TermVariable> varsInHead = head.VariablesOrEmpty.ToImmutableHashSet();
IDictionary<TermVariable, ISet<TermObject>> varDomains = GetVarDomains(rule, curDomains, model);
foreach (TermVariable var in rule.VariablesOrEmpty.ToImmutableHashSet())
{
if (!varsInHead.Contains(var))
{
ISet<TermObject> neededConstants = varDomains[var];
if (neededConstants == null)
throw new Exception(string.Format("var is {0};\nvarDomains key set is {1};\nvarsInHead is {2};\nrule is " + rule, var, varDomains.Keys, varsInHead));
foreach (Expression conjunct in rule.Antecedents.Conjuncts)
somethingChanged |= AddPossibleValuesToConjunct(neededConstants, conjunct, var, neededConstantsByForm, model);
}
}
}
return somethingChanged;
}
class OptimizerSentenceFormDomain : ISentenceFormDomain
{
private readonly ISentenceForm form;
private readonly Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains;
public OptimizerSentenceFormDomain(ISentenceForm form, Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains)
{
this.form = form;
this.curDomains = curDomains;
}
public IEnumerator<Fact> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public ISentenceForm Form { get { return form; } }
public ISet<TermObject> GetDomainForSlot(int slotIndex)
{
return !curDomains.ContainsKey(form)
? JavaHashSet<TermObject>.Empty
: new JavaHashSet<TermObject>(curDomains[form][slotIndex]);
}
}
private class OptimizerSentenceDomainModel : AbstractSentenceDomainModel
{
private readonly Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains;
public OptimizerSentenceDomainModel(ISentenceFormModel formModel, Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains)
: base(formModel)
{
this.curDomains = curDomains;
}
public override ISentenceFormDomain GetDomain(ISentenceForm form)
{
return new OptimizerSentenceFormDomain(form, curDomains);
}
}
private static IDictionary<TermVariable, ISet<TermObject>> GetVarDomains(Implication rule,
Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
var domainModel = new OptimizerSentenceDomainModel(model, curDomains);
return SentenceDomainModels.GetVarDomains(rule, domainModel, SentenceDomainModels.VarDomainOpts.IncludeHead);
}
private static bool ApplyRuleHeadPropagation(Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededConstantsByForm,
Dictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
bool somethingChanged = false;
//If a term that is a variable in the head of a rule needs a particular value, AND that variable is possible (i.e. in the
//current domain) in every appearance of the variable in positive conjuncts in the rule's body, then the value is
//needed in every appearance of the variable in the rule (positive or negative).
foreach (Implication rule in GetRules(model.Description))
{
Fact head = rule.Consequent;
ISentenceForm headForm = model.GetSentenceForm(head);
List<Term> headTuple = head.NestedTerms.ToList();
IDictionary<TermVariable, ISet<TermObject>> varDomains = GetVarDomains(rule, curDomains, model);
for (int i = 0; i < headTuple.Count; i++)
{
//ConcurrencyUtils.checkForInterruption();
var curVar = headTuple[i] as TermVariable;
if (curVar != null)
{
var neededConstants = new HashSet<TermObject>(neededConstantsByForm[headForm][i]);
//Whittle these down based on what's possible throughout the rule
ISet<TermObject> neededAndPossibleConstants = new HashSet<TermObject>(neededConstants);
neededAndPossibleConstants.IntersectWith(varDomains[curVar]);
//Relay those values back to the conjuncts in the rule body
foreach (Expression conjunct in rule.Antecedents.Conjuncts)
somethingChanged |= AddPossibleValuesToConjunct(neededAndPossibleConstants, conjunct, curVar, neededConstantsByForm, model);
}
}
}
return somethingChanged;
}
private static bool AddPossibleValuesToConjunct(ISet<TermObject> neededAndPossibleConstants, Expression conjunct, TermVariable curVar,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededConstantsByForm, ISentenceFormModel model)
{
var fact = conjunct as Fact;
if (fact != null)
return fact.RelationName != GameContainer.Parser.TokDistinct
&& AddPossibleValuesToSentence(neededAndPossibleConstants, fact, curVar, neededConstantsByForm, model);
var negation = conjunct as Negation;
if (negation != null)
return AddPossibleValuesToSentence(neededAndPossibleConstants, (Fact)negation.Negated, curVar, neededConstantsByForm, model);
if (conjunct is Disjunction)
throw new Exception("The SentenceDomainModelOptimizer is not designed for game descriptions with OR. Use the DeORer.");
throw new Exception("Unexpected literal type " + conjunct.GetType() + " for literal " + conjunct);
}
private static bool AddPossibleValuesToSentence(ISet<TermObject> neededAndPossibleConstants, Fact sentence, TermVariable curVar,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededConstantsByForm, ISentenceFormModel model)
{
bool somethingChanged = false;
ISentenceForm form = model.GetSentenceForm(sentence);
List<Term> tuple = sentence.NestedTerms.ToList();
Debug.Assert(form.TupleSize == tuple.Count);
for (int i = 0; i < tuple.Count; i++)
{
if (Equals(tuple[i], curVar))
{
Debug.Assert(neededConstantsByForm[form] != null);
Debug.Assert(neededAndPossibleConstants != null);
var before = neededConstantsByForm[form][i].Count;
neededConstantsByForm[form].AddMany(i, neededAndPossibleConstants);
somethingChanged |= before != neededConstantsByForm[form][i].Count;
}
}
return somethingChanged;
}
private static IEnumerable<Fact> GetPositiveConjuncts(IEnumerable<Expression> body)
{
return body.OfType<Fact>().Where(fact => fact.RelationName != GameContainer.Parser.TokDistinct);
}
/// <summary>
/// Unlike getPositiveConjuncts, this also returns sentences inside NOT literals.
/// </summary>
private static IEnumerable<Fact> GetAllSentencesInBody(List<Expression> body)
{
var sentences = new List<Fact>();
GdlVisitors.VisitAll(body, new GdlVisitor { VisitSentence = sentence => sentences.Add(sentence) });
return sentences;
}
private static IEnumerable<Implication> GetRules(IEnumerable<Expression> description)
{
return description.Where(input => input is Implication).Cast<Implication>();
}
private static readonly ImmutableHashSet<int> AlwaysNeededSentenceNames = ImmutableHashSet.Create(
GameContainer.Parser.TokNext, GameContainer.Parser.TokGoal, GameContainer.Parser.TokLegal,
GameContainer.Parser.TokInit, GameContainer.Parser.TokRole, GameContainer.SymbolTable["base"],
GameContainer.SymbolTable["input"], GameContainer.Parser.TokTrue, GameContainer.Parser.TokDoes);
private static void PopulateInitialNeededConstants(IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newNeededConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> curDomains, ISentenceFormModel model)
{
// If the term model is part of a keyword-named sentence, then it is needed. This includes base and init.
foreach (ISentenceForm form in model.SentenceForms) //ConcurrencyUtils.checkForInterruption();
if (AlwaysNeededSentenceNames.Contains(form.Name))
foreach (var kv in curDomains[form])
newNeededConstantsByForm[form].AddMany(kv.Key, kv.Value);
// If the term has a constant value in some sentence in the BODY of a rule, then it is needed.
foreach (Implication rule in GetRules(model.Description))
foreach (Fact sentence in GetAllSentencesInBody(rule.Antecedents.Conjuncts.ToList()))
AddConstantsFromSentenceIfInOldDomain(newNeededConstantsByForm, curDomains, model, sentence);
}
private static void AddConstantsFromSentenceIfInOldDomain(IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> newConstantsByForm,
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> oldDomain, ISentenceFormModel model, Fact sentence)
{
ISentenceForm form = model.GetSentenceForm(sentence);
List<Term> tuple = sentence.NestedTerms.ToList();
if (tuple.Count != form.TupleSize)
throw new Exception();
for (int i = 0; i < form.TupleSize; i++)
{
var term = tuple[i] as TermObject;
if (term != null && oldDomain[form][i].Contains(term))
newConstantsByForm[form].Add(i, term);
}
}
private static ImmutableSentenceDomainModel ToSentenceDomainModel(
IDictionary<ISentenceForm, MultiDictionary<int, TermObject>> neededAndPossibleConstantsByForm, ISentenceFormModel formModel)
{
var domains = new Dictionary<ISentenceForm, ISentenceFormDomain>();
foreach (ISentenceForm form in formModel.SentenceForms)
domains[form] = new CartesianSentenceFormDomain(form, neededAndPossibleConstantsByForm[form]);
return new ImmutableSentenceDomainModel(formModel, domains);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Tests;
using NUnit.Framework;
namespace Azure.Messaging.ServiceBus.Tests.Sender
{
public class SenderLiveTests : ServiceBusLiveTestBase
{
[Test]
public async Task SendConnStringWithSharedKey()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
await sender.SendMessageAsync(GetMessage());
}
}
[Test]
public async Task SendConnStringWithSignature()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions();
var audience = ServiceBusConnection.BuildConnectionResource(options.TransportType, TestEnvironment.FullyQualifiedNamespace, scope.QueueName);
var connectionString = TestEnvironment.BuildConnectionStringWithSharedAccessSignature(scope.QueueName, audience);
await using var sender = new ServiceBusClient(connectionString, options).CreateSender(scope.QueueName);
await sender.SendMessageAsync(GetMessage());
}
}
[Test]
public async Task SendToken()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.FullyQualifiedNamespace, TestEnvironment.Credential);
var sender = client.CreateSender(scope.QueueName);
await sender.SendMessageAsync(GetMessage());
}
}
[Test]
public async Task SendConnectionTopic()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(GetMessage());
}
}
[Test]
public async Task SendTopicSession()
{
await using (var scope = await ServiceBusScope.CreateWithTopic(enablePartitioning: false, enableSession: false))
{
var options = new ServiceBusClientOptions
{
TransportType = ServiceBusTransportType.AmqpWebSockets,
WebProxy = WebRequest.DefaultWebProxy,
RetryOptions = new ServiceBusRetryOptions()
{
Mode = ServiceBusRetryMode.Exponential
}
};
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString, options);
ServiceBusSender sender = client.CreateSender(scope.TopicName);
await sender.SendMessageAsync(GetMessage("sessionId"));
}
}
[Test]
public async Task CanSendAMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
ServiceBusMessageBatch messageBatch = AddMessages(batch, 3);
await sender.SendMessagesAsync(messageBatch);
}
}
[Test]
public async Task SendingEmptyBatchDoesNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CanSendAnEmptyBodyMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
batch.TryAddMessage(new ServiceBusMessage(Array.Empty<byte>()));
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task CanSendLargeMessageBatch()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: true))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
await AddAndSendMessages();
batch.Clear();
Assert.AreEqual(0, batch.Count);
Assert.AreEqual(0, batch.SizeInBytes);
await AddAndSendMessages();
async Task AddAndSendMessages()
{
// service limits to 4500 messages but we have not added this to our client validation yet
while (batch.Count < 4500 && batch.TryAddMessage(
new ServiceBusMessage(new byte[50])
{
MessageId = "new message ID that takes up some space",
SessionId = "sessionId",
PartitionKey = "sessionId",
ApplicationProperties = { { "key", "value" } }
}))
{
}
if (batch.Count < 4500)
{
// the difference in size from the max allowable size should be less than the size of 1 message
Assert.IsTrue(batch.MaxSizeInBytes - batch.SizeInBytes < 180);
}
Assert.Greater(batch.Count, 0);
await sender.SendMessagesAsync(batch);
}
}
}
[Test]
public async Task CannotSendLargerThanMaximumSize()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch.
ServiceBusMessage message = new ServiceBusMessage(new byte[batch.MaxSizeInBytes + 10]);
Assert.That(async () => await sender.SendMessageAsync(message), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessageSizeExceeded));
}
}
[Test]
public async Task TryAddReturnsFalseIfSizeExceed()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
ServiceBusSender sender = client.CreateSender(scope.QueueName);
using ServiceBusMessageBatch batch = await sender.CreateMessageBatchAsync();
// Actual limit is set by the service; query it from the batch. Because this will be used for the
// message body, leave some padding for the conversion and batch envelope.
var padding = 500;
var size = (batch.MaxSizeInBytes - padding);
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[size])), Is.True, "A message was rejected by the batch; all messages should be accepted.");
Assert.That(() => batch.TryAddMessage(new ServiceBusMessage(new byte[padding + 1])), Is.False, "A message was rejected by the batch; message size exceed.");
await sender.SendMessagesAsync(batch);
}
}
[Test]
public async Task ClientProperties()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.AreEqual(scope.QueueName, sender.EntityPath);
Assert.AreEqual(TestEnvironment.FullyQualifiedNamespace, sender.FullyQualifiedNamespace);
}
}
[Test]
public async Task Schedule()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var seq = await sender.ScheduleMessageAsync(GetMessage(), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
await sender.CancelScheduledMessageAsync(seq);
msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
}
[Test]
public async Task ScheduleMultipleArray()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: sequenceNums);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty array
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Array.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleList()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>(sequenceNums));
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty list
await sender.CancelScheduledMessagesAsync(sequenceNumbers: new List<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task ScheduleMultipleEnumerable()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
await using var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNums = await sender.ScheduleMessagesAsync(GetMessages(5), scheduleTime);
await using var receiver = client.CreateReceiver(scope.QueueName);
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
// use an enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: GetEnumerable());
IEnumerable<long> GetEnumerable()
{
foreach (long seq in sequenceNums)
{
yield return seq;
}
}
foreach (long seq in sequenceNums)
{
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(seq);
Assert.IsNull(msg);
}
// can cancel empty enumerable
await sender.CancelScheduledMessagesAsync(sequenceNumbers: Enumerable.Empty<long>());
// cannot cancel null
Assert.That(
async () => await sender.CancelScheduledMessagesAsync(sequenceNumbers: null),
Throws.InstanceOf<ArgumentNullException>());
}
}
[Test]
public async Task CloseSenderShouldNotCloseConnection()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
var scheduleTime = DateTimeOffset.UtcNow.AddHours(10);
var sequenceNum = await sender.ScheduleMessageAsync(GetMessage(), scheduleTime);
await sender.DisposeAsync(); // shouldn't close connection, but should close send link
Assert.That(async () => await sender.SendMessageAsync(GetMessage()), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.ScheduleMessageAsync(GetMessage(), default), Throws.InstanceOf<ObjectDisposedException>());
Assert.That(async () => await sender.CancelScheduledMessageAsync(sequenceNum), Throws.InstanceOf<ObjectDisposedException>());
// receive should still work
await using var receiver = client.CreateReceiver(scope.QueueName);
ServiceBusReceivedMessage msg = await receiver.PeekMessageAsync(sequenceNum);
Assert.AreEqual(0, Convert.ToInt32(new TimeSpan(scheduleTime.Ticks - msg.ScheduledEnqueueTime.Ticks).TotalSeconds));
}
}
[Test]
public async Task CreateSenderWithoutParentReference()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
await sender.SendMessageAsync(GetMessage());
}
}
}
[Test]
public async Task SendSessionMessageToNonSessionfulEntityShouldNotThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
await using var client = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);
var sender = client.CreateSender(scope.QueueName);
// this is apparently supported. The session is ignored by the service but can be used
// as additional app data. Not recommended.
await sender.SendMessageAsync(GetMessage("sessionId"));
var receiver = client.CreateReceiver(scope.QueueName);
var msg = await receiver.ReceiveMessageAsync();
Assert.AreEqual("sessionId", msg.SessionId);
}
}
[Test]
public async Task SendNonSessionMessageToSessionfulEntityShouldThrow()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: true))
{
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
Assert.That(
async () => await sender.SendMessageAsync(GetMessage()),
Throws.InstanceOf<InvalidOperationException>());
}
}
[Test]
public async Task CanSendReceivedMessage()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var client = new ServiceBusClient(
TestEnvironment.FullyQualifiedNamespace,
TestEnvironment.Credential);
await using var sender = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString).CreateSender(scope.QueueName);
var messageCt = 10;
IEnumerable<ServiceBusMessage> messages = GetMessages(messageCt);
await sender.SendMessagesAsync(messages);
var receiver = client.CreateReceiver(scope.QueueName, new ServiceBusReceiverOptions()
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
});
var remainingMessages = messageCt;
IList<ServiceBusReceivedMessage> receivedMessages = new List<ServiceBusReceivedMessage>();
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(messageCt))
{
remainingMessages--;
receivedMessages.Add(msg);
}
}
foreach (ServiceBusReceivedMessage msg in receivedMessages)
{
await sender.SendMessageAsync(new ServiceBusMessage(msg));
}
var messageEnum = receivedMessages.GetEnumerator();
remainingMessages = messageCt;
while (remainingMessages > 0)
{
foreach (var msg in await receiver.ReceiveMessagesAsync(remainingMessages))
{
remainingMessages--;
messageEnum.MoveNext();
Assert.AreEqual(messageEnum.Current.MessageId, msg.MessageId);
}
}
Assert.AreEqual(0, remainingMessages);
}
}
[Test]
public async Task CreateBatchThrowsIftheEntityDoesNotExist()
{
await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: false, enableSession: false))
{
var connectionString = TestEnvironment.BuildConnectionStringForEntity("FakeEntity");
await using var client = new ServiceBusClient(connectionString);
ServiceBusSender sender = client.CreateSender("FakeEntity");
Assert.That(async () => await sender.CreateMessageBatchAsync(), Throws.InstanceOf<ServiceBusException>().And.Property(nameof(ServiceBusException.Reason)).EqualTo(ServiceBusFailureReason.MessagingEntityNotFound));
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="PerformanceCounters.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Microsoft.Build.Framework;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>Add</i> (<b>Required: </b> CategoryName, CounterList, CategoryHelp <b>Optional: </b> MultiInstance)</para>
/// <para><i>CheckCategoryExists</i> (<b>Required: </b> CategoryName <b>Optional: </b> MachineName)</para>
/// <para><i>CheckCounterExists</i> (<b>Required: </b> CategoryName, CounterName <b>Optional: </b> MachineName)</para>
/// <para><i>GetValue</i> (<b>Required: </b> CategoryName, CounterName <b>Output: </b> Value, MachineName)</para>
/// <para><i>Remove</i> (<b>Required: </b> CategoryName)</para>
/// <para><b>Remote Execution Support:</b> Partial</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <ItemGroup>
/// <!-- Configure some perf counters -->
/// <CounterList Include="foobar.A">
/// <CounterName>ACounter</CounterName>
/// <CounterHelp>A Custom Counter</CounterHelp>
/// <CounterType>CounterTimer</CounterType>
/// </CounterList>
/// <CounterList Include="foobar.A">
/// <CounterName>AnotherCounter</CounterName>
/// <CounterHelp>Another Custom Counter</CounterHelp>
/// <CounterType>CounterTimer</CounterType>
/// </CounterList>
/// </ItemGroup>
/// <!-- Add a Performance Counter -->
/// <MSBuild.ExtensionPack.Computer.PerformanceCounters TaskAction="Add" CategoryName="YourCustomCategory" CategoryHelp="This is a custom performance counter category" CounterList="@(CounterList)" MultiInstance="true" />
/// <!-- Check whether a Category Exists -->
/// <MSBuild.ExtensionPack.Computer.PerformanceCounters TaskAction="CheckCategoryExists" CategoryName="aYourCustomCategory">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Computer.PerformanceCounters>
/// <Message Text="aYourCustomCategory - $(DoesExist)"/>
/// <!-- Check whether a Counter Exists -->
/// <MSBuild.ExtensionPack.Computer.PerformanceCounters TaskAction="CheckCounterExists" CategoryName="aYourCustomCategory" CounterName="AnotherCounter">
/// <Output TaskParameter="Exists" PropertyName="DoesExist"/>
/// </MSBuild.ExtensionPack.Computer.PerformanceCounters>
/// <Message Text="AnotherCounter - $(DoesExist)"/>
/// <!-- Remove a Performance Counter -->
/// <MSBuild.ExtensionPack.Computer.PerformanceCounters TaskAction="Remove" CategoryName="YourCustomCategory"/>
/// <!-- Get a Performance Counter value-->
/// <MSBuild.ExtensionPack.Computer.PerformanceCounters TaskAction="GetValue" CategoryName="Memory" CounterName="Available MBytes">
/// <Output PropertyName="TheValue" TaskParameter="Value"/>
/// </MSBuild.ExtensionPack.Computer.PerformanceCounters>
/// <Message Text="Available MBytes: $(TheValue)"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class PerformanceCounters : BaseTask
{
private const string AddTaskAction = "Add";
private const string CheckCategoryExistsTaskAction = "CheckCategoryExists";
private const string CheckCounterExistsTaskAction = "CheckCounterExists";
private const string GetValueTaskAction = "GetValue";
private const string RemoveTaskAction = "Remove";
/// <summary>
/// Sets the CategoryName
/// </summary>
[Required]
public string CategoryName { get; set; }
/// <summary>
/// Sets the description of the custom category.
/// </summary>
public string CategoryHelp { get; set; }
/// <summary>
/// Gets the value of the counter
/// </summary>
[Output]
public string Value { get; set; }
/// <summary>
/// Sets the name of the counter.
/// </summary>
public string CounterName { get; set; }
/// <summary>
/// Sets a value indicating whether to create a multiple instance performance counter. Default is false
/// </summary>
public bool MultiInstance { get; set; }
/// <summary>
/// Gets whether the item exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Sets the TaskItem[] that specifies the counters to create as part of the new category.
/// </summary>
public ITaskItem[] CounterList { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
switch (this.TaskAction)
{
case AddTaskAction:
this.Add();
break;
case RemoveTaskAction:
this.Remove();
break;
case GetValueTaskAction:
this.GetValue();
break;
case CheckCategoryExistsTaskAction:
this.LogTaskMessage(MessageImportance.Normal, string.Format(CultureInfo.CurrentCulture, "Checking whether Performance Counter Category: {0} exists on : {1}", this.CategoryName, this.MachineName));
this.Exists = PerformanceCounterCategory.Exists(this.CategoryName, this.MachineName);
break;
case CheckCounterExistsTaskAction:
this.Exists = this.CheckCounterExists();
break;
default:
this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private bool CheckCounterExists()
{
if (string.IsNullOrEmpty(this.CounterName))
{
Log.LogError("CounterName is required");
return false;
}
if (!PerformanceCounterCategory.Exists(this.CategoryName, this.MachineName))
{
this.LogTaskWarning(string.Format(CultureInfo.CurrentCulture, "Performance Counter Category not found: {0}", this.CategoryName));
return false;
}
PerformanceCounterCategory cat = new PerformanceCounterCategory(this.CategoryName, this.MachineName);
PerformanceCounter[] counters = cat.GetCounters();
return counters.Any(c => c.CounterName == this.CounterName);
}
private void GetValue()
{
if (PerformanceCounterCategory.Exists(this.CategoryName, this.MachineName))
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Getting Performance Counter: {0} from: {1} on: {2}", this.CounterName, this.CategoryName, this.MachineName));
using (PerformanceCounter pc = new PerformanceCounter(this.CategoryName, this.CounterName, null, this.MachineName))
{
this.Value = pc.NextValue().ToString(CultureInfo.CurrentCulture);
}
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Performance Counter Category not found: {0}", this.CategoryName));
}
}
private void Add()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Adding Performance Counter Category: {0}", this.CategoryName));
CounterCreationDataCollection colCounterCreationData = new CounterCreationDataCollection();
colCounterCreationData.Clear();
if (PerformanceCounterCategory.Exists(this.CategoryName))
{
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Removing Performance Counter Category: {0}", this.CategoryName));
PerformanceCounterCategory.Delete(this.CategoryName);
}
foreach (ITaskItem counter in this.CounterList)
{
string counterName = counter.GetMetadata("CounterName");
string counterHelp = counter.GetMetadata("CounterHelp");
PerformanceCounterType counterType = (PerformanceCounterType)Enum.Parse(typeof(PerformanceCounterType), counter.GetMetadata("CounterType"));
this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Adding Performance Counter: {0}", counterName));
CounterCreationData objCreateCounter = new CounterCreationData(counterName, counterHelp, counterType);
colCounterCreationData.Add(objCreateCounter);
}
if (colCounterCreationData.Count > 0)
{
PerformanceCounterCategoryType categoryType = PerformanceCounterCategoryType.SingleInstance;
if (this.MultiInstance)
{
categoryType = PerformanceCounterCategoryType.MultiInstance;
}
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Performance Counter Category: {0}", this.CategoryName));
PerformanceCounterCategory.Create(this.CategoryName, this.CategoryHelp, categoryType, colCounterCreationData);
}
}
private void Remove()
{
if (PerformanceCounterCategory.Exists(this.CategoryName))
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Removing Performance Counter Category: {0}", this.CategoryName));
PerformanceCounterCategory.Delete(this.CategoryName);
}
else
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Performance Counter Category not found: {0}", this.CategoryName));
}
}
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections;
using System.IO;
using System.Text;
namespace log4net.DateFormatter
{
/// <summary>
/// Formats a <see cref="DateTime"/> as <c>"HH:mm:ss,fff"</c>.
/// </summary>
/// <remarks>
/// <para>
/// Formats a <see cref="DateTime"/> in the format <c>"HH:mm:ss,fff"</c> for example, <c>"15:49:37,459"</c>.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public class AbsoluteTimeDateFormatter : IDateFormatter
{
#region Protected Instance Methods
/// <summary>
/// Renders the date into a string. Format is <c>"HH:mm:ss"</c>.
/// </summary>
/// <param name="dateToFormat">The date to render into a string.</param>
/// <param name="buffer">The string builder to write to.</param>
/// <remarks>
/// <para>
/// Subclasses should override this method to render the date
/// into a string using a precision up to the second. This method
/// will be called at most once per second and the result will be
/// reused if it is needed again during the same second.
/// </para>
/// </remarks>
virtual protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer)
{
int hour = dateToFormat.Hour;
if (hour < 10)
{
buffer.Append('0');
}
buffer.Append(hour);
buffer.Append(':');
int mins = dateToFormat.Minute;
if (mins < 10)
{
buffer.Append('0');
}
buffer.Append(mins);
buffer.Append(':');
int secs = dateToFormat.Second;
if (secs < 10)
{
buffer.Append('0');
}
buffer.Append(secs);
}
#endregion Protected Instance Methods
#region Implementation of IDateFormatter
/// <summary>
/// Renders the date into a string. Format is "HH:mm:ss,fff".
/// </summary>
/// <param name="dateToFormat">The date to render into a string.</param>
/// <param name="writer">The writer to write to.</param>
/// <remarks>
/// <para>
/// Uses the <see cref="FormatDateWithoutMillis"/> method to generate the
/// time string up to the seconds and then appends the current
/// milliseconds. The results from <see cref="FormatDateWithoutMillis"/> are
/// cached and <see cref="FormatDateWithoutMillis"/> is called at most once
/// per second.
/// </para>
/// <para>
/// Sub classes should override <see cref="FormatDateWithoutMillis"/>
/// rather than <see cref="FormatDate"/>.
/// </para>
/// </remarks>
virtual public void FormatDate(DateTime dateToFormat, TextWriter writer)
{
// Calculate the current time precise only to the second
long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond));
string timeString = null;
// Compare this time with the stored last time
// If we are in the same second then append
// the previously calculated time string
if (s_lastTimeToTheSecond != currentTimeToTheSecond)
{
s_lastTimeStrings.Clear();
}
else
{
timeString = (string) s_lastTimeStrings[GetType()];
}
if (timeString == null)
{
// lock so that only one thread can use the buffer and
// update the s_lastTimeToTheSecond and s_lastTimeStrings
// PERF: Try removing this lock and using a new StringBuilder each time
lock(s_lastTimeBuf)
{
timeString = (string) s_lastTimeStrings[GetType()];
if (timeString == null)
{
// We are in a new second.
s_lastTimeBuf.Length = 0;
// Calculate the new string for this second
FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf);
// Render the string buffer to a string
timeString = s_lastTimeBuf.ToString();
#if NET_1_1
// Ensure that the above string is written into the variable NOW on all threads.
// This is only required on multiprocessor machines with weak memeory models
System.Threading.Thread.MemoryBarrier();
#endif
// Store the time as a string (we only have to do this once per second)
s_lastTimeStrings[GetType()] = timeString;
s_lastTimeToTheSecond = currentTimeToTheSecond;
}
}
}
writer.Write(timeString);
// Append the current millisecond info
writer.Write(',');
int millis = dateToFormat.Millisecond;
if (millis < 100)
{
writer.Write('0');
}
if (millis < 10)
{
writer.Write('0');
}
writer.Write(millis);
}
#endregion Implementation of IDateFormatter
#region Public Static Fields
/// <summary>
/// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is <b>ABSOLUTE</b>.
/// </summary>
public const string AbsoluteTimeDateFormat = "ABSOLUTE";
/// <summary>
/// String constant used to specify DateTimeDateFormat in layouts. Current value is <b>DATE</b>.
/// </summary>
public const string DateAndTimeDateFormat = "DATE";
/// <summary>
/// String constant used to specify ISO8601DateFormat in layouts. Current value is <b>ISO8601</b>.
/// </summary>
public const string Iso8601TimeDateFormat = "ISO8601";
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// Last stored time with precision up to the second.
/// </summary>
private static long s_lastTimeToTheSecond = 0;
/// <summary>
/// Last stored time with precision up to the second, formatted
/// as a string.
/// </summary>
private static StringBuilder s_lastTimeBuf = new StringBuilder();
/// <summary>
/// Last stored time with precision up to the second, formatted
/// as a string.
/// </summary>
private static Hashtable s_lastTimeStrings = new Hashtable();
#endregion Private Static Fields
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Methods for Parsing numbers and Strings.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.CompilerServices;
namespace System
{
internal static class ParseNumbers
{
internal const int LeftAlign = 0x0001;
internal const int RightAlign = 0x0004;
internal const int PrefixSpace = 0x0008;
internal const int PrintSign = 0x0010;
internal const int PrintBase = 0x0020;
internal const int PrintAsI1 = 0x0040;
internal const int PrintAsI2 = 0x0080;
internal const int PrintAsI4 = 0x0100;
internal const int TreatAsUnsigned = 0x0200;
internal const int TreatAsI1 = 0x0400;
internal const int TreatAsI2 = 0x0800;
internal const int IsTight = 0x1000;
internal const int NoSpace = 0x2000;
internal const int PrintRadixBase = 0x4000;
private const int MinRadix = 2;
private const int MaxRadix = 36;
public unsafe static long StringToLong(System.String s, int radix, int flags)
{
int pos = 0;
return StringToLong(s, radix, flags, ref pos);
}
public static long StringToLong(string s, int radix, int flags, ref int currPos)
{
long result = 0;
int sign = 1;
int length;
int i;
int grabNumbersStart = 0;
int r;
if (s != null)
{
i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
grabNumbersStart = i;
result = GrabLongs(r, s, ref i, (flags & TreatAsUnsigned) != 0);
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
//If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((ulong)result == 0x8000000000000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
throw new OverflowException(SR.Overflow_Int64);
if (r == 10)
result *= sign;
}
else
{
result = 0;
}
return result;
}
public static int StringToInt(string s, int radix, int flags)
{
int pos = 0;
return StringToInt(s, radix, flags, ref pos);
}
public static int StringToInt(string s, int radix, int flags, ref int currPos)
{
int result = 0;
int sign = 1;
int length;
int i;
int grabNumbersStart = 0;
int r;
if (s != null)
{
// They're requied to tell me where to start parsing.
i = currPos;
// Do some radix checking.
// A radix of -1 says to use whatever base is spec'd on the number.
// Parse in Base10 until we figure out what the base actually is.
r = (-1 == radix) ? 10 : radix;
if (r != 2 && r != 10 && r != 8 && r != 16)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
length = s.Length;
if (i < 0 || i >= length)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index);
// Get rid of the whitespace and then check that we've still got some digits to parse.
if (((flags & IsTight) == 0) && ((flags & NoSpace) == 0))
{
EatWhiteSpace(s, ref i);
if (i == length)
throw new FormatException(SR.Format_EmptyInputString);
}
// Check for a sign
if (s[i] == '-')
{
if (r != 10)
throw new ArgumentException(SR.Arg_CannotHaveNegativeValue);
if ((flags & TreatAsUnsigned) != 0)
throw new OverflowException(SR.Overflow_NegativeUnsigned);
sign = -1;
i++;
}
else if (s[i] == '+')
{
i++;
}
// Consume the 0x if we're in an unknown base or in base-16.
if ((radix == -1 || radix == 16) && (i + 1 < length) && s[i] == '0')
{
if (s[i + 1] == 'x' || s[i + 1] == 'X')
{
r = 16;
i += 2;
}
}
grabNumbersStart = i;
result = GrabInts(r, s, ref i, ((flags & TreatAsUnsigned) != 0));
// Check if they passed us a string with no parsable digits.
if (i == grabNumbersStart)
throw new FormatException(SR.Format_NoParsibleDigits);
if ((flags & IsTight) != 0)
{
// If we've got effluvia left at the end of the string, complain.
if (i < length)
throw new FormatException(SR.Format_ExtraJunkAtEnd);
}
// Put the current index back into the correct place.
currPos = i;
// Return the value properly signed.
if ((flags & TreatAsI1) != 0)
{
if ((uint)result > 0xFF)
throw new OverflowException(SR.Overflow_SByte);
}
else if ((flags & TreatAsI2) != 0)
{
if ((uint)result > 0xFFFF)
throw new OverflowException(SR.Overflow_Int16);
}
else if ((uint)result == 0x80000000 && sign == 1 && r == 10 && ((flags & TreatAsUnsigned) == 0))
{
throw new OverflowException(SR.Overflow_Int32);
}
if (r == 10)
result *= sign;
}
else
{
result = 0;
}
return result;
}
public static String IntToString(int n, int radix, int width, char paddingChar, int flags)
{
bool isNegative = false;
int index = 0;
int buffLength;
int i;
uint l;
char[] buffer = new char[66]; // Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
// If the number is negative, make it positive and remember the sign.
// If the number is MIN_VALUE, this will still be negative, so we'll have to
// special case this later.
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
if (10 == radix)
l = (uint)-n;
else
l = (uint)n;
}
else
{
l = (uint)n;
}
// The conversion to a uint will sign extend the number. In order to ensure
// that we only get as many bits as we expect, we chop the number.
if ((flags & PrintAsI1) != 0)
l &= 0xFF;
else if ((flags & PrintAsI2) != 0)
l &= 0xFFFF;
// Special case the 0.
if (0 == l)
{
buffer[0] = '0';
index = 1;
}
else
{
do
{
uint charVal = l % (uint)radix;
l /= (uint)radix;
if (charVal < 10)
buffer[index++] = (char)(charVal + '0');
else
buffer[index++] = (char)(charVal + 'a' - 10);
}
while (l != 0);
}
// If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
}
if (10 == radix)
{
// If it was negative, append the sign, else if they requested, add the '+'.
// If they requested a leading space, put it on.
if (isNegative)
buffer[index++] = '-';
else if ((flags & PrintSign) != 0)
buffer[index++] = '+';
else if ((flags & PrefixSpace) != 0)
buffer[index++] = ' ';
}
// Figure out the size of our string.
if (width <= index)
buffLength = index;
else
buffLength = width;
StringBuilder sb = new StringBuilder(buffLength);
// Put the characters into the String in reverse order
// Fill the remaining space -- if there is any --
// with the correct padding character.
if ((flags & LeftAlign) != 0)
{
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
}
else
{
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
}
return sb.ToString();
}
public static String LongToString(long n, int radix, int width, char paddingChar, int flags)
{
bool isNegative = false;
int index = 0;
int charVal;
ulong ul;
int i;
int buffLength = 0;
char[] buffer = new char[67];//Longest possible string length for an integer in binary notation with prefix
if (radix < MinRadix || radix > MaxRadix)
throw new ArgumentException(SR.Arg_InvalidBase, "radix");
//If the number is negative, make it positive and remember the sign.
if (n < 0)
{
isNegative = true;
// For base 10, write out -num, but other bases write out the
// 2's complement bit pattern
if (10 == radix)
ul = (ulong)(-n);
else
ul = (ulong)n;
}
else
{
ul = (ulong)n;
}
if ((flags & PrintAsI1) != 0)
ul = ul & 0xFF;
else if ((flags & PrintAsI2) != 0)
ul = ul & 0xFFFF;
else if ((flags & PrintAsI4) != 0)
ul = ul & 0xFFFFFFFF;
//Special case the 0.
if (0 == ul)
{
buffer[0] = '0';
index = 1;
}
else
{
//Pull apart the number and put the digits (in reverse order) into the buffer.
for (index = 0; ul > 0; ul = ul / (ulong)radix, index++)
{
if ((charVal = (int)(ul % (ulong)radix)) < 10)
buffer[index] = (char)(charVal + '0');
else
buffer[index] = (char)(charVal + 'a' - 10);
}
}
//If they want the base, append that to the string (in reverse order)
if (radix != 10 && ((flags & PrintBase) != 0))
{
if (16 == radix)
{
buffer[index++] = 'x';
buffer[index++] = '0';
}
else if (8 == radix)
{
buffer[index++] = '0';
}
else if ((flags & PrintRadixBase) != 0)
{
buffer[index++] = '#';
buffer[index++] = (char)((radix % 10) + '0');
buffer[index++] = (char)((radix / 10) + '0');
}
}
if (10 == radix)
{
//If it was negative, append the sign.
if (isNegative)
{
buffer[index++] = '-';
}
//else if they requested, add the '+';
else if ((flags & PrintSign) != 0)
{
buffer[index++] = '+';
}
//If they requested a leading space, put it on.
else if ((flags & PrefixSpace) != 0)
{
buffer[index++] = ' ';
}
}
//Figure out the size of our string.
if (width <= index)
buffLength = index;
else
buffLength = width;
StringBuilder sb = new StringBuilder(buffLength);
//Put the characters into the String in reverse order
//Fill the remaining space -- if there is any --
//with the correct padding character.
if ((flags & LeftAlign) != 0)
{
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
}
else
{
if (buffLength > index)
sb.Append(paddingChar, buffLength - index);
for (i = 0; i < index; i++)
sb.Append(buffer[index - i - 1]);
}
return sb.ToString();
}
private static void EatWhiteSpace(string s, ref int i)
{
for (; i < s.Length && char.IsWhiteSpace(s[i]); i++)
;
}
private static long GrabLongs(int radix, string s, ref int i, bool isUnsigned)
{
ulong result = 0;
int value;
ulong maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = 0x7FFFFFFFFFFFFFFF / 10;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || ((long)result) < 0)
throw new OverflowException(SR.Overflow_Int64);
result = result * (ulong)radix + (ulong)value;
i++;
}
if ((long)result < 0 && result != 0x8000000000000000)
throw new OverflowException(SR.Overflow_Int64);
}
else
{
maxVal = 0xffffffffffffffff / (ulong)radix;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
throw new OverflowException(SR.Overflow_UInt64);
ulong temp = result * (ulong)radix + (ulong)value;
if (temp < result) // this means overflow as well
throw new OverflowException(SR.Overflow_UInt64);
result = temp;
i++;
}
}
return (long)result;
}
private static int GrabInts(int radix, string s, ref int i, bool isUnsigned)
{
uint result = 0;
int value;
uint maxVal;
// Allow all non-decimal numbers to set the sign bit.
if (radix == 10 && !isUnsigned)
{
maxVal = (0x7FFFFFFF / 10);
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal || (int)result < 0)
throw new OverflowException(SR.Overflow_Int32);
result = result * (uint)radix + (uint)value;
i++;
}
if ((int)result < 0 && result != 0x80000000)
throw new OverflowException(SR.Overflow_Int32);
}
else
{
maxVal = 0xffffffff / (uint)radix;
// Read all of the digits and convert to a number
while (i < s.Length && (IsDigit(s[i], radix, out value)))
{
// Check for overflows - this is sufficient & correct.
if (result > maxVal)
throw new OverflowException(SR.Overflow_UInt32);
// the above check won't cover 4294967296 to 4294967299
uint temp = result * (uint)radix + (uint)value;
if (temp < result) // this means overflow as well
throw new OverflowException(SR.Overflow_UInt32);
result = temp;
i++;
}
}
return (int)result;
}
private static bool IsDigit(char c, int radix, out int result)
{
if (c >= '0' && c <= '9')
result = c - '0';
else if (c >= 'A' && c <= 'Z')
result = c - 'A' + 10;
else if (c >= 'a' && c <= 'z')
result = c - 'a' + 10;
else
result = -1;
if ((result >= 0) && (result < radix))
return true;
return false;
}
}
}
| |
using System.Linq;
using NUnit.Framework;
using ServiceStack.Webhooks.ServiceModel.Types;
namespace ServiceStack.Webhooks.IntTests
{
[TestFixture]
public abstract class GivenNoUserWithSubscriptionStoreBase
{
private ISubscriptionStore store;
[SetUp]
public void Initialize()
{
store = GetSubscriptionStore();
store.InitSchema();
}
[Test, Category("Integration")]
public void WhenAdd_ThenReturnsId()
{
var id = store.Add(new WebhookSubscription
{
Event = "aneventname"
});
Assert.That(id.IsEntityId());
var result = store.Get(null, "aneventname");
Assert.That(result.Id, Is.EqualTo(id));
}
[Test, Category("Integration")]
public void WhenGetAndUnknownSubscription_ThenReturnsNull()
{
var result = store.Get(null, "aneventname");
Assert.That(result, Is.Null);
}
[Test, Category("Integration")]
public void WhenGetAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname"
});
var result = store.Get(null, "aneventname");
Assert.That(result.Event, Is.EqualTo("aneventname"));
}
[Test, Category("Integration")]
public void WhenFind_ThenReturnsNoSubscriptions()
{
var results = store.Find(null);
Assert.That(results.Count, Is.EqualTo(0));
}
[Test, Category("Integration")]
public void WhenFindAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname"
});
var results = store.Find(null)
.OrderBy(e => e.Event)
.ToList();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Event, Is.EqualTo("aneventname"));
}
[Test, Category("Integration")]
public void WhenFindAndExistingSubscriptions_ThenReturnsSubscriptions()
{
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1"
});
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname2"
});
var results = store.Find(null)
.OrderBy(e => e.Event)
.ToList();
Assert.That(results.Count, Is.EqualTo(2));
Assert.That(results[0].Event, Is.EqualTo("aneventname1"));
Assert.That(results[1].Event, Is.EqualTo("aneventname2"));
}
[Test, Category("Integration")]
public void WhenSearch_ThenReturnsNoSubscriptions()
{
var results = store.Search("aneventname", null);
Assert.That(results.Count, Is.EqualTo(0));
}
[Test, Category("Integration")]
public void WhenSearchAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname",
Config = new SubscriptionConfig
{
Url = "aurl"
}
});
var results = store.Search("aneventname", null)
.ToList();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Config.Url, Is.EqualTo("aurl"));
}
[Test, Category("Integration")]
public void WhenSearchAndExistingSubscriptions_ThenReturnsSubscriptions()
{
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1",
Config = new SubscriptionConfig
{
Url = "aurl1"
}
});
store.Add(new WebhookSubscription
{
CreatedById = null,
Event = "aneventname2",
Config = new SubscriptionConfig
{
Url = "aurl2"
}
});
var results = store.Search("aneventname1", null)
.ToList();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Config.Url, Is.EqualTo("aurl1"));
}
[Test, Category("Integration")]
public void WhenUpdateAndExists_ThenUpdates()
{
var subscription = new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
subscription.Name = "anewname";
store.Update(subscriptionId, subscription);
var result = store.Get(null, "aneventname1");
Assert.That(result.Id, Is.EqualTo(subscriptionId));
Assert.That(result.Event, Is.EqualTo("aneventname1"));
Assert.That(result.Name, Is.EqualTo("anewname"));
}
[Test, Category("Integration")]
public void WhenDeleteAndExists_ThenDeletes()
{
var subscription = new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
subscription.Name = "anewname";
store.Delete(subscriptionId);
var result = store.Get(null, "aneventname1");
Assert.That(result, Is.Null);
}
[Test, Category("Integration")]
public void WhenAddHistory_ThenAdds()
{
var subscription = new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
store.Add(subscriptionId, new SubscriptionDeliveryResult
{
Id = "aresultid",
SubscriptionId = subscriptionId
});
var result = store.Search(subscriptionId, 100);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result[0].Id, Is.EqualTo("aresultid"));
}
public abstract ISubscriptionStore GetSubscriptionStore();
}
[TestFixture]
public abstract class GivenAUserWithSubscriptionStoreBase
{
private ISubscriptionStore store;
[SetUp]
public void Initialize()
{
store = GetSubscriptionStore();
store.InitSchema();
}
[Test, Category("Integration")]
public void WhenAdd_ThenReturnsId()
{
var id = store.Add(new WebhookSubscription
{
Event = "aneventname",
CreatedById = "auserid"
});
Assert.That(id.IsEntityId());
var result = store.Get("auserid", "aneventname");
Assert.That(result.Id, Is.EqualTo(id));
}
[Test, Category("Integration")]
public void WhenGetAndUnknownSubscription_ThenReturnsNull()
{
var result = store.Get("auserid", "aneventname");
Assert.That(result, Is.Null);
}
[Test, Category("Integration")]
public void WhenGetAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname"
});
var result = store.Get("auserid", "aneventname");
Assert.That(result.Event, Is.EqualTo("aneventname"));
}
[Test, Category("Integration")]
public void WhenFind_ThenReturnsNoSubscriptions()
{
var results = store.Find("auserid");
Assert.That(results.Count, Is.EqualTo(0));
}
[Test, Category("Integration")]
public void WhenFindAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname"
});
var results = store.Find("auserid")
.OrderBy(e => e.Event)
.ToList();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Event, Is.EqualTo("aneventname"));
}
[Test, Category("Integration")]
public void WhenFindAndExistingSubscriptions_ThenReturnsSubscriptions()
{
store.Add(new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname1"
});
store.Add(new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname2"
});
var results = store.Find("auserid")
.OrderBy(e => e.Event)
.ToList();
Assert.That(results.Count, Is.EqualTo(2));
Assert.That(results[0].Event, Is.EqualTo("aneventname1"));
Assert.That(results[1].Event, Is.EqualTo("aneventname2"));
}
[Test, Category("Integration")]
public void WhenSearch_ThenReturnsNoSubscriptions()
{
var results = store.Search("aneventname", null);
Assert.That(results.Count, Is.EqualTo(0));
}
[Test, Category("Integration")]
public void WhenSearchAndExistingSubscription_ThenReturnsSubscription()
{
store.Add(new WebhookSubscription
{
CreatedById = "auserid1",
Event = "aneventname",
Config = new SubscriptionConfig
{
Url = "aurl"
}
});
var results = store.Search("aneventname", null)
.ToList();
Assert.That(results.Count, Is.EqualTo(1));
Assert.That(results[0].Config.Url, Is.EqualTo("aurl"));
}
[Test, Category("Integration")]
public void WhenSearchAndExistingSubscriptions_ThenReturnsSubscriptions()
{
store.Add(new WebhookSubscription
{
CreatedById = "auserid1",
Event = "aneventname",
Config = new SubscriptionConfig
{
Url = "aurl1"
}
});
store.Add(new WebhookSubscription
{
CreatedById = "auserid2",
Event = "aneventname",
Config = new SubscriptionConfig
{
Url = "aurl2"
}
});
var results = store.Search("aneventname", null)
.OrderBy(r => r.Config.Url)
.ToList();
Assert.That(results.Count, Is.EqualTo(2));
Assert.That(results[0].Config.Url, Is.EqualTo("aurl1"));
Assert.That(results[1].Config.Url, Is.EqualTo("aurl2"));
}
[Test, Category("Integration")]
public void WhenUpdateAndExists_ThenUpdates()
{
var subscription = new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
subscription.Name = "anewname";
store.Update(subscriptionId, subscription);
var result = store.Get("auserid", "aneventname1");
Assert.That(result.Id, Is.EqualTo(subscriptionId));
Assert.That(result.Event, Is.EqualTo("aneventname1"));
Assert.That(result.Name, Is.EqualTo("anewname"));
Assert.That(result.CreatedById, Is.EqualTo("auserid"));
}
[Test, Category("Integration")]
public void WhenDeleteAndExists_ThenDeletes()
{
var subscription = new WebhookSubscription
{
CreatedById = "auserid",
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
subscription.Name = "anewname";
store.Delete(subscriptionId);
var result = store.Get("auserid", "aneventname1");
Assert.That(result, Is.Null);
}
[Test, Category("Integration")]
public void WhenAddHistory_ThenAdds()
{
var subscription = new WebhookSubscription
{
CreatedById = null,
Event = "aneventname1"
};
var subscriptionId = store.Add(subscription);
store.Add(subscriptionId, new SubscriptionDeliveryResult
{
Id = "aresultid",
SubscriptionId = subscriptionId
});
var result = store.Search(subscriptionId, 100);
Assert.That(result.Count, Is.EqualTo(1));
Assert.That(result[0].Id, Is.EqualTo("aresultid"));
}
public abstract ISubscriptionStore GetSubscriptionStore();
}
}
| |
//
// ArtworkDisplay.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright 2009 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 Clutter;
using Hyena.Data;
using Hyena.Collections;
using Banshee.Base;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Gui;
using Banshee.Collection.Database;
namespace Cubano.NowPlaying
{
internal class ActorCache : LruCache<string, Actor>
{
public ActorCache (int maxCount) : base (maxCount)
{
}
public static int GetActorCountForScreen (double textureSize)
{
return GetActorCountForScreen (textureSize, Gdk.Screen.Default);
}
public static int GetActorCountForScreen (double textureSize, Gdk.Screen screen)
{
return GetActorCountForArea (textureSize, screen.Width, screen.Height);
}
public static int GetActorCountForArea (double textureSize, int areaWidth, int areaHeight)
{
return (int)(Math.Ceiling (areaWidth / textureSize) * Math.Ceiling (areaHeight / textureSize));
}
}
internal class AlbumArtActor : Texture
{
private static ArtworkManager artwork_manager;
private AlbumInfo album;
public AlbumInfo Album {
get { return album; }
}
public AlbumArtActor (IntPtr raw) : base (raw)
{
}
public AlbumArtActor (AlbumInfo album, double textureSize) : base ()
{
if (artwork_manager == null && ServiceManager.Contains<ArtworkManager> ()) {
artwork_manager = ServiceManager.Get<ArtworkManager> ();
}
var image = artwork_manager.LookupScalePixbuf (album.ArtworkId, (int)textureSize);
if (image != null) {
SetFromRgbData (image.Pixels, image.HasAlpha, image.Width, image.Height,
image.Rowstride, image.HasAlpha ? 4 : 3, TextureFlags.None);
}
this.album = album;
}
}
public class ArtworkDisplay : Actor
{
private static readonly double ActorSize = 100;
private ActorCache actor_cache = new ActorCache (ActorCache.GetActorCountForScreen (ActorSize));
private Random random = new Random ();
private int allocation_seed;
private Clone [,] grid = null;
private float last_alloc_width, last_alloc_height;
private int visible_grid_width, visible_grid_height;
private int visible_actor_count;
private Timeline cell_select_timeline;
private bool paused = true;
public ArtworkDisplay () : base ()
{
SetSource (ServiceManager.SourceManager.MusicLibrary);
cell_select_timeline = new Timeline () {
Duration = 500,
Loop = true
};
cell_select_timeline.NewFrame += OnCellSelectTimelineNewFrame;
allocation_seed = random.Next ();
}
public ArtworkDisplay (IntPtr raw) : base (raw)
{
}
private void BuildCloneGrid ()
{
if (grid != null) {
return;
}
float pixel_x = 0;
float pixel_y = 0;
float size = (float)ActorSize;
int grid_width = (int)(Math.Ceiling (Gdk.Screen.Default.Width / size));
int grid_height = (int)(Math.Ceiling (Gdk.Screen.Default.Height / size));
int x = 0, y = 0;
grid = new Clone[grid_width, grid_height];
// Populate a collection with enough clones to build
// a grid large enough to cover the entire screen
for (int i = 0; i < actor_cache.MaxCount; i++) {
var slot = new Clone (null) {
Parent = this,
IsVisible = true
};
slot.Allocate (new ActorBox (pixel_x, pixel_y, size, size));
grid[x, y] = slot;
pixel_x += size;
if (x++ == grid_width - 1) {
x = 0;
y++;
pixel_x = 0;
pixel_y += size;
}
}
}
protected override void OnAllocate (ActorBox box, AllocationFlags flags)
{
base.OnAllocate (box, flags);
float width = Width;
float height = Height;
if (width <= 0 || height <= 0 ||
width == last_alloc_width || height == last_alloc_height ||
Model == null) {
return;
}
// Calculate the number of actors that will fit in our window
visible_actor_count = ActorCache.GetActorCountForArea (ActorSize, (int)Width, (int)Height);
if (visible_actor_count <= 0) {
return;
}
BuildCloneGrid ();
last_alloc_width = width;
last_alloc_height = height;
var rand = new Random (allocation_seed);
float size = (float)ActorSize;
visible_grid_width = (int)(Math.Ceiling (width / size));
visible_grid_height = (int)(Math.Ceiling (height / size));
for (int i = 0; i < visible_actor_count; i++) {
var actor = GetRandomActor (rand);
// Assign the artwork actor to a clone slot in the screen grid
grid[i % visible_grid_width, i / visible_grid_width].Source = actor;
}
Resume ();
}
protected override void OnPainted ()
{
if (grid == null || Width <= 0 || Height <= 0) {
return;
}
Cogl.General.PushMatrix ();
foreach (var child in waiting_for_slot) {
child.Paint ();
}
foreach (var child in grid) {
child.Paint ();
}
Cogl.General.PopMatrix ();
}
#region Animation
private List<Actor> waiting_for_slot = new List<Actor> ();
private Queue<Actor> history_slots = new Queue<Actor> ();
private void OnCellSelectTimelineNewFrame (object o, NewFrameArgs args)
{
if (visible_actor_count <= 0 || visible_grid_width <= 0) {
return;
}
int target_x = 0, target_y = 0;
Clone cell_target = null;
while (cell_target == null) {
int index = random.Next (0, visible_actor_count);
target_x = index % visible_grid_width;
target_y = index / visible_grid_width;
cell_target = grid[target_x, target_y];
if (waiting_for_slot.Contains (cell_target) ||
history_slots.Contains (cell_target)) {
cell_target = null;
}
}
var cell_source = new Clone (GetRandomActor ()) { IsVisible = true, Parent = this };
cell_source.Allocate (cell_target.AllocationGeometry);
waiting_for_slot.Insert (0, cell_source);
history_slots.Enqueue (cell_source);
if (history_slots.Count > 5) {
history_slots.Dequeue ();
}
cell_target.AnimationChain
.SetEasing (AnimationMode.EaseInQuad)
.SetDuration ((uint)random.Next (300, 1500))
.WhenFinished ((a) => {
grid[target_x, target_y] = cell_source;
waiting_for_slot.Remove (cell_source);
QueueRedraw ();
})
.Animate ("opacity", 0);
}
public void Pause ()
{
paused = true;
cell_select_timeline.Pause ();
foreach (var child in waiting_for_slot) {
if (child.AnimationChain.LastAnimation != null) {
child.AnimationChain.LastAnimation.Timeline.Stop ();
}
}
waiting_for_slot.Clear ();
}
public void Resume ()
{
paused = false;
InnerResume ();
}
private void InnerResume ()
{
if (!cell_select_timeline.IsPlaying && !paused) {
cell_select_timeline.Start ();
}
}
#endregion
#region Data Model
private IListModel<AlbumInfo> album_model;
public IListModel<AlbumInfo> Model {
get { return album_model; }
}
public void SetSource (DatabaseSource source)
{
if (album_model != null) {
album_model.Reloaded -= OnModelReloaded;
album_model = null;
}
foreach (IListModel model in source.CurrentFilters) {
album_model = model as IListModel<AlbumInfo>;
if (album_model != null) {
break;
}
}
if (album_model != null) {
album_model.Reloaded += OnModelReloaded;
}
QueueRelayout ();
}
private void OnModelReloaded (object o, EventArgs args)
{
QueueRelayout ();
}
private Actor GetRandomActor ()
{
return GetRandomActor (null);
}
private Actor GetRandomActor (Random rand)
{
while (true) {
// FIXME: do a smarter job at picking a random piece of art
// so that duplicate artwork is only displayed when there isn't
// enough to actually fill the entire grid
var actor = GetActorAtIndex ((rand ?? random).Next (0, Model.Count - 1));
if (actor != null) {
if (actor.AllocationGeometry.Width == 0 || actor.AllocationGeometry.Height == 0) {
actor.Allocate (new ActorBox (0, 0,
(float)ActorSize, (float)ActorSize));
}
return actor;
}
}
}
private Actor GetActorAtIndex (int index)
{
if (index < 0 || index > Model.Count) {
return null;
}
return GetActorForAlbumInfo (Model[index]);
}
private Actor GetActorForAlbumInfo (AlbumInfo info)
{
Actor actor = null;
if (info == null || info.ArtworkId == null) {
return null;
}
if (actor_cache.TryGetValue (info.ArtworkId, out actor)) {
return actor;
}
if (!CoverArtSpec.CoverExists (info.ArtworkId)) {
return null;
}
actor = new AlbumArtActor (info, ActorSize) { Parent = this };
actor_cache.Add (info.ArtworkId, actor);
return actor;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="TangoApplication.cs" company="Google">
//
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System.Linq;
using UnityEngine;
namespace Tango
{
/// <summary>
/// Delegate for permission callbacks.
/// </summary>
/// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param>
public delegate void PermissionsEvent(bool permissionsGranted);
/// <summary>
/// Delegate for service connection.
/// </summary>
public delegate void OnTangoConnectEventHandler();
/// <summary>
/// Delegate for service disconnection.
/// </summary>
public delegate void OnTangoDisconnectEventHandler();
/// <summary>
/// Main entry point for the Tango Service.
///
/// This component handles nearly all communication with the underlying TangoService. You must have one of these
/// in your scene for Tango to work. Customization of the Tango connection can be done in the Unity editor or by
/// programatically setting the member flags.
///
/// This sends out events to Components that derive from the ITangoPose, ITangoDepth, etc. interfaces and
/// register themselves via Register. This also sends out events to callbacks passed in through
/// RegisterOnTangoConnect, RegisterOnTangoDisconnect, and RegisterPermissionsCallback.
///
/// Note: To connect to the Tango Service, you should call InitApplication after properly registering everything.
/// </summary>
public class TangoApplication : MonoBehaviour
{
/// <summary>
/// Permission types used by Tango applications.
/// </summary>
[Flags]
private enum PermissionsTypes
{
// All entries must be a power of two for
// use in a bit field as flags.
NONE = 0,
MOTION_TRACKING = 0x1,
AREA_LEARNING = 0x2,
}
public bool m_allowOutOfDateTangoAPI = false;
public bool m_enableMotionTracking = true;
public bool m_enableDepth = true;
public bool m_enableVideoOverlay = false;
public bool m_motionTrackingAutoReset = true;
public bool m_enableAreaLearning = false;
public bool m_enableADFLoading = false;
public bool m_useExperimentalVideoOverlay = true;
public bool m_autoConnectToService = false;
internal bool m_enableCloudADF = false;
private const string CLASS_NAME = "TangoApplication";
private const int MINIMUM_API_VERSION = 6804;
private static string m_tangoServiceVersion = string.Empty;
/// <summary>
/// Occurs when permission event.
/// </summary>
private event PermissionsEvent PermissionEvent;
/// <summary>
/// Occurs when on tango connect.
/// </summary>
private event OnTangoConnectEventHandler OnTangoConnect;
/// <summary>
/// Occurs when on tango disconnect.
/// </summary>
private event OnTangoDisconnectEventHandler OnTangoDisconnect;
/// <summary>
/// If RequestPermissions() has been called automatically.
///
/// This only matters if m_autoConnectToService is set.
/// </summary>
private bool m_autoConnectRequestedPermissions = false;
private PermissionsTypes m_requiredPermissions = 0;
private IntPtr m_callbackContext = IntPtr.Zero;
private bool m_isServiceInitialized = false;
private bool m_isServiceConnected = false;
private bool m_shouldReconnectService = false;
private bool m_sendPermissions = false;
private bool m_permissionsSuccessful = false;
private PoseListener m_poseListener;
private DepthListener m_depthListener;
private VideoOverlayListener m_videoOverlayListener;
private TangoEventListener m_tangoEventListener;
private TangoCloudEventListener m_tangoCloudEventListener;
private AreaDescriptionEventListener m_areaDescriptionEventListener;
private YUVTexture m_yuvTexture;
private TangoConfig m_tangoConfig;
private TangoConfig m_tangoRuntimeConfig;
/// <summary>
/// Get the Tango service version name.
/// </summary>
/// <returns>String for the version name.</returns>
public static string GetTangoServiceVersion()
{
if (m_tangoServiceVersion == string.Empty)
{
m_tangoServiceVersion = AndroidHelper.GetVersionName("com.projecttango.tango");
}
return m_tangoServiceVersion;
}
/// <summary>
/// Get the video overlay texture.
/// </summary>
/// <returns>The video overlay texture.</returns>
public YUVTexture GetVideoOverlayTextureYUV()
{
return m_yuvTexture;
}
/// <summary>
/// Register to get Tango callbacks.
///
/// The object should derive from one of ITangoDepth, ITangoEvent, ITangoPos, ITangoVideoOverlay, or
/// ITangoExperimentalTangoVideoOverlay. You will get callback during Update until you unregister.
/// </summary>
/// <param name="tangoObject">Object to get Tango callbacks from.</param>
public void Register(System.Object tangoObject)
{
ITangoAreaDescriptionEvent areaDescriptionEvent = tangoObject as ITangoAreaDescriptionEvent;
if (areaDescriptionEvent != null)
{
_RegisterOnAreaDescriptionEvent(areaDescriptionEvent.OnAreaDescriptionImported,
areaDescriptionEvent.OnAreaDescriptionExported);
}
ITangoEvent tangoEvent = tangoObject as ITangoEvent;
if (tangoEvent != null)
{
_RegisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler);
}
ITangoEventMultithreaded tangoEventMultithreaded = tangoObject as ITangoEventMultithreaded;
if (tangoEventMultithreaded != null)
{
_RegisterOnTangoEventMultithreaded(tangoEventMultithreaded.OnTangoEventMultithreadedAvailableEventHandler);
}
ITangoLifecycle tangoLifecycle = tangoObject as ITangoLifecycle;
if (tangoLifecycle != null)
{
_RegisterPermissionsCallback(tangoLifecycle.OnTangoPermissions);
_RegisterOnTangoConnect(tangoLifecycle.OnTangoServiceConnected);
_RegisterOnTangoDisconnect(tangoLifecycle.OnTangoServiceDisconnected);
}
ITangoCloudEvent tangoCloudEvent = tangoObject as ITangoCloudEvent;
if (tangoCloudEvent != null)
{
_RegisterOnTangoCloudEvent(tangoCloudEvent.OnTangoCloudEventAvailableEventHandler);
}
if (m_enableMotionTracking)
{
ITangoPose poseHandler = tangoObject as ITangoPose;
if (poseHandler != null)
{
_RegisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable);
}
}
if (m_enableDepth)
{
ITangoDepth depthHandler = tangoObject as ITangoDepth;
if (depthHandler != null)
{
_RegisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable);
}
}
if (m_enableVideoOverlay)
{
if (m_useExperimentalVideoOverlay)
{
IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay;
if (videoOverlayHandler != null)
{
_RegisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable);
}
}
else
{
ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay;
if (videoOverlayHandler != null)
{
_RegisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler);
}
}
}
}
/// <summary>
/// Unregister from Tango callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="tangoObject">Object to stop getting Tango callbacks from.</param>
public void Unregister(System.Object tangoObject)
{
ITangoAreaDescriptionEvent areaDescriptionEvent = tangoObject as ITangoAreaDescriptionEvent;
if (areaDescriptionEvent != null)
{
_UnregisterOnAreaDescriptionEvent(areaDescriptionEvent.OnAreaDescriptionImported,
areaDescriptionEvent.OnAreaDescriptionExported);
}
ITangoEvent tangoEvent = tangoObject as ITangoEvent;
if (tangoEvent != null)
{
_UnregisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler);
}
ITangoEventMultithreaded tangoEventMultithreaded = tangoObject as ITangoEventMultithreaded;
if (tangoEventMultithreaded != null)
{
_UnregisterOnTangoEventMultithreaded(tangoEventMultithreaded.OnTangoEventMultithreadedAvailableEventHandler);
}
ITangoLifecycle tangoLifecycle = tangoObject as ITangoLifecycle;
if (tangoLifecycle != null)
{
_UnregisterPermissionsCallback(tangoLifecycle.OnTangoPermissions);
_UnregisterOnTangoConnect(tangoLifecycle.OnTangoServiceConnected);
_UnregisterOnTangoDisconnect(tangoLifecycle.OnTangoServiceDisconnected);
}
ITangoCloudEvent tangoCloudEvent = tangoObject as ITangoCloudEvent;
if (tangoCloudEvent != null)
{
_UnregisterOnTangoCloudEvent(tangoCloudEvent.OnTangoCloudEventAvailableEventHandler);
}
if (m_enableMotionTracking)
{
ITangoPose poseHandler = tangoObject as ITangoPose;
if (poseHandler != null)
{
_UnregisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable);
}
}
if (m_enableDepth)
{
ITangoDepth depthHandler = tangoObject as ITangoDepth;
if (depthHandler != null)
{
_UnregisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable);
}
}
if (m_enableVideoOverlay)
{
if (m_useExperimentalVideoOverlay)
{
IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay;
if (videoOverlayHandler != null)
{
_UnregisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable);
}
}
else
{
ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay;
if (videoOverlayHandler != null)
{
_UnregisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler);
}
}
}
}
/// <summary>
/// Check if all requested permissions have been granted.
/// </summary>
/// <returns><c>true</c> if all requested permissions were granted; otherwise, <c>false</c>.</returns>
public bool HasRequestedPermissions()
{
return m_requiredPermissions == PermissionsTypes.NONE;
}
/// <summary>
/// Manual initialization step 1: Call this to request Tango permissions.
///
/// To know the result of the permissions request, implement the interface ITangoLifecycle and register
/// yourself before calling this.
///
/// Once all permissions have been granted, you can call TangoApplication.Startup, optionally passing in the
/// AreaDescription to load. You can get the list of AreaDescriptions once the appropriate permission is
/// granted.
/// </summary>
public void RequestPermissions()
{
_ResetPermissionsFlags();
_RequestNextPermission();
}
/// <summary>
/// Manual initalization step 2: Call this to connect to the Tango service.
///
/// After connecting to the Tango service, you will get updates for Motion Tracking, Depth Sensing, and Area
/// Learning. If you have a specific Area Description you want to localize too, pass that Area Description in
/// here.
/// </summary>
/// <param name="areaDescription">If not null, the Area Description to localize to.</param>
public void Startup(AreaDescription areaDescription)
{
// Make sure all required permissions have been granted.
if (m_requiredPermissions != PermissionsTypes.NONE)
{
Debug.Log("TangoApplication.Startup() -- ERROR: Not all required permissions were accepted yet.");
return;
}
_CheckTangoVersion();
if (m_enableVideoOverlay && m_useExperimentalVideoOverlay)
{
int yTextureWidth = 0;
int yTextureHeight = 0;
int uvTextureWidth = 0;
int uvTextureHeight = 0;
m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_WIDTH, ref yTextureWidth);
m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_HEIGHT, ref yTextureHeight);
m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_WIDTH, ref uvTextureWidth);
m_tangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_HEIGHT, ref uvTextureHeight);
if (yTextureWidth == 0 || yTextureHeight == 0 || uvTextureWidth == 0 || uvTextureHeight == 0)
{
Debug.Log("Video overlay texture sizes were not set properly");
}
m_yuvTexture.ResizeAll(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight);
}
if (areaDescription != null)
{
_InitializeMotionTracking(areaDescription.m_uuid);
}
else
{
_InitializeMotionTracking(null);
}
if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_DEPTH_PERCEPTION_BOOL, m_enableDepth) && m_enableDepth)
{
_SetDepthCallbacks();
}
if (m_enableVideoOverlay)
{
_SetVideoOverlayCallbacks();
}
_SetEventCallbacks();
_TangoConnect();
}
/// <summary>
/// Disconnect from the Tango service.
///
/// This is called automatically when the TangoApplication goes away. You only need
/// to call this to disconnect from the Tango service before the TangoApplication goes
/// away.
/// </summary>
public void Shutdown()
{
Debug.Log("Tango Shutdown");
_TangoDisconnect();
}
/// <summary>
/// Set the framerate of the depth camera.
///
/// Disabling or reducing the framerate of the depth camera when it is running can save a significant amount
/// of battery.
/// </summary>
/// <param name="rate">The rate in frames per second, for the depth camera to run at.</param>
public void SetDepthCameraRate(int rate)
{
if (rate < 0)
{
Debug.Log("Invalid rate passed to SetDepthCameraRate");
return;
}
m_tangoRuntimeConfig.SetInt32(TangoConfig.Keys.RUNTIME_DEPTH_FRAMERATE, rate);
m_tangoRuntimeConfig.SetRuntimeConfig();
}
/// <summary>
/// Set the framerate of the depth camera.
///
/// Disabling or reducing the framerate of the depth camera when it is running can save a significant amount
/// of battery.
/// </summary>
/// <param name="rate">A special rate to set the depth camera to.</param>
public void SetDepthCameraRate(TangoEnums.TangoDepthCameraRate rate)
{
switch (rate)
{
case TangoEnums.TangoDepthCameraRate.DISABLED:
SetDepthCameraRate(0);
break;
case TangoEnums.TangoDepthCameraRate.MAXIMUM:
// Set the depth frame rate to a sufficiently high number, it will get rounded down. There is no
// way to actually get the maximum value to pass in.
SetDepthCameraRate(9000);
break;
}
}
/// <summary>
/// Propagates an event from the java plugin connected to the Cloud Service through UnitySendMessage().
/// </summary>
/// <param name="message">A string representation of the cloud event key and value.</param>
internal void SendCloudEvent(string message)
{
Debug.Log("New message from Cloud Service: " + message);
string[] keyValue = message.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
int key;
int value;
if (m_tangoCloudEventListener != null &&
keyValue.Length == 2 &&
Int32.TryParse(keyValue[0], out key) &&
Int32.TryParse(keyValue[1], out value))
{
m_tangoCloudEventListener.OnCloudEventAvailable(key, value);
}
}
/// <summary>
/// Get the Tango config. Useful for debugging.
/// </summary>
/// <value>The config.</value>
internal TangoConfig Config
{
get { return m_tangoConfig; }
}
/// <summary>
/// Get the current Tango runtime config. Useful for debugging.
/// </summary>
/// <value>The current runtime config.</value>
internal TangoConfig RuntimeConfig
{
get { return m_tangoRuntimeConfig; }
}
/// <summary>
/// Gets the get tango API version code.
/// </summary>
/// <returns>The get tango API version code.</returns>
private static int _GetTangoAPIVersion()
{
return AndroidHelper.GetVersionCode("com.projecttango.tango");
}
/// <summary>
/// Register to get Tango pose callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Handler.</param>
private void _RegisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler)
{
if (m_poseListener != null)
{
m_poseListener.RegisterTangoPoseAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango pose callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler)
{
if (m_poseListener != null)
{
m_poseListener.UnregisterTangoPoseAvailable(handler);
}
}
/// <summary>
/// Register to get Tango depth callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler)
{
if (m_depthListener != null)
{
m_depthListener.RegisterOnTangoDepthAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango depth callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler)
{
if (m_depthListener != null)
{
m_depthListener.UnregisterOnTangoDepthAvailable(handler);
}
}
/// <summary>
/// Register to get Tango cloud event callbacks.
///
/// See TangoApplication.Register for details.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnTangoCloudEvent(OnTangoCloudEventAvailableEventHandler handler)
{
if (m_tangoCloudEventListener != null)
{
m_tangoCloudEventListener.RegisterOnTangoCloudEventAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango cloud event callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnTangoCloudEvent(OnTangoCloudEventAvailableEventHandler handler)
{
if (m_tangoCloudEventListener != null)
{
m_tangoCloudEventListener.UnregisterOnTangoCloudEventAvailable(handler);
}
}
/// <summary>
/// Register to get Tango event callbacks.
///
/// See TangoApplication.Register for details.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnTangoEvent(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.RegisterOnTangoEventAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango event callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnTangoEvent(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.UnregisterOnTangoEventAvailable(handler);
}
}
/// <summary>
/// Register to get Tango event callbacks.
///
/// See TangoApplication.Register for details.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnTangoEventMultithreaded(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.RegisterOnTangoEventMultithreadedAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango event callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event to remove.</param>
private void _UnregisterOnTangoEventMultithreaded(OnTangoEventAvailableEventHandler handler)
{
if (m_tangoEventListener != null)
{
m_tangoEventListener.UnregisterOnTangoEventMultithreadedAvailable(handler);
}
}
/// <summary>
/// Register to get Tango video overlay callbacks.
///
/// See TangoApplication.Register for details.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.RegisterOnTangoImageAvailable(handler);
}
}
/// <summary>
/// Unregister from the Tango video overlay callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.UnregisterOnTangoImageAvailable(handler);
}
}
/// <summary>
/// Experimental API only, subject to change. Register to get Tango video overlay callbacks.
/// </summary>
/// <param name="handler">Event handler.</param>
private void _RegisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.RegisterOnExperimentalTangoImageAvailable(handler);
}
}
/// <summary>
/// Experimental API only, subject to change. Unregister from the Tango video overlay callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="handler">Event handler to remove.</param>
private void _UnregisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler)
{
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.UnregisterOnExperimentalTangoImageAvailable(handler);
}
}
/// <summary>
/// Register to get Tango event callbacks.
///
/// See TangoApplication.Register for details.
/// </summary>
/// <param name="import">The handler to the import callback function.</param>
/// <param name="export">The handler to the export callback function.</param>
private void _RegisterOnAreaDescriptionEvent(OnAreaDescriptionImportEventHandler import,
OnAreaDescriptionExportEventHandler export)
{
if (m_areaDescriptionEventListener != null)
{
m_areaDescriptionEventListener.Register(import, export);
}
}
/// <summary>
/// Unregister from the Tango event callbacks.
///
/// See TangoApplication.Register for more details.
/// </summary>
/// <param name="import">The handler to the import callback function.</param>
/// <param name="export">The handler to the export callback function.</param>
private void _UnregisterOnAreaDescriptionEvent(OnAreaDescriptionImportEventHandler import,
OnAreaDescriptionExportEventHandler export)
{
if (m_areaDescriptionEventListener != null)
{
m_areaDescriptionEventListener.Unregister(import, export);
}
}
/// <summary>
/// Register to get an event callback when all permissions are granted.
///
/// The passed event will get called once all Tango permissions have been granted. Registering
/// after all permissions have already been granted will cause the event to never fire.
/// </summary>
/// <param name="permissionsEventHandler">Event to call.</param>
private void _RegisterPermissionsCallback(PermissionsEvent permissionsEventHandler)
{
if (permissionsEventHandler != null)
{
PermissionEvent += permissionsEventHandler;
}
}
/// <summary>
/// Unregister from the permission callbacks.
///
/// See TangoApplication.RegisterPermissionsCallback for more details.
/// </summary>
/// <param name="permissionsEventHandler">Event to remove.</param>
private void _UnregisterPermissionsCallback(PermissionsEvent permissionsEventHandler)
{
if (permissionsEventHandler != null)
{
PermissionEvent -= permissionsEventHandler;
}
}
/// <summary>
/// Register to get an event callback when connected to the Tango service.
///
/// The passed event will get called once connected to the Tango service. Registering
/// after already connected will cause the event to not fire until disconnected and then
/// connecting again.
/// </summary>
/// <param name="handler">Event to call.</param>
private void _RegisterOnTangoConnect(OnTangoConnectEventHandler handler)
{
if (handler != null)
{
OnTangoConnect += handler;
}
}
/// <summary>
/// Unregister from the callback when connected to the Tango service.
///
/// See TangoApplication.RegisterOnTangoConnect for more details.
/// </summary>
/// <param name="handler">Event to remove.</param>
private void _UnregisterOnTangoConnect(OnTangoConnectEventHandler handler)
{
if (handler != null)
{
OnTangoConnect -= handler;
}
}
/// <summary>
/// Register to get an event callback when disconnected from the Tango service.
///
/// The passed event will get called when disconnected from the Tango service.
/// </summary>
/// <param name="handler">Event to remove.</param>
private void _RegisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler)
{
if (handler != null)
{
OnTangoDisconnect += handler;
}
}
/// <summary>
/// Unregister from the callback when disconnected from the Tango service.
///
/// See TangoApplication.RegisterOnTangoDisconnect for more details.
/// </summary>
/// <param name="handler">Event to remove.</param>
private void _UnregisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler)
{
if (handler != null)
{
OnTangoDisconnect -= handler;
}
}
/// <summary>
/// Helper method that will resume the tango services on App Resume.
/// Locks the config again and connects the service.
/// </summary>
private void _ResumeTangoServices()
{
RequestPermissions();
}
/// <summary>
/// Helper method that will suspend the tango services on App Suspend.
/// Unlocks the tango config and disconnects the service.
/// </summary>
private void _SuspendTangoServices()
{
Debug.Log("Suspending Tango Service");
_TangoDisconnect();
}
/// <summary>
/// Set callbacks on all PoseListener objects.
/// </summary>
/// <param name="framePairs">Frame pairs.</param>
private void _SetMotionTrackingCallbacks(TangoCoordinateFramePair[] framePairs)
{
Debug.Log("TangoApplication._SetMotionTrackingCallbacks()");
if (m_poseListener != null)
{
m_poseListener.AutoReset = m_motionTrackingAutoReset;
m_poseListener.SetCallback(framePairs);
}
}
/// <summary>
/// Set callbacks for all DepthListener objects.
/// </summary>
private void _SetDepthCallbacks()
{
Debug.Log("TangoApplication._SetDepthCallbacks()");
if (m_depthListener != null)
{
m_depthListener.SetCallback();
}
}
/// <summary>
/// Set callbacks for all TangoEventListener objects.
/// </summary>
private void _SetEventCallbacks()
{
Debug.Log("TangoApplication._SetEventCallbacks()");
if (m_tangoEventListener != null)
{
m_tangoEventListener.SetCallback();
}
}
/// <summary>
/// Set callbacks for all VideoOverlayListener objects.
/// </summary>
private void _SetVideoOverlayCallbacks()
{
Debug.Log("TangoApplication._SetVideoOverlayCallbacks()");
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.SetCallback(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, m_useExperimentalVideoOverlay, m_yuvTexture);
}
}
/// <summary>
/// Initialize motion tracking.
/// </summary>
/// <param name="uuid">ADF UUID to load.</param>
private void _InitializeMotionTracking(string uuid)
{
Debug.Log("TangoApplication._InitializeMotionTracking(" + uuid + ")");
System.Collections.Generic.List<TangoCoordinateFramePair> framePairs = new System.Collections.Generic.List<TangoCoordinateFramePair>();
if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_BOOL, m_enableMotionTracking) && m_enableMotionTracking)
{
TangoCoordinateFramePair motionTracking;
motionTracking.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE;
motionTracking.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE;
framePairs.Add(motionTracking);
bool areaLearningEnabled = false;
if (m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_AREA_LEARNING_BOOL, m_enableAreaLearning) && m_enableAreaLearning)
{
areaLearningEnabled = true;
Debug.Log("Area Learning is enabled.");
}
// For backward compatibility, don't require the m_enableADFLoading to be set.
if (areaLearningEnabled || m_enableADFLoading)
{
if (!string.IsNullOrEmpty(uuid))
{
m_tangoConfig.SetString(TangoConfig.Keys.LOAD_AREA_DESCRIPTION_UUID_STRING, uuid);
}
}
if (areaLearningEnabled || m_enableADFLoading)
{
TangoCoordinateFramePair areaDescription;
areaDescription.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION;
areaDescription.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE;
TangoCoordinateFramePair startToADF;
startToADF.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION;
startToADF.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE;
framePairs.Add(areaDescription);
framePairs.Add(startToADF);
}
}
if (framePairs.Count > 0)
{
_SetMotionTrackingCallbacks(framePairs.ToArray());
}
// The C API does not default this to on, but it is locked down.
m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_LOW_LATENCY_IMU_INTEGRATION, true);
m_tangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_AUTO_RECOVERY_BOOL, m_motionTrackingAutoReset);
if (m_enableCloudADF)
{
Debug.Log("Connect to Cloud Service.");
AndroidHelper.ConnectCloud();
}
}
/// <summary>
/// Validate the TangoService version is supported.
/// </summary>
private void _CheckTangoVersion()
{
int tangoVersion = _GetTangoAPIVersion();
if (tangoVersion < MINIMUM_API_VERSION)
{
Debug.Log(string.Format(CLASS_NAME + ".Initialize() Invalid API version {0}. Please update Project Tango Core to at least {1}.", tangoVersion, MINIMUM_API_VERSION));
if (!m_allowOutOfDateTangoAPI)
{
AndroidHelper.ShowAndroidToastMessage("Please update Tango Core");
return;
}
}
m_isServiceInitialized = true;
Debug.Log(CLASS_NAME + ".Initialize() Tango was initialized!");
}
/// <summary>
/// Connect to the Tango Service.
/// </summary>
private void _TangoConnect()
{
Debug.Log("TangoApplication._TangoConnect()");
if (!m_isServiceInitialized)
{
return;
}
if (!m_isServiceConnected)
{
m_isServiceConnected = true;
AndroidHelper.PerformanceLog("Unity _TangoConnect start");
if (TangoServiceAPI.TangoService_connect(m_callbackContext, m_tangoConfig.GetHandle()) != Common.ErrorType.TANGO_SUCCESS)
{
AndroidHelper.ShowAndroidToastMessage("Failed to connect to Tango Service.");
Debug.Log(CLASS_NAME + ".Connect() Could not connect to the Tango Service!");
}
else
{
AndroidHelper.PerformanceLog("Unity _TangoConnect end");
Debug.Log(CLASS_NAME + ".Connect() Tango client connected to service!");
if (OnTangoConnect != null)
{
OnTangoConnect();
}
}
}
}
/// <summary>
/// Disconnect from the Tango Service.
/// </summary>
private void _TangoDisconnect()
{
Debug.Log(CLASS_NAME + ".Disconnect() Disconnecting from the Tango Service");
m_isServiceConnected = false;
if (TangoServiceAPI.TangoService_disconnect() != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".Disconnect() Could not disconnect from the Tango Service!");
}
else
{
Debug.Log(CLASS_NAME + ".Disconnect() Tango client disconnected from service!");
if (OnTangoDisconnect != null)
{
OnTangoDisconnect();
}
}
if (m_enableCloudADF)
{
Debug.Log("Disconnect from Cloud Service.");
AndroidHelper.DisconnectCloud();
}
}
/// <summary>
/// Android on pause.
/// </summary>
private void _androidOnPause()
{
if (m_isServiceConnected && m_requiredPermissions == PermissionsTypes.NONE)
{
Debug.Log("Pausing services");
m_shouldReconnectService = true;
_SuspendTangoServices();
}
Debug.Log("androidOnPause done");
}
/// <summary>
/// Android on resume.
/// </summary>
private void _androidOnResume()
{
if (m_shouldReconnectService)
{
Debug.Log("Resuming services");
m_shouldReconnectService = false;
_ResumeTangoServices();
}
Debug.Log("androidOnResume done");
}
/// <summary>
/// EventHandler for Android's on activity result.
/// </summary>
/// <param name="requestCode">Request code.</param>
/// <param name="resultCode">Result code.</param>
/// <param name="data">Data.</param>
private void _androidOnActivityResult(int requestCode, int resultCode, AndroidJavaObject data)
{
Debug.Log("Activity returned result code : " + resultCode);
switch (requestCode)
{
case Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE:
{
if (resultCode == (int)Common.AndroidResult.SUCCESS)
{
_FlipBitAndCheckPermissions(PermissionsTypes.MOTION_TRACKING);
}
else
{
_PermissionWasDenied();
}
break;
}
case Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE:
{
if (resultCode == (int)Common.AndroidResult.SUCCESS)
{
_FlipBitAndCheckPermissions(PermissionsTypes.AREA_LEARNING);
}
else
{
_PermissionWasDenied();
}
break;
}
default:
{
break;
}
}
Debug.Log("Activity returned result end");
}
/// <summary>
/// Awake this instance.
/// </summary>
private void Awake()
{
AndroidHelper.RegisterPauseEvent(_androidOnPause);
AndroidHelper.RegisterResumeEvent(_androidOnResume);
AndroidHelper.RegisterOnActivityResultEvent(_androidOnActivityResult);
// Setup listeners.
m_tangoEventListener = new TangoEventListener();
m_areaDescriptionEventListener = new AreaDescriptionEventListener();
if (m_enableCloudADF)
{
m_tangoCloudEventListener = new TangoCloudEventListener();
}
if (m_enableMotionTracking)
{
m_poseListener = new PoseListener();
}
if (m_enableDepth)
{
m_depthListener = new DepthListener();
}
if (m_enableVideoOverlay)
{
int yTextureWidth = 0;
int yTextureHeight = 0;
int uvTextureWidth = 0;
int uvTextureHeight = 0;
m_yuvTexture = new YUVTexture(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight, TextureFormat.RGBA32, false);
m_videoOverlayListener = new VideoOverlayListener();
}
// Setup configs.
m_tangoConfig = new TangoConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_DEFAULT);
m_tangoRuntimeConfig = new TangoConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_RUNTIME);
}
/// <summary>
/// Reset permissions flags.
/// </summary>
private void _ResetPermissionsFlags()
{
if (m_requiredPermissions == PermissionsTypes.NONE)
{
m_requiredPermissions |= m_enableAreaLearning ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE;
m_requiredPermissions |= m_enableADFLoading ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE;
}
}
/// <summary>
/// Flip a permission bit and check to see if all permissions were accepted.
/// </summary>
/// <param name="permission">Permission.</param>
private void _FlipBitAndCheckPermissions(PermissionsTypes permission)
{
m_requiredPermissions ^= permission;
if (m_requiredPermissions == 0)
{
// all permissions are good!
Debug.Log("All permissions have been accepted!");
_SendPermissionEvent(true);
}
else
{
_RequestNextPermission();
}
}
/// <summary>
/// A Tango permission was denied.
/// </summary>
private void _PermissionWasDenied()
{
m_requiredPermissions = PermissionsTypes.NONE;
if (PermissionEvent != null)
{
_SendPermissionEvent(false);
}
}
/// <summary>
/// Request next permission.
/// </summary>
private void _RequestNextPermission()
{
Debug.Log("TangoApplication._RequestNextPermission()");
// if no permissions are needed let's kick-off the Tango connect
if (m_requiredPermissions == PermissionsTypes.NONE)
{
_SendPermissionEvent(true);
}
if ((m_requiredPermissions & PermissionsTypes.MOTION_TRACKING) == PermissionsTypes.MOTION_TRACKING)
{
if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_MOTION_TRACKING_PERMISSIONS))
{
_androidOnActivityResult(Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE, -1, null);
}
else
{
AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_MOTION_TRACKING_PERMISSIONS);
}
}
else if ((m_requiredPermissions & PermissionsTypes.AREA_LEARNING) == PermissionsTypes.AREA_LEARNING)
{
if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS))
{
_androidOnActivityResult(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE, -1, null);
}
else
{
AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS);
}
}
}
/// <summary>
/// Sends the permission event.
/// </summary>
/// <param name="permissions">If set to <c>true</c> permissions.</param>
private void _SendPermissionEvent(bool permissions)
{
m_sendPermissions = true;
m_permissionsSuccessful = permissions;
}
/// <summary>
/// Disperse any events related to Tango functionality.
/// </summary>
private void Update()
{
// Autoconnect requesting permissions can not be moved earlier into Awake() or Start(). All other scripts
// must be able to register for the permissions callback before RequestPermissions() is called. The
// earliest another script can register is in Start(). Therefore, this logic must be run after Start() has
// run on all scripts. That means it must be in FixedUpdate(), Update(), LateUpdate(), or a coroutine.
if (m_autoConnectToService)
{
if (!m_autoConnectRequestedPermissions)
{
RequestPermissions();
m_autoConnectRequestedPermissions = true;
}
}
if (m_sendPermissions)
{
if (PermissionEvent != null)
{
PermissionEvent(m_permissionsSuccessful);
}
if (m_permissionsSuccessful && m_autoConnectToService)
{
Startup(null);
}
m_sendPermissions = false;
}
if (m_poseListener != null)
{
m_poseListener.SendPoseIfAvailable();
}
if (m_tangoEventListener != null)
{
m_tangoEventListener.SendIfTangoEventAvailable();
}
if (m_tangoCloudEventListener != null)
{
m_tangoCloudEventListener.SendIfTangoCloudEventAvailable();
}
if (m_depthListener != null)
{
m_depthListener.SendDepthIfAvailable();
}
if (m_videoOverlayListener != null)
{
m_videoOverlayListener.SendIfVideoOverlayAvailable();
}
if (m_areaDescriptionEventListener != null)
{
m_areaDescriptionEventListener.SendEventIfAvailable();
}
}
/// <summary>
/// Unity callback when this object is destroyed.
/// </summary>
private void OnDestroy()
{
Shutdown();
// Clean up configs.
if (m_tangoConfig != null)
{
m_tangoConfig.Dispose();
m_tangoConfig = null;
}
if (m_tangoRuntimeConfig != null)
{
m_tangoRuntimeConfig.Dispose();
m_tangoRuntimeConfig = null;
}
}
#region NATIVE_FUNCTIONS
/// <summary>
/// Interface for native function calls to Tango Service.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "C API Wrapper.")]
private struct TangoServiceAPI
{
#if UNITY_ANDROID && !UNITY_EDITOR
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_initialize(IntPtr jniEnv, IntPtr appContext);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_connect(IntPtr callbackContext, IntPtr config);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern int TangoService_disconnect();
#else
public static int TangoService_initialize(IntPtr jniEnv, IntPtr appContext)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_connect(IntPtr callbackContext, IntPtr config)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_disconnect()
{
return Common.ErrorType.TANGO_SUCCESS;
}
#endif
}
#endregion // NATIVE_FUNCTIONS
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.DocumentationComments;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions:
SymbolDisplayGenericsOptions.IncludeTypeParameters |
SymbolDisplayGenericsOptions.IncludeVariance |
SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
memberOptions:
SymbolDisplayMemberOptions.IncludeParameters |
SymbolDisplayMemberOptions.IncludeType |
SymbolDisplayMemberOptions.IncludeContainingType,
kindOptions:
SymbolDisplayKindOptions.IncludeMemberKeyword,
propertyStyle:
SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
parameterOptions:
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeParamsRefOut |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeOptionalBrackets,
localOptions: SymbolDisplayLocalOptions.IncludeType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName);
private static readonly SymbolDisplayFormat s_descriptionStyle =
new SymbolDisplayFormat(
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword);
private static readonly SymbolDisplayFormat s_globalNamespaceStyle =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included);
private readonly ISymbolDisplayService _displayService;
private readonly SemanticModel _semanticModel;
private readonly int _position;
private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService;
private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap =
new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>();
protected readonly Workspace Workspace;
protected readonly CancellationToken CancellationToken;
protected AbstractSymbolDescriptionBuilder(
ISymbolDisplayService displayService,
SemanticModel semanticModel,
int position,
Workspace workspace,
IAnonymousTypeDisplayService anonymousTypeDisplayService,
CancellationToken cancellationToken)
{
_displayService = displayService;
_anonymousTypeDisplayService = anonymousTypeDisplayService;
this.Workspace = workspace;
this.CancellationToken = cancellationToken;
_semanticModel = semanticModel;
_position = position;
}
protected abstract void AddExtensionPrefix();
protected abstract void AddAwaitablePrefix();
protected abstract void AddAwaitableExtensionPrefix();
protected abstract void AddDeprecatedPrefix();
protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol);
protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; }
protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; }
protected void AddPrefixTextForAwaitKeyword()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.Awaited_task_returns),
Space());
}
protected void AddTextForSystemVoid()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
PlainText(FeaturesResources.no_value));
}
protected SemanticModel GetSemanticModel(SyntaxTree tree)
{
if (_semanticModel.SyntaxTree == tree)
{
return _semanticModel;
}
var model = _semanticModel.GetOriginalSemanticModel();
if (model.Compilation.ContainsSyntaxTree(tree))
{
return model.Compilation.GetSemanticModel(tree);
}
// it is from one of its p2p references
foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations())
{
// find the reference that contains the given tree
if (referencedCompilation.ContainsSyntaxTree(tree))
{
return referencedCompilation.GetSemanticModel(tree);
}
}
// the tree, a source symbol is defined in, doesn't exist in universe
// how this can happen?
Contract.Requires(false, "How?");
return null;
}
private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols)
{
await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false);
AddOverloadCountPart(symbols);
FixAllAnonymousTypes(symbols[0]);
AddExceptions(symbols[0]);
}
private void AddExceptions(ISymbol symbol)
{
var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes;
if (exceptionTypes.Any())
{
var parts = new List<SymbolDisplayPart>();
parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions_colon}"));
foreach (var exceptionString in exceptionTypes)
{
parts.AddRange(LineBreak());
parts.AddRange(Space(count: 2));
parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel));
}
AddToGroup(SymbolDescriptionGroups.Exceptions, parts);
}
}
public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync(
ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescription(groups);
}
public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup)
{
Contract.ThrowIfFalse(symbolGroup.Length > 0);
await AddPartsAsync(symbolGroup).ConfigureAwait(false);
return this.BuildDescriptionSections();
}
private async Task AddDescriptionPartAsync(ISymbol symbol)
{
if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute"))
{
AddDeprecatedPrefix();
}
if (symbol is IDynamicTypeSymbol)
{
AddDescriptionForDynamicType();
}
else if (symbol is IFieldSymbol)
{
await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is ILocalSymbol)
{
await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IMethodSymbol)
{
AddDescriptionForMethod((IMethodSymbol)symbol);
}
else if (symbol is ILabelSymbol)
{
AddDescriptionForLabel((ILabelSymbol)symbol);
}
else if (symbol is INamedTypeSymbol)
{
await AddDescriptionForNamedTypeAsync((INamedTypeSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is INamespaceSymbol)
{
AddDescriptionForNamespace((INamespaceSymbol)symbol);
}
else if (symbol is IParameterSymbol)
{
await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false);
}
else if (symbol is IPropertySymbol)
{
AddDescriptionForProperty((IPropertySymbol)symbol);
}
else if (symbol is IRangeVariableSymbol)
{
AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol);
}
else if (symbol is ITypeParameterSymbol)
{
AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol);
}
else if (symbol is IAliasSymbol)
{
await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false);
}
else
{
AddDescriptionForArbitrarySymbol(symbol);
}
}
private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups)
{
var finalParts = new List<SymbolDisplayPart>();
var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2);
foreach (var group in orderedGroups)
{
if ((groups & group) == 0)
{
continue;
}
if (!finalParts.IsEmpty())
{
var newLines = GetPrecedingNewLineCount(group);
finalParts.AddRange(LineBreak(newLines));
}
var parts = _groupMap[group];
finalParts.AddRange(parts);
}
return finalParts.AsImmutable();
}
private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group)
{
switch (group)
{
case SymbolDescriptionGroups.MainDescription:
// these parts are continuations of whatever text came before them
return 0;
case SymbolDescriptionGroups.Documentation:
return 1;
case SymbolDescriptionGroups.AnonymousTypes:
return 0;
case SymbolDescriptionGroups.Exceptions:
case SymbolDescriptionGroups.TypeParameterMap:
// Everything else is in a group on its own
return 2;
default:
return Contract.FailWithReturn<int>("unknown part kind");
}
}
private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections()
{
return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty());
}
private void AddDescriptionForDynamicType()
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Keyword("dynamic"));
AddToGroup(SymbolDescriptionGroups.Documentation,
PlainText(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
private async Task AddDescriptionForNamedTypeAsync(INamedTypeSymbol symbol)
{
if (symbol.IsAwaitableNonDynamic(_semanticModel, _position))
{
AddAwaitablePrefix();
}
var token = await _semanticModel.SyntaxTree.GetTouchingTokenAsync(_position, this.CancellationToken).ConfigureAwait(false);
if (token != default(SyntaxToken))
{
var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>();
if (syntaxFactsService.IsAwaitKeyword(token))
{
AddPrefixTextForAwaitKeyword();
if (symbol.SpecialType == SpecialType.System_Void)
{
AddTextForSystemVoid();
return;
}
}
}
if (symbol.TypeKind == TypeKind.Delegate)
{
var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, style));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle));
}
if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol))
{
var allTypeParameters = symbol.GetAllTypeParameters().ToList();
var allTypeArguments = symbol.GetAllTypeArguments().ToList();
AddTypeParameterMapPart(allTypeParameters, allTypeArguments);
}
}
private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol)
{
var typeArguments = symbol.GetAllTypeArguments().ToList();
var typeParameters = symbol.GetAllTypeParameters().ToList();
for (int i = 0; i < typeArguments.Count; i++)
{
var typeArgument = typeArguments[i];
var typeParameter = typeParameters[i];
if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name)
{
continue;
}
return false;
}
return true;
}
private void AddDescriptionForNamespace(INamespaceSymbol symbol)
{
if (symbol.IsGlobalNamespace)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_globalNamespaceStyle));
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToDisplayParts(symbol, s_descriptionStyle));
}
}
private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol)
{
var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false);
// Don't bother showing disambiguating text for enum members. The icon displayed
// on Quick Info should be enough.
if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum)
{
AddToGroup(SymbolDescriptionGroups.MainDescription, parts);
}
else
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.constant)
: Description(FeaturesResources.field),
parts);
}
}
private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol)
{
var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false);
AddToGroup(SymbolDescriptionGroups.MainDescription,
symbol.IsConst
? Description(FeaturesResources.local_constant)
: Description(FeaturesResources.local_variable),
parts);
}
private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol)
{
if (symbol.IsConst)
{
var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
return parts;
}
}
return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants);
}
private void AddDescriptionForLabel(ILabelSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.label),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.range_variable),
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForMethod(IMethodSymbol method)
{
// TODO : show duplicated member case
var awaitable = method.IsAwaitableNonDynamic(_semanticModel, _position);
var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension;
if (awaitable && extension)
{
AddAwaitableExtensionPrefix();
}
else if (awaitable)
{
AddAwaitablePrefix();
}
else if (extension)
{
AddExtensionPrefix();
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat));
if (awaitable)
{
AddAwaitableUsageText(method, _semanticModel, _position);
}
}
protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position);
private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol)
{
IEnumerable<SymbolDisplayPart> initializerParts;
if (symbol.IsOptional)
{
initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false);
if (initializerParts != null)
{
var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList();
parts.AddRange(Space());
parts.AddRange(Punctuation("="));
parts.AddRange(Space());
parts.AddRange(initializerParts);
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter), parts);
return;
}
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
Description(FeaturesResources.parameter),
ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants));
}
protected virtual void AddDescriptionForProperty(IPropertySymbol symbol)
{
if (symbol.IsIndexer)
{
// TODO : show duplicated member case
// TODO : a way to check whether it is a member call off dynamic type?
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
return;
}
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat));
}
private void AddDescriptionForArbitrarySymbol(ISymbol symbol)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol));
}
private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol)
{
Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref);
AddToGroup(SymbolDescriptionGroups.MainDescription,
ToMinimalDisplayParts(symbol),
Space(),
PlainText(FeaturesResources.in_),
Space(),
ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat));
}
private void AddOverloadCountPart(
ImmutableArray<ISymbol> symbolGroup)
{
var count = GetOverloadCount(symbolGroup);
if (count >= 1)
{
AddToGroup(SymbolDescriptionGroups.MainDescription,
Space(),
Punctuation("("),
Punctuation("+"),
Space(),
PlainText(count.ToString()),
Space(),
count == 1 ? PlainText(FeaturesResources.overload) : PlainText(FeaturesResources.overloads_),
Punctuation(")"));
}
}
private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup)
{
return symbolGroup.Select(s => s.OriginalDefinition)
.Where(s => !s.Equals(symbolGroup.First().OriginalDefinition))
.Where(s => s is IMethodSymbol || s.IsIndexer())
.Count();
}
protected void AddTypeParameterMapPart(
List<ITypeParameterSymbol> typeParameters,
List<ITypeSymbol> typeArguments)
{
var parts = new List<SymbolDisplayPart>();
var count = typeParameters.Count;
for (int i = 0; i < count; i++)
{
parts.AddRange(TypeParameterName(typeParameters[i].Name));
parts.AddRange(Space());
parts.AddRange(PlainText(FeaturesResources.is_));
parts.AddRange(Space());
parts.AddRange(ToMinimalDisplayParts(typeArguments[i]));
if (i < count - 1)
{
parts.AddRange(LineBreak());
}
}
AddToGroup(SymbolDescriptionGroups.TypeParameterMap,
parts);
}
protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray)
{
AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray);
}
protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray)
{
var partsList = partsArray.Flatten().ToList();
if (partsList.Count > 0)
{
IList<SymbolDisplayPart> existingParts;
if (!_groupMap.TryGetValue(group, out existingParts))
{
existingParts = new List<SymbolDisplayPart>();
_groupMap.Add(group, existingParts);
}
existingParts.AddRange(partsList);
}
}
private IEnumerable<SymbolDisplayPart> Description(string description)
{
return Punctuation("(")
.Concat(PlainText(description))
.Concat(Punctuation(")"))
.Concat(Space());
}
protected IEnumerable<SymbolDisplayPart> Keyword(string text)
{
return Part(SymbolDisplayPartKind.Keyword, text);
}
protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1)
{
for (int i = 0; i < count; i++)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n");
}
}
protected IEnumerable<SymbolDisplayPart> PlainText(string text)
{
return Part(SymbolDisplayPartKind.Text, text);
}
protected IEnumerable<SymbolDisplayPart> Punctuation(string text)
{
return Part(SymbolDisplayPartKind.Punctuation, text);
}
protected IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
format = format ?? MinimallyQualifiedFormat;
return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format);
}
protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null)
{
return _displayService.ToDisplayParts(symbol, format);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text)
{
yield return new SymbolDisplayPart(kind, symbol, text);
}
private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text)
{
return Part(kind, null, text);
}
private IEnumerable<SymbolDisplayPart> TypeParameterName(string text)
{
return Part(SymbolDisplayPartKind.TypeParameterName, text);
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Validation;
using VersionOne.ServiceHost.ServerConnector.Entities;
using VersionOne.ServiceHost.ConfigurationTool.DL;
using VersionOne.ServiceHost.ConfigurationTool.Entities;
using VersionOne.ServiceHost.ConfigurationTool.Validation;
using log4net;
using System.Text.RegularExpressions;
namespace VersionOne.ServiceHost.ConfigurationTool.BZ {
// TODO rename methods containing 'List' in name and not actually returning lists
public class Facade : IFacade {
public static readonly List<string> ConfigurationFileNames = new List<string>(new[] { "VersionOne.ServiceHost.exe.config", "VersionOne.ServiceExecutor.exe.config"});
private static IFacade instance;
private readonly XmlEntitySerializer serializer = new XmlEntitySerializer();
private readonly ILog logger = LogManager.GetLogger(typeof(Facade));
public static IFacade Instance {
get { return instance ?? (instance = new Facade()); }
}
private Facade() { }
/// <summary>
/// Get VersionOne connection state
/// </summary>
public bool IsConnected {
get { return V1Connector.Instance.IsConnected; }
}
/// <summary>
/// Validate V1 connection settings.
/// </summary>
/// <param name="settings">settings for validation.</param>
/// <returns>true, if validation succeeds.</returns>
public bool IsVersionOneConnectionValid(VersionOneSettings settings) {
//TODO remove this hack after changing V1Connector with ServerConnector
return V1Connector.Instance.ValidateConnection(settings);
}
/// <summary>
/// Create empty Settings entity.
/// </summary>
public ServiceHostConfiguration CreateConfiguration() {
return new ServiceHostConfiguration();
}
/// <summary>
/// Get list of available values for Test Status.
/// </summary>
public IList<ListValue> GetTestStatuses() {
try {
var testStatuses = V1Connector.Instance.GetTestStatuses();
return ConvertToListValues(testStatuses);
} catch (Exception ex) {
ProcessException("Failed to get test status list", ex);
return null;
}
}
/// <summary>
/// Get list of available values for Story Status.
/// </summary>
public IList<ListValue> GetStoryStatuses() {
try {
var storyStatuses = V1Connector.Instance.GetStoryStatuses();
return ConvertToListValues(storyStatuses);
} catch (Exception ex) {
ProcessException("Failed to get story statuses", ex);
return null;
}
}
/// <summary>
/// Get list of available values for Workitem Priority.
/// </summary>
public IList<ListValue> GetVersionOnePriorities() {
try {
var priorities = V1Connector.Instance.GetWorkitemPriorities();
return ConvertToListValues(priorities);
} catch (Exception ex) {
ProcessException("Failed to get test status list", ex);
return null;
}
}
private static IList<ListValue> ConvertToListValues(IDictionary<string, string> items) {
var list = new List<ListValue>(items.Count);
list.AddRange(items.Select(pair => new ListValue(pair.Key, pair.Value)));
return list;
}
/// <summary>
/// Get list of available values for Workitem Type.
/// </summary>
public IList<ListValue> GetVersionOneWorkitemTypes() {
try {
var types = V1Connector.Instance.GetPrimaryWorkitemTypes();
return types.Select(x => new ListValue(x, x)).ToList();
} catch(Exception ex) {
ProcessException("Failed to get primary workitem type list", ex);
return null;
}
}
/// <summary>
/// Get list of available values for custom List Type by name
/// </summary>
public IList<ListValue> GetVersionOneCustomTypeValues(string typeName) {
try {
return V1Connector.Instance.GetValuesForType(typeName);
} catch(Exception ex) {
ProcessException("Failed to get custom list type values", ex);
return null;
}
}
/// <summary>
/// Dump settings XML to file.
/// </summary>
/// <param name="settings">Configuration entity</param>
/// <param name="fileName">Path to output file</param>
// TODO decide on whether throwing exception when validation fails lets us get better code
public ConfigurationValidationResult SaveConfigurationToFile(ServiceHostConfiguration settings, string fileName) {
var validationResult = ValidateConfiguration(settings);
if(!validationResult.IsValid) {
return validationResult;
}
try {
serializer.Serialize(settings.Services);
serializer.SaveToFile(fileName);
} catch(Exception ex) {
ProcessException("Failed to flush data to file", ex);
}
return validationResult;
}
/// <summary>
/// Load configuration from XML file.
/// </summary>
/// <param name="fileName">Path to input file</param>
/// <returns>Settings entity or NULL if loading failed.</returns>
public ServiceHostConfiguration LoadConfigurationFromFile(string fileName) {
var shortFileName = Path.GetFileName(fileName);
if (!ConfigurationFileNames.Contains(shortFileName)) {
var filesNames = "'" + ConfigurationFileNames[0] + "' or '" + ConfigurationFileNames[1] + "'";
throw new InvalidFilenameException("Invalid filename. Please use " + filesNames);
}
try {
serializer.LoadFromFile(fileName);
var entities = serializer.Deserialize();
return new ServiceHostConfiguration(entities);
} catch (Exception ex) {
ProcessException("Failed to load data from file", ex);
}
return null;
}
/// <summary>
/// Verify whether the file exists.
/// </summary>
/// <param name="fileName">The file to check</param>
/// <returns>True if path contains the name of an existing file, otherwise, false</returns>
// TODO refactor to encapsulate filename
public bool FileExists(string fileName) {
return File.Exists(fileName);
}
public bool AnyFileExists(IEnumerable<string> fileNames) {
if (fileNames == null) {
throw new ArgumentNullException("fileNames");
}
return fileNames.Any(FileExists);
}
/// <summary>
/// Get collection of fields belonging to Test asset type that could be set up to store reference value.
/// </summary>
public string[] GetTestReferenceFieldList() {
try {
return V1Connector.Instance.GetReferenceFieldList(V1Connector.TestTypeToken).ToArray();
} catch (Exception ex) {
ProcessException("Failed to get reference field list for Tests", ex);
}
return null;
}
/// <summary>
/// Get collection of sources from VersionOne server
/// </summary>
public string[] GetSourceList() {
try {
return V1Connector.Instance.GetSourceList().ToArray();
} catch (Exception ex) {
ProcessException("Failed to get source list", ex);
}
return null;
}
/// <summary>
/// Get collection of fields belonging to Defect asset type that could be set up to store reference value.
/// </summary>
public string[] GetDefectReferenceFieldList() {
try {
return V1Connector.Instance.GetReferenceFieldList(V1Connector.DefectTypeToken).ToArray();
} catch (Exception ex) {
ProcessException("Failed to get reference field list for Defects", ex);
}
return null;
}
/// <summary>
/// Gets collection of custom list fields depends on specified typeName
/// </summary>
/// <param name="typeName">Asset type name</param>
/// <returns>list fields</returns>
public IList<ListValue> GetVersionOneCustomListFields(string typeName) {
try {
var fields = V1Connector.Instance.GetCustomFields(typeName, FieldType.List);
return fields.Select(x => new ListValue(ConvertFromCamelCase(x), x)).ToList();
} catch(Exception ex) {
ProcessException("Failed to get custom list fields", ex);
}
return null;
}
/// <summary>
/// Gets collection of custom numeric fields depends on specified type
/// </summary>
/// <param name="typeName">Asset type name</param>
/// <returns>numeric fields</returns>
public IList<ListValue> GetVersionOneCustomNumericFields(string typeName) {
try {
var fields = V1Connector.Instance.GetCustomFields(typeName, FieldType.Numeric);
return fields.Select(x => new ListValue(ConvertFromCamelCase(x), x)).ToList();
} catch(Exception ex) {
ProcessException("Failed to get custom list fields", ex);
}
return null;
}
public IList<ListValue> GetVersionOneCustomTextFields(string typeName) {
try {
var fields = V1Connector.Instance.GetCustomFields(typeName, FieldType.Text);
return fields.Select(x => new ListValue(ConvertFromCamelCase(x), x)).ToList();
} catch (Exception ex) {
ProcessException("Failed to get custom list fields", ex);
}
return null;
}
private static string ConvertFromCamelCase(string camelCasedString) {
const string customPrefix = "Custom_";
if (camelCasedString.StartsWith(customPrefix)) {
camelCasedString = camelCasedString.Remove(0, customPrefix.Length);
}
return Regex.Replace(camelCasedString,
@"(?<a>(?<!^)((?:[A-Z][a-z])|(?:(?<!^[A-Z]+)[A-Z0-9]+(?:(?=[A-Z][a-z])|$))|(?:[0-9]+)))", @" ${a}");
}
public string GetVersionOneCustomListTypeName(string fieldName, string containingTypeName) {
try {
return V1Connector.Instance.GetTypeByFieldName(fieldName, containingTypeName);
} catch(Exception ex) {
ProcessException("Failed to get custom list type for field", ex);
}
return null;
}
public IList<string> GetProjectList() {
var projectList = new List<ProjectWrapper>();
try {
projectList = V1Connector.Instance.GetProjectList();
} catch(Exception ex) {
ProcessException("Failed to get project list", ex);
}
return projectList.Select(wrapper => wrapper.ProjectName).ToList();
}
public IList<ProjectWrapper> GetProjectWrapperList() {
IList<ProjectWrapper> projectsList = new List<ProjectWrapper>();
try {
projectsList = V1Connector.Instance.GetProjectList();
} catch(Exception ex) {
ProcessException("Failed to get project list", ex);
}
return projectsList;
}
/// <summary>
/// Validate connection to third party system.
/// </summary>
public bool ValidateConnection(BaseServiceEntity configuration) {
try {
var validator = ConnectionValidatorFactory.Instance.CreateValidator(configuration);
return validator.Validate();
} catch(FileNotFoundException ex) {
throw new AssemblyLoadException(ex.Message, ex);
}
}
/// <summary>
/// Validate service configurations
/// </summary>
/// <param name="config">Settings to validate</param>
/// <returns>Validation result</returns>
public ConfigurationValidationResult ValidateConfiguration(ServiceHostConfiguration config) {
var result = new ConfigurationValidationResult();
var configResults = ValidateEntity(config);
foreach (var configResult in configResults) {
result.AddError(configResult.Message);
}
foreach (var entity in config.Services) {
var results = ValidateEntity(entity);
if(!results.IsValid) {
var messages = results.Select(x => x.Message).ToList();
result.AddEntity(entity, messages);
}
}
return result;
}
public ValidationResults ValidateEntity<TEntity>(TEntity entity) {
return ValidationFactory.CreateValidatorFromAttributes(entity.GetType(), string.Empty).Validate(entity);
}
[Obsolete]
public void LogMessage(string message) {
logger.Info(message);
}
/// <summary>
///
/// </summary>
/// <param name="message">Human-readable error message.</param>
/// <param name="ex">Original exception to log and wrap/rethrow.</param>
private void ProcessException(string message, Exception ex) {
logger.Error(message, ex);
throw new BusinessException(message, ex);
}
/// <summary>
/// Reset V1 connection
/// </summary>
public void ResetConnection() {
V1Connector.Instance.ResetConnection();
}
public void AddTestServiceMappingIfRequired(ServiceHostConfiguration config, TestPublishProjectMapping mapping) {
foreach (var entity in config.Services) {
if(!(entity is QCServiceEntity)) {
continue;
}
var qcEntity = (QCServiceEntity) entity;
if (qcEntity.Projects.Any(qcProject => string.Equals(qcProject.Id, mapping.DestinationProject))) {
return;
}
var newProject = new QCProject {Id = mapping.DestinationProject, VersionOneProject = mapping.Name};
qcEntity.Projects.Add(newProject);
}
}
public void AddQCMappingIfRequired () { }
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using OpenMetaverse;
using log4net;
using Nini.Config;
using System.Reflection;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Data;
using OpenSim.Framework;
namespace OpenSim.Services.InventoryService
{
public class XInventoryService : ServiceBase, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
protected IXInventoryData m_Database;
protected bool m_AllowDelete = true;
protected string m_ConfigName = "InventoryService";
public XInventoryService(IConfigSource config)
: this(config, "InventoryService")
{
}
public XInventoryService(IConfigSource config, string configName) : base(config)
{
if (configName != string.Empty)
m_ConfigName = configName;
string dllName = String.Empty;
string connString = String.Empty;
//string realm = "Inventory"; // OSG version doesn't use this
//
// Try reading the [InventoryService] section first, if it exists
//
IConfig authConfig = config.Configs[m_ConfigName];
if (authConfig != null)
{
dllName = authConfig.GetString("StorageProvider", dllName);
connString = authConfig.GetString("ConnectionString", connString);
m_AllowDelete = authConfig.GetBoolean("AllowDelete", true);
// realm = authConfig.GetString("Realm", realm);
}
//
// Try reading the [DatabaseService] section, if it exists
//
IConfig dbConfig = config.Configs["DatabaseService"];
if (dbConfig != null)
{
if (dllName == String.Empty)
dllName = dbConfig.GetString("StorageProvider", String.Empty);
if (connString == String.Empty)
connString = dbConfig.GetString("ConnectionString", String.Empty);
}
//
// We tried, but this doesn't exist. We can't proceed.
//
if (dllName == String.Empty)
throw new Exception("No StorageProvider configured");
m_Database = LoadPlugin<IXInventoryData>(dllName,
new Object[] {connString, String.Empty});
if (m_Database == null)
throw new Exception("Could not find a storage interface in the given module");
}
public virtual bool CreateUserInventory(UUID principalID)
{
// This is braindeaad. We can't ever communicate that we fixed
// an existing inventory. Well, just return root folder status,
// but check sanity anyway.
//
bool result = false;
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
rootFolder = ConvertToOpenSim(CreateFolder(principalID, UUID.Zero, (int)FolderType.Root, InventoryFolderBase.ROOT_FOLDER_NAME));
result = true;
}
XInventoryFolder[] sysFolders = GetSystemFolders(principalID, rootFolder.ID);
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Animation) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Animation, "Animations");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.BodyPart) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.BodyPart, "Body Parts");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.CallingCard) return true; return false; }))
{
XInventoryFolder folder = CreateFolder(principalID, rootFolder.ID, (int)FolderType.CallingCard, "Calling Cards");
folder = CreateFolder(principalID, folder.folderID, (int)FolderType.CallingCard, "Friends");
CreateFolder(principalID, folder.folderID, (int)FolderType.CallingCard, "All");
}
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Clothing) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Clothing, "Clothing");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.CurrentOutfit) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.CurrentOutfit, "Current Outfit");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Favorites) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Favorites, "Favorites");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Gesture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Gesture, "Gestures");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Landmark) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Landmark, "Landmarks");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.LostAndFound) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.LostAndFound, "Lost And Found");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Notecard) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Notecard, "Notecards");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Object) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Object, "Objects");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Snapshot) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Snapshot, "Photo Album");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.LSLText) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.LSLText, "Scripts");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Sound) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Sound, "Sounds");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Texture) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Texture, "Textures");
if (!Array.Exists(sysFolders, delegate(XInventoryFolder f) { if (f.type == (int)FolderType.Trash) return true; return false; }))
CreateFolder(principalID, rootFolder.ID, (int)FolderType.Trash, "Trash");
return result;
}
protected XInventoryFolder CreateFolder(UUID principalID, UUID parentID, int type, string name)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.folderName = name;
newFolder.type = type;
newFolder.version = 1;
newFolder.folderID = UUID.Random();
newFolder.agentID = principalID;
newFolder.parentFolderID = parentID;
m_Database.StoreFolder(newFolder);
return newFolder;
}
protected virtual XInventoryFolder[] GetSystemFolders(UUID principalID, UUID rootID)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting system folders for {0}", principalID);
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID" },
new string[] { principalID.ToString(), rootID.ToString() });
XInventoryFolder[] sysFolders = Array.FindAll(
allFolders,
delegate (XInventoryFolder f)
{
if (f.type > 0)
return true;
return false;
});
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found {0} system folders for {1}", sysFolders.Length, principalID);
return sysFolders;
}
public virtual List<InventoryFolderBase> GetInventorySkeleton(UUID principalID)
{
XInventoryFolder[] allFolders = m_Database.GetFolders(
new string[] { "agentID" },
new string[] { principalID.ToString() });
if (allFolders.Length == 0)
return null;
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
foreach (XInventoryFolder x in allFolders)
{
//m_log.DebugFormat("[XINVENTORY SERVICE]: Adding folder {0} to skeleton", x.folderName);
folders.Add(ConvertToOpenSim(x));
}
return folders;
}
public virtual InventoryFolderBase GetRootFolder(UUID principalID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID"},
new string[] { principalID.ToString(), UUID.Zero.ToString() });
if (folders.Length == 0)
return null;
XInventoryFolder root = null;
foreach (XInventoryFolder folder in folders)
{
if (folder.folderName == InventoryFolderBase.ROOT_FOLDER_NAME)
{
root = folder;
break;
}
}
if (root == null) // oops
root = folders[0];
return ConvertToOpenSim(root);
}
public virtual InventoryFolderBase GetFolderForType(UUID principalID, FolderType type)
{
// m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0} for user {1}", type, principalID);
InventoryFolderBase rootFolder = GetRootFolder(principalID);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in GetFolderForType() when looking for {1}",
principalID, type);
return null;
}
return GetSystemFolderForType(rootFolder, type);
}
private InventoryFolderBase GetSystemFolderForType(InventoryFolderBase rootFolder, FolderType type)
{
//m_log.DebugFormat("[XINVENTORY SERVICE]: Getting folder type {0}", type);
if (type == FolderType.Root)
return rootFolder;
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "agentID", "parentFolderID", "type"},
new string[] { rootFolder.Owner.ToString(), rootFolder.ID.ToString(), ((int)type).ToString() });
if (folders.Length == 0)
{
//m_log.WarnFormat("[XINVENTORY SERVICE]: Found no folder for type {0} ", type);
return null;
}
//m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Found folder {0} {1} for type {2}",
// folders[0].folderName, folders[0].folderID, type);
return ConvertToOpenSim(folders[0]);
}
public virtual InventoryCollection GetFolderContent(UUID principalID, UUID folderID)
{
// This method doesn't receive a valud principal id from the
// connector. So we disregard the principal and look
// by ID.
//
//m_log.DebugFormat("[XINVENTORY SERVICE]: Fetch contents for folder {0}", folderID.ToString());
InventoryCollection inventory = new InventoryCollection();
inventory.OwnerID = principalID;
inventory.Folders = new List<InventoryFolderBase>();
inventory.Items = new List<InventoryItemBase>();
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryFolder x in folders)
{
//m_log.DebugFormat("[XINVENTORY]: Adding folder {0} to response", x.folderName);
inventory.Folders.Add(ConvertToOpenSim(x));
}
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID"},
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
{
//m_log.DebugFormat("[XINVENTORY]: Adding item {0} to response", i.inventoryName);
inventory.Items.Add(ConvertToOpenSim(i));
}
InventoryFolderBase f = GetFolder(principalID, folderID);
if (f != null)
{
inventory.Version = f.Version;
inventory.OwnerID = f.Owner;
}
inventory.FolderID = folderID;
return inventory;
}
public virtual InventoryCollection[] GetMultipleFoldersContent(UUID principalID, UUID[] folderIDs)
{
InventoryCollection[] multiple = new InventoryCollection[folderIDs.Length];
int i = 0;
foreach (UUID fid in folderIDs)
multiple[i++] = GetFolderContent(principalID, fid);
return multiple;
}
public virtual List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID)
{
// m_log.DebugFormat("[XINVENTORY]: Fetch items for folder {0}", folderID);
// Since we probably don't get a valid principal here, either ...
//
List<InventoryItemBase> invItems = new List<InventoryItemBase>();
XInventoryItem[] items = m_Database.GetItems(
new string[] { "parentFolderID" },
new string[] { folderID.ToString() });
foreach (XInventoryItem i in items)
invItems.Add(ConvertToOpenSim(i));
return invItems;
}
public virtual bool AddFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Add folder {0} type {1} in parent {2}", folder.Name, folder.Type, folder.ParentID);
InventoryFolderBase check = GetFolder(folder.Owner, folder.ID);
if (check != null)
return false;
if (folder.Type != (short)FolderType.None)
{
InventoryFolderBase rootFolder = GetRootFolder(folder.Owner);
if (rootFolder == null)
{
m_log.WarnFormat(
"[XINVENTORY]: Found no root folder for {0} in AddFolder() when looking for {1}",
folder.Owner, folder.Type);
return false;
}
// Check we're not trying to add this as a system folder.
if (folder.ParentID == rootFolder.ID)
{
InventoryFolderBase existingSystemFolder
= GetSystemFolderForType(rootFolder, (FolderType)folder.Type);
if (existingSystemFolder != null)
{
m_log.WarnFormat(
"[XINVENTORY]: System folder of type {0} already exists when tried to add {1} to {2} for {3}",
folder.Type, folder.Name, folder.ParentID, folder.Owner);
return false;
}
}
}
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
return m_Database.StoreFolder(xFolder);
}
public virtual bool UpdateFolder(InventoryFolderBase folder)
{
// m_log.DebugFormat("[XINVENTORY]: Update folder {0} {1} ({2})", folder.Name, folder.Type, folder.ID);
XInventoryFolder xFolder = ConvertFromOpenSim(folder);
InventoryFolderBase check = GetFolder(folder.Owner, folder.ID);
if (check == null)
return AddFolder(folder);
if ((check.Type != (short)FolderType.None || xFolder.type != (short)FolderType.None)
&& (check.Type != (short)FolderType.Outfit || xFolder.type != (short)FolderType.Outfit))
{
if (xFolder.version < check.Version)
{
// m_log.DebugFormat("[XINVENTORY]: {0} < {1} can't do", xFolder.version, check.Version);
return false;
}
check.Version = (ushort)xFolder.version;
xFolder = ConvertFromOpenSim(check);
// m_log.DebugFormat(
// "[XINVENTORY]: Storing version only update to system folder {0} {1} {2}",
// xFolder.folderName, xFolder.version, xFolder.type);
return m_Database.StoreFolder(xFolder);
}
if (xFolder.version < check.Version)
xFolder.version = check.Version;
xFolder.folderID = check.ID;
return m_Database.StoreFolder(xFolder);
}
public virtual bool MoveFolder(InventoryFolderBase folder)
{
return m_Database.MoveFolder(folder.ID.ToString(), folder.ParentID.ToString());
}
// We don't check the principal's ID here
//
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs)
{
return DeleteFolders(principalID, folderIDs, true);
}
public virtual bool DeleteFolders(UUID principalID, List<UUID> folderIDs, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
// Ignore principal ID, it's bogus at connector level
//
foreach (UUID id in folderIDs)
{
if (onlyIfTrash && !ParentIsTrash(id))
continue;
//m_log.InfoFormat("[XINVENTORY SERVICE]: Delete folder {0}", id);
InventoryFolderBase f = new InventoryFolderBase();
f.ID = id;
PurgeFolder(f, onlyIfTrash);
m_Database.DeleteFolders("folderID", id.ToString());
}
return true;
}
public virtual bool PurgeFolder(InventoryFolderBase folder)
{
return PurgeFolder(folder, true);
}
public virtual bool PurgeFolder(InventoryFolderBase folder, bool onlyIfTrash)
{
if (!m_AllowDelete)
return false;
if (onlyIfTrash && !ParentIsTrash(folder.ID))
return false;
XInventoryFolder[] subFolders = m_Database.GetFolders(
new string[] { "parentFolderID" },
new string[] { folder.ID.ToString() });
foreach (XInventoryFolder x in subFolders)
{
PurgeFolder(ConvertToOpenSim(x), onlyIfTrash);
m_Database.DeleteFolders("folderID", x.folderID.ToString());
}
m_Database.DeleteItems("parentFolderID", folder.ID.ToString());
return true;
}
public virtual bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[XINVENTORY SERVICE]: Adding item {0} {1} to folder {2} for {3}", item.Name, item.ID, item.Folder, item.Owner);
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool UpdateItem(InventoryItemBase item)
{
if (!m_AllowDelete)
if (item.AssetType == (sbyte)AssetType.Link || item.AssetType == (sbyte)AssetType.LinkFolder)
return false;
// m_log.InfoFormat(
// "[XINVENTORY SERVICE]: Updating item {0} {1} in folder {2}", item.Name, item.ID, item.Folder);
InventoryItemBase retrievedItem = GetItem(item.Owner, item.ID);
if (retrievedItem == null)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Tried to update item {0} {1}, owner {2} but no existing item found.",
item.Name, item.ID, item.Owner);
return false;
}
// Do not allow invariants to change. Changes to folder ID occur in MoveItems()
if (retrievedItem.InvType != item.InvType
|| retrievedItem.AssetType != item.AssetType
|| retrievedItem.Folder != item.Folder
|| retrievedItem.CreatorIdentification != item.CreatorIdentification
|| retrievedItem.Owner != item.Owner)
{
m_log.WarnFormat(
"[XINVENTORY SERVICE]: Caller to UpdateItem() for {0} {1} tried to alter property(s) that should be invariant, (InvType, AssetType, Folder, CreatorIdentification, Owner), existing ({2}, {3}, {4}, {5}, {6}), update ({7}, {8}, {9}, {10}, {11})",
retrievedItem.Name,
retrievedItem.ID,
retrievedItem.InvType,
retrievedItem.AssetType,
retrievedItem.Folder,
retrievedItem.CreatorIdentification,
retrievedItem.Owner,
item.InvType,
item.AssetType,
item.Folder,
item.CreatorIdentification,
item.Owner);
item.InvType = retrievedItem.InvType;
item.AssetType = retrievedItem.AssetType;
item.Folder = retrievedItem.Folder;
item.CreatorIdentification = retrievedItem.CreatorIdentification;
item.Owner = retrievedItem.Owner;
}
return m_Database.StoreItem(ConvertFromOpenSim(item));
}
public virtual bool MoveItems(UUID principalID, List<InventoryItemBase> items)
{
// Principal is b0rked. *sigh*
//
foreach (InventoryItemBase i in items)
{
m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString());
}
return true;
}
public virtual bool DeleteItems(UUID principalID, List<UUID> itemIDs)
{
if (!m_AllowDelete)
{
// We must still allow links and links to folders to be deleted, otherwise they will build up
// in the player's inventory until they can no longer log in. Deletions of links due to code bugs or
// similar is inconvenient but on a par with accidental movement of items. The original item is never
// touched.
foreach (UUID id in itemIDs)
{
if (!m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.Link).ToString() }))
{
m_Database.DeleteItems(
new string[] { "inventoryID", "assetType" },
new string[] { id.ToString(), ((sbyte)AssetType.LinkFolder).ToString() });
}
}
}
else
{
// Just use the ID... *facepalms*
//
foreach (UUID id in itemIDs)
m_Database.DeleteItems("inventoryID", id.ToString());
}
return true;
}
public virtual InventoryItemBase GetItem(UUID principalID, UUID itemID)
{
XInventoryItem[] items = m_Database.GetItems(
new string[] { "inventoryID" },
new string[] { itemID.ToString() });
if (items.Length == 0)
return null;
return ConvertToOpenSim(items[0]);
}
public virtual InventoryItemBase[] GetMultipleItems(UUID userID, UUID[] ids)
{
InventoryItemBase[] items = new InventoryItemBase[ids.Length];
int i = 0;
foreach (UUID id in ids)
items[i++] = GetItem(userID, id);
return items;
}
public virtual InventoryFolderBase GetFolder(UUID principalID, UUID folderID)
{
XInventoryFolder[] folders = m_Database.GetFolders(
new string[] { "folderID"},
new string[] { folderID.ToString() });
if (folders.Length == 0)
return null;
return ConvertToOpenSim(folders[0]);
}
public virtual List<InventoryItemBase> GetActiveGestures(UUID principalID)
{
XInventoryItem[] items = m_Database.GetActiveGestures(principalID);
if (items.Length == 0)
return new List<InventoryItemBase>();
List<InventoryItemBase> ret = new List<InventoryItemBase>();
foreach (XInventoryItem x in items)
ret.Add(ConvertToOpenSim(x));
return ret;
}
public virtual int GetAssetPermissions(UUID principalID, UUID assetID)
{
return m_Database.GetAssetPermissions(principalID, assetID);
}
// Unused.
//
public bool HasInventoryForUser(UUID userID)
{
return false;
}
// CM Helpers
//
protected InventoryFolderBase ConvertToOpenSim(XInventoryFolder folder)
{
InventoryFolderBase newFolder = new InventoryFolderBase();
newFolder.ParentID = folder.parentFolderID;
newFolder.Type = (short)folder.type;
//// Viewer can't understand anything that's not in it's LLFolderType enum
//if (newFolder.Type == InventoryItemBase.SUITCASE_FOLDER_TYPE)
// newFolder.Type = InventoryItemBase.SUITCASE_FOLDER_FAKE_TYPE;
newFolder.Version = (ushort)folder.version;
newFolder.Name = folder.folderName;
newFolder.Owner = folder.agentID;
newFolder.ID = folder.folderID;
return newFolder;
}
protected XInventoryFolder ConvertFromOpenSim(InventoryFolderBase folder)
{
XInventoryFolder newFolder = new XInventoryFolder();
newFolder.parentFolderID = folder.ParentID;
newFolder.type = (int)folder.Type;
newFolder.version = (int)folder.Version;
newFolder.folderName = folder.Name;
newFolder.agentID = folder.Owner;
newFolder.folderID = folder.ID;
return newFolder;
}
protected InventoryItemBase ConvertToOpenSim(XInventoryItem item)
{
InventoryItemBase newItem = new InventoryItemBase();
newItem.AssetID = item.assetID;
newItem.AssetType = item.assetType;
newItem.Name = item.inventoryName;
newItem.Owner = item.avatarID;
newItem.ID = item.inventoryID;
newItem.InvType = item.invType;
newItem.Folder = item.parentFolderID;
newItem.CreatorIdentification = item.creatorID;
newItem.Description = item.inventoryDescription;
newItem.NextPermissions = (uint)item.inventoryNextPermissions;
newItem.CurrentPermissions = (uint)item.inventoryCurrentPermissions;
newItem.BasePermissions = (uint)item.inventoryBasePermissions;
newItem.EveryOnePermissions = (uint)item.inventoryEveryOnePermissions;
newItem.GroupPermissions = (uint)item.inventoryGroupPermissions;
newItem.GroupID = item.groupID;
if (item.groupOwned == 0)
newItem.GroupOwned = false;
else
newItem.GroupOwned = true;
newItem.SalePrice = item.salePrice;
newItem.SaleType = (byte)item.saleType;
newItem.Flags = (uint)item.flags;
newItem.CreationDate = item.creationDate;
return newItem;
}
protected XInventoryItem ConvertFromOpenSim(InventoryItemBase item)
{
XInventoryItem newItem = new XInventoryItem();
newItem.assetID = item.AssetID;
newItem.assetType = item.AssetType;
newItem.inventoryName = item.Name;
newItem.avatarID = item.Owner;
newItem.inventoryID = item.ID;
newItem.invType = item.InvType;
newItem.parentFolderID = item.Folder;
newItem.creatorID = item.CreatorIdentification;
newItem.inventoryDescription = item.Description;
newItem.inventoryNextPermissions = (int)item.NextPermissions;
newItem.inventoryCurrentPermissions = (int)item.CurrentPermissions;
newItem.inventoryBasePermissions = (int)item.BasePermissions;
newItem.inventoryEveryOnePermissions = (int)item.EveryOnePermissions;
newItem.inventoryGroupPermissions = (int)item.GroupPermissions;
newItem.groupID = item.GroupID;
if (item.GroupOwned)
newItem.groupOwned = 1;
else
newItem.groupOwned = 0;
newItem.salePrice = item.SalePrice;
newItem.saleType = (int)item.SaleType;
newItem.flags = (int)item.Flags;
newItem.creationDate = item.CreationDate;
return newItem;
}
private bool ParentIsTrash(UUID folderID)
{
XInventoryFolder[] folder = m_Database.GetFolders(new string[] {"folderID"}, new string[] {folderID.ToString()});
if (folder.Length < 1)
return false;
if (folder[0].type == (int)FolderType.Trash)
return true;
UUID parentFolder = folder[0].parentFolderID;
while (parentFolder != UUID.Zero)
{
XInventoryFolder[] parent = m_Database.GetFolders(new string[] {"folderID"}, new string[] {parentFolder.ToString()});
if (parent.Length < 1)
return false;
if (parent[0].type == (int)FolderType.Trash)
return true;
if (parent[0].type == (int)FolderType.Root)
return false;
parentFolder = parent[0].parentFolderID;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Security
{
internal class SslState
{
//
// The public Client and Server classes enforce the parameters rules before
// calling into this .ctor.
//
internal SslState(Stream innerStream, RemoteCertValidationCallback certValidationCallback, LocalCertSelectionCallback certSelectionCallback, EncryptionPolicy encryptionPolicy)
{
}
//
//
//
internal void ValidateCreateContext(bool isServer, string targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertRevocationStatus)
{
}
internal bool IsAuthenticated
{
get
{
return false;
}
}
internal bool IsMutuallyAuthenticated
{
get
{
return false;
}
}
internal bool RemoteCertRequired
{
get
{
return false;
}
}
internal bool IsServer
{
get
{
return false;
}
}
//
// This will return selected local cert for both client/server streams
//
internal X509Certificate LocalCertificate
{
get
{
return null;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
return null;
}
internal bool CheckCertRevocationStatus
{
get
{
return false;
}
}
internal CipherAlgorithmType CipherAlgorithm
{
get
{
return CipherAlgorithmType.Null;
}
}
internal int CipherStrength
{
get
{
return 0;
}
}
internal HashAlgorithmType HashAlgorithm
{
get
{
return HashAlgorithmType.None;
}
}
internal int HashStrength
{
get
{
return 0;
}
}
internal ExchangeAlgorithmType KeyExchangeAlgorithm
{
get
{
return ExchangeAlgorithmType.None;
}
}
internal int KeyExchangeStrength
{
get
{
return 0;
}
}
internal SslProtocols SslProtocol
{
get
{
return SslProtocols.None;
}
}
internal _SslStream SecureStream
{
get
{
return null;
}
}
public bool IsShutdown { get; internal set; }
internal void CheckThrow(bool authSucessCheck)
{
}
internal void Flush()
{
}
internal Task FlushAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
//
// This is to not depend on GC&SafeHandle class if the context is not needed anymore.
//
internal void Close()
{
}
//
// This method assumes that a SSPI context is already in a good shape.
// For example it is either a fresh context or already authenticated context that needs renegotiation.
//
internal void ProcessAuthentication(LazyAsyncResult lazyResult)
{
}
internal void EndProcessAuthentication(IAsyncResult result)
{
}
internal IAsyncResult BeginShutdown(AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
internal void EndShutdown(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
}
internal class _SslStream : Stream
{
public override bool CanRead
{
get
{
throw new NotImplementedException();
}
}
public override bool CanSeek
{
get
{
throw new NotImplementedException();
}
}
public override bool CanWrite
{
get
{
throw new NotImplementedException();
}
}
public override long Length
{
get
{
throw new NotImplementedException();
}
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void Flush()
{
throw new NotImplementedException();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return Task.FromException(new NotImplementedException());
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public Task WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
{
throw new NotImplementedException();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
throw new NotImplementedException();
}
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotImplementedException();
}
}
}
| |
// 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.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Debugging
{
public partial class ProximityExpressionsGetterTests
{
private SyntaxTree GetTree()
{
return SyntaxFactory.ParseSyntaxTree(Resources.ProximityExpressionsGetterTestFile);
}
private SyntaxTree GetTreeFromCode(string code)
{
return SyntaxFactory.ParseSyntaxTree(code);
}
public async Task GenerateBaseline()
{
Console.WriteLine(typeof(FactAttribute));
var text = Resources.ProximityExpressionsGetterTestFile;
using (var workspace = await TestWorkspace.CreateCSharpAsync(text))
{
var languageDebugInfo = new CSharpLanguageDebugInfoService();
var hostdoc = workspace.Documents.First();
var snapshot = hostdoc.TextBuffer.CurrentSnapshot;
var document = workspace.CurrentSolution.GetDocument(hostdoc.Id);
var builder = new StringBuilder();
var statements = (await document.GetSyntaxRootAsync(CancellationToken.None)).DescendantTokens().Select(t => t.GetAncestor<StatementSyntax>()).Distinct().WhereNotNull();
// Try to get proximity expressions at every token position and the start of every
// line.
var index = 0;
foreach (var statement in statements)
{
builder.AppendLine("[WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]");
builder.AppendLine("public void TestAtStartOfStatement_" + index + "()");
builder.AppendLine("{");
var token = statement.GetFirstToken();
var line = snapshot.GetLineFromPosition(token.SpanStart);
builder.AppendLine(" //// Line " + (line.LineNumber + 1));
builder.AppendLine();
if (line.LineNumber > 0)
{
builder.AppendLine(" //// " + snapshot.GetLineFromLineNumber(line.LineNumber - 1).GetText());
}
builder.AppendLine(" //// " + line.GetText());
var charIndex = token.SpanStart - line.Start;
builder.AppendLine(" //// " + new string(' ', charIndex) + "^");
builder.AppendLine(" var tree = GetTree(\"ProximityExpressionsGetterTestFile.cs\");");
builder.AppendLine(" var terms = CSharpProximityExpressionsService.Do(tree, " + token.SpanStart + ");");
var proximityExpressionsGetter = new CSharpProximityExpressionsService();
var terms = await proximityExpressionsGetter.GetProximityExpressionsAsync(document, token.SpanStart, CancellationToken.None);
if (terms == null)
{
builder.AppendLine(" Assert.Null(terms);");
}
else
{
builder.AppendLine(" Assert.NotNull(terms);");
var termsString = terms.Select(t => "\"" + t + "\"").Join(", ");
builder.AppendLine(" AssertEx.Equal(new[] { " + termsString + " }, terms);");
}
builder.AppendLine("}");
builder.AppendLine();
index++;
}
var str = builder.ToString();
Console.WriteLine(str);
}
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public void TestWithinStatement_1()
{
var tree = GetTreeFromCode(@"using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var xx = true;
var yy = new List<bool>();
yy.Add(xx?true:false);
}
}
}");
var terms = CSharpProximityExpressionsService.Do(tree, 245);
Assert.NotNull(terms);
AssertEx.Equal(new[] { "yy", "xx" }, terms);
}
private async Task TestProximityExpressionGetterAsync(
string markup,
Func<CSharpProximityExpressionsService, Document, int, Task> continuation)
{
using (var workspace = await TestWorkspace.CreateCSharpAsync(markup))
{
var testDocument = workspace.Documents.Single();
var caretPosition = testDocument.CursorPosition.Value;
var snapshot = testDocument.TextBuffer.CurrentSnapshot;
var languageDebugInfo = new CSharpLanguageDebugInfoService();
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
var proximityExpressionsGetter = new CSharpProximityExpressionsService();
await continuation(proximityExpressionsGetter, document, caretPosition);
}
}
private async Task TestTryDoAsync(string input, params string[] expectedTerms)
{
await TestProximityExpressionGetterAsync(input, async (getter, document, position) =>
{
var actualTerms = await getter.GetProximityExpressionsAsync(document, position, CancellationToken.None);
Assert.Equal(expectedTerms.Length == 0, actualTerms == null);
if (expectedTerms.Length > 0)
{
AssertEx.Equal(expectedTerms, actualTerms);
}
});
}
private async Task TestIsValidAsync(string input, string expression, bool expectedValid)
{
await TestProximityExpressionGetterAsync(input, async (getter, semanticSnapshot, position) =>
{
var actualValid = await getter.IsValidAsync(semanticSnapshot, position, expression, CancellationToken.None);
Assert.Equal(expectedValid, actualValid);
});
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestTryDo1()
{
await TestTryDoAsync("class Class { void Method() { string local;$$ } }", "local", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestNoParentToken()
{
await TestTryDoAsync("$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValid1()
{
await TestIsValidAsync("class Class { void Method() { string local;$$ } }", "local", true);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValidWithDiagnostics()
{
// local doesn't exist in this context
await TestIsValidAsync("class Class { void Method() { string local; } $$}", "local", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValidReferencingLocalBeforeDeclaration()
{
await TestIsValidAsync("class Class { void Method() { $$int i; int j; } }", "j", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValidReferencingUndefinedVariable()
{
await TestIsValidAsync("class Class { void Method() { $$int i; int j; } }", "k", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValidNoTypeSymbol()
{
await TestIsValidAsync("namespace Namespace$$ { }", "foo", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestIsValidLocalAfterPosition()
{
await TestIsValidAsync("class Class { void Method() { $$ int i; string local; } }", "local", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestThis()
{
await TestTryDoAsync(@"
class Class
{
public Class() : this(true)
{
base.ToString();
this.ToString()$$;
}
}", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestArrayCreationExpression()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
int[] i = new int[] { 3 }$$;
}
}", "i", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestPostfixUnaryExpressionSyntax()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
int i = 3;
i++$$;
}
}", "i", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestLabeledStatement()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
label: int i = 3;
label2$$: i++;
}
}", "i", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestThrowStatement()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
e = new Exception();
thr$$ow e;
}
}", "e");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestDoStatement()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
do$$ { } while (true);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestLockStatement()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
lock(typeof(Cl$$ass)) { };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestWhileStatement()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
while(DateTime.Now <$$ DateTime.Now) { };
}
}", "DateTime", "DateTime.Now");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestForStatementWithDeclarators()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
for(int i = 0; i < 10; i$$++) { }
}
}", "i");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestForStatementWithInitializers()
{
await TestTryDoAsync(@"
class Class
{
static void Method()
{
int i = 0;
for(i = 1; i < 10; i$$++) { }
}
}", "i");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestUsingStatement()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
using (FileStream fs = new FileStream($$)) { }
}
}", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538879")]
public async Task TestValueInPropertySetter()
{
await TestTryDoAsync(@"
class Class
{
string Name
{
get { return """"; }
set { $$ }
}
}", "this", "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestValueInEventAdd()
{
await TestTryDoAsync(@"
class Class
{
event Action Event
{
add { $$ }
set { }
}
}", "this", "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestValueInEventRemove()
{
await TestTryDoAsync(@"
class Class
{
event Action Event
{
add { }
remove { $$ }
}
}", "this", "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538880")]
public async Task TestValueInIndexerSetter()
{
await TestTryDoAsync(@"
class Class
{
string this[int index]
{
get { return """"; }
set { $$ }
}
}", "index", "this", "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538881")]
public async Task TestCatchBlock()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
try { }
catch(Exception ex) { int $$ }
}
}", "ex", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538881")]
public async Task TestCatchBlockEmpty_OpenBrace()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
try { }
catch(Exception ex) { $$ }
}
}", "ex", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task TestCatchBlockEmpty_CloseBrace()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
try { }
catch(Exception ex) { } $$
}
}", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538874, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538874")]
public async Task TestObjectCreation()
{
await TestTryDoAsync(@"
class Class
{
void Method()
{
$$Foo(new Bar(a).Baz);
}
}", "a", "new Bar(a).Baz", "Foo", "this");
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538874, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538874")]
public async Task Test2()
{
await TestIsValidAsync(@"
class D
{
private static int x;
}
class Class
{
void Method()
{
$$Foo(D.x);
}
}", "D.x", false);
}
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
[WorkItem(538890, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538890")]
public async Task TestArrayCreation()
{
await TestTryDoAsync(@"
class Class
{
int a;
void Method()
{
$$new int[] { a };
}
}", "this");
}
[WorkItem(751141, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751141")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task Bug751141()
{
await TestTryDoAsync(@"
class Program
{
double m_double = 1.1;
static void Main(string[] args)
{
new Program().M();
}
void M()
{
int local_int = (int)m_double;
$$System.Diagnostics.Debugger.Break();
}
}
", "System.Diagnostics.Debugger", "local_int", "m_double", "(int)m_double", "this");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForLoopExpressionsInFirstStatementOfLoop1()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
for(int i = 0; i < 5; i++)
{
$$var x = 8;
}
}
}", "i", "x");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForLoopExpressionsInFirstStatementOfLoop2()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int i = 0, j = 0, k = 0, m = 0, n = 0;
for(i = 0; j < 5; k++)
{
$$m = 8;
n = 7;
}
}
}", "m", "i", "j", "k");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForLoopExpressionsInFirstStatementOfLoop3()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int i = 0, j = 0, k = 0, m = 0;
for(i = 0; j < 5; k++)
{
var m = 8;
$$var n = 7;
}
}
}", "m", "n");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForLoopExpressionsInFirstStatementOfLoop4()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int i = 0, j = 0, k = 0, m = 0;
for(i = 0; j < 5; k++)
$$m = 8;
}
}", "m", "i", "j", "k");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForEachLoopExpressionsInFirstStatementOfLoop1()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
foreach (var x in new int[] { 1, 2, 3 })
{
$$var z = 0;
}
}
}", "x", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ForEachLoopExpressionsInFirstStatementOfLoop2()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
foreach (var x in new int[] { 1, 2, 3 })
$$var z = 0;
}
}", "x", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterForLoop1()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0;
for (a = 5; b < 1; b++)
{
c = 8;
d = 9; // included
}
$$var z = 0;
}
}", "a", "b", "d", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterForLoop2()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0;
for (a = 5; b < 1; b++)
{
c = 8;
int d = 9; // not included
}
$$var z = 0;
}
}", "a", "b", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterForEachLoop()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0;
foreach (var q in new int[] {1, 2, 3})
{
c = 8;
d = 9; // included
}
$$var z = 0;
}
}", "q", "d", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterNestedForLoop()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
for (a = 5; b < 1; b++)
{
c = 8;
d = 9;
for (a = 7; b < 9; b--)
{
e = 8;
f = 10; // included
}
}
$$var z = 0;
}
}", "a", "b", "f", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterCheckedStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
checked
{
a = 7;
b = 0; // included
}
$$var z = 0;
}
}", "b", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterUncheckedStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
unchecked
{
a = 7;
b = 0; // included
}
$$var z = 0;
}
}", "b", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterIfStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
if (a == 0)
{
c = 8;
d = 9; // included
}
$$var z = 0;
}
}", "a", "d", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterIfStatementWithElse()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
if (a == 0)
{
c = 8;
d = 9; // included
}
else
{
e = 1;
f = 2; // included
}
$$var z = 0;
}
}", "a", "d", "f", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterLockStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
lock (new object())
{
a = 2;
b = 3; // included
}
$$var z = 0;
}
}", "b", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterSwitchStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0;
switch(a)
{
case 1:
b = 7;
c = 8; // included
break;
case 2:
d = 9;
e = 10; // included
break;
default:
f = 1;
g = 2; // included
break;
}
$$var z = 0;
}
}", "a", "c", "e", "g", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterTryStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0;
try
{
a = 2;
b = 3; // included
}
catch (System.DivideByZeroException)
{
c = 2;
d = 5; // included
}
catch (System.EntryPointNotFoundException)
{
e = 8;
f = 9; // included
}
$$var z = 0;
}
}", "b", "d", "f", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterTryStatementWithFinally()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0;
try
{
a = 2;
b = 3;
}
catch (System.DivideByZeroException)
{
c = 2;
d = 5;
}
catch (System.EntryPointNotFoundException)
{
e = 8;
f = 9;
}
finally
{
g = 2; // included
}
$$var z = 0;
}
}", "g", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterUsingStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0;
using (null as System.IDisposable)
{
a = 4;
b = 8; // Included
}
$$var z = 0;
}
}", "b", "z");
}
[WorkItem(775161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775161")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsAfterWhileStatement()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0;
while (a < 5)
{
a++;
b = 8; // Included
}
$$var z = 0;
}
}", "a", "b", "z");
}
[WorkItem(778215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/778215")]
[Fact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]
public async Task ExpressionsInParenthesizedExpressions()
{
await TestTryDoAsync(@"class Program
{
static void Main(string[] args)
{
int i = 0, j = 0, k = 0, m = 0;
int flags = 7;
if((flags & i) == k)
{
$$ m = 8;
}
}
}", "m", "flags", "i", "k");
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: A representation of an IEEE double precision
** floating point number.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Double : IComparable, IConvertible, IFormattable, IComparable<Double>, IEquatable<Double>, ISpanFormattable
{
private double m_value; // Do not rename (binary serialization)
//
// Public Constants
//
public const double MinValue = -1.7976931348623157E+308;
public const double MaxValue = 1.7976931348623157E+308;
// Note Epsilon should be a double whose hex representation is 0x1
// on little endian machines.
public const double Epsilon = 4.9406564584124654E-324;
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
public const double NaN = (double)0.0 / (double)0.0;
// We use this explicit definition to avoid the confusion between 0.0 and -0.0.
internal const double NegativeZero = -0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsFinite(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is infinite.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is NaN.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
return (bits & 0x7FFFFFFFFFFFFFFF) > 0x7FF0000000000000;
}
/// <summary>Determines whether the specified value is negative.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(double d)
{
var bits = unchecked((ulong)BitConverter.DoubleToInt64Bits(d));
return (bits & 0x8000000000000000) == 0x8000000000000000;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNegativeInfinity(double d)
{
return (d == double.NegativeInfinity);
}
/// <summary>Determines whether the specified value is normal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) != 0);
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPositiveInfinity(double d)
{
return (d == double.PositiveInfinity);
}
/// <summary>Determines whether the specified value is subnormal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(double d)
{
var bits = BitConverter.DoubleToInt64Bits(d);
bits &= 0x7FFFFFFFFFFFFFFF;
return (bits < 0x7FF0000000000000) && (bits != 0) && ((bits & 0x7FF0000000000000) == 0);
}
// Compares this object to another object, returning an instance of System.Relation.
// Null is considered less than any instance.
//
// If object is not of type Double, this method throws an ArgumentException.
//
// Returns a value less than zero if this object
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Double)
{
double d = (double)value;
if (m_value < d) return -1;
if (m_value > d) return 1;
if (m_value == d) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(d) ? 0 : -1);
else
return 1;
}
throw new ArgumentException(SR.Arg_MustBeDouble);
}
public int CompareTo(Double value)
{
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else
return 1;
}
// True if obj is another Double with the same value as the current instance. This is
// a method of object equality, that only returns true if obj is also a double.
public override bool Equals(Object obj)
{
if (!(obj is Double))
{
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
if (temp == m_value)
{
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
[NonVersionable]
public static bool operator ==(Double left, Double right)
{
return left == right;
}
[NonVersionable]
public static bool operator !=(Double left, Double right)
{
return left != right;
}
[NonVersionable]
public static bool operator <(Double left, Double right)
{
return left < right;
}
[NonVersionable]
public static bool operator >(Double left, Double right)
{
return left > right;
}
[NonVersionable]
public static bool operator <=(Double left, Double right)
{
return left <= right;
}
[NonVersionable]
public static bool operator >=(Double left, Double right)
{
return left >= right;
}
public bool Equals(Double obj)
{
if (obj == m_value)
{
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
[MethodImpl(MethodImplOptions.AggressiveInlining)] // 64-bit constants make the IL unusually large that makes the inliner to reject the method
public override int GetHashCode()
{
var bits = Unsafe.As<double, long>(ref m_value);
// Optimized check for IsNan() || IsZero()
if (((bits - 1) & 0x7FFFFFFFFFFFFFFF) >= 0x7FF0000000000000)
{
// Ensure that all NaNs and both zeros have the same hash code
bits &= 0x7FF0000000000000;
}
return unchecked((int)bits) ^ ((int)(bits >> 32));
}
public override String ToString()
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
public String ToString(String format)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
public String ToString(IFormatProvider provider)
{
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public String ToString(String format, IFormatProvider provider)
{
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
public static double Parse(String s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
// Parses a double from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
public static double Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(String s, out double result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out double result)
{
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out double result)
{
bool success = Number.TryParseDouble(s, style, info, out result);
if (!success)
{
ReadOnlySpan<char> sTrim = StringSpanHelpers.Trim(s);
if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol))
{
result = NaN;
}
else
{
return false; // We really failed
}
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Double;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return m_value;
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmPersonFPRegOT
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmPersonFPRegOT() : base()
{
Load += frmPersonFPRegOT_Load;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
public System.Windows.Forms.Label Label4;
public System.Windows.Forms.Panel picButtons;
public System.Windows.Forms.TextBox eName;
public System.Windows.Forms.PictureBox HiddenPict;
public System.Windows.Forms.ListBox Status;
private System.Windows.Forms.Button withEventsField_Close_Renamed;
public System.Windows.Forms.Button Close_Renamed {
get { return withEventsField_Close_Renamed; }
set {
if (withEventsField_Close_Renamed != null) {
withEventsField_Close_Renamed.Click -= Close_Renamed_Click;
}
withEventsField_Close_Renamed = value;
if (withEventsField_Close_Renamed != null) {
withEventsField_Close_Renamed.Click += Close_Renamed_Click;
}
}
}
public System.Windows.Forms.PictureBox Picture1;
public System.Windows.Forms.Label Samples;
public System.Windows.Forms.Label Label3;
public System.Windows.Forms.Label Label2;
public System.Windows.Forms.Label Prompt;
public System.Windows.Forms.Label Label1;
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmPersonFPRegOT));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this.picButtons = new System.Windows.Forms.Panel();
this.cmdExit = new System.Windows.Forms.Button();
this.Label4 = new System.Windows.Forms.Label();
this.eName = new System.Windows.Forms.TextBox();
this.HiddenPict = new System.Windows.Forms.PictureBox();
this.Status = new System.Windows.Forms.ListBox();
this.Close_Renamed = new System.Windows.Forms.Button();
this.Picture1 = new System.Windows.Forms.PictureBox();
this.Samples = new System.Windows.Forms.Label();
this.Label3 = new System.Windows.Forms.Label();
this.Label2 = new System.Windows.Forms.Label();
this.Prompt = new System.Windows.Forms.Label();
this.Label1 = new System.Windows.Forms.Label();
this.picButtons.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Text = "Registration Form";
this.ClientSize = new System.Drawing.Size(521, 311);
this.Location = new System.Drawing.Point(3, 29);
this.ControlBox = false;
this.KeyPreview = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.Control;
this.Enabled = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.Name = "frmPersonFPRegOT";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(521, 39);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 10;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Size = new System.Drawing.Size(73, 29);
this.cmdExit.Location = new System.Drawing.Point(432, 3);
this.cmdExit.TabIndex = 11;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.Label4.Text = "Registration Form";
this.Label4.ForeColor = System.Drawing.Color.White;
this.Label4.Size = new System.Drawing.Size(313, 25);
this.Label4.Location = new System.Drawing.Point(8, 8);
this.Label4.TabIndex = 12;
this.Label4.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label4.BackColor = System.Drawing.Color.Transparent;
this.Label4.Enabled = true;
this.Label4.Cursor = System.Windows.Forms.Cursors.Default;
this.Label4.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label4.UseMnemonic = true;
this.Label4.Visible = true;
this.Label4.AutoSize = false;
this.Label4.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label4.Name = "Label4";
this.eName.AutoSize = false;
this.eName.BackColor = System.Drawing.Color.Blue;
this.eName.ForeColor = System.Drawing.Color.White;
this.eName.Size = new System.Drawing.Size(489, 17);
this.eName.Location = new System.Drawing.Point(16, 48);
this.eName.ReadOnly = true;
this.eName.TabIndex = 9;
this.eName.Text = "name";
this.eName.AcceptsReturn = true;
this.eName.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.eName.CausesValidation = true;
this.eName.Enabled = true;
this.eName.HideSelection = true;
this.eName.MaxLength = 0;
this.eName.Cursor = System.Windows.Forms.Cursors.IBeam;
this.eName.Multiline = false;
this.eName.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.eName.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.eName.TabStop = true;
this.eName.Visible = true;
this.eName.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.eName.Name = "eName";
this.HiddenPict.Size = new System.Drawing.Size(41, 33);
this.HiddenPict.Location = new System.Drawing.Point(224, 328);
this.HiddenPict.TabIndex = 8;
this.HiddenPict.Visible = false;
this.HiddenPict.Dock = System.Windows.Forms.DockStyle.None;
this.HiddenPict.BackColor = System.Drawing.SystemColors.Control;
this.HiddenPict.CausesValidation = true;
this.HiddenPict.Enabled = true;
this.HiddenPict.ForeColor = System.Drawing.SystemColors.ControlText;
this.HiddenPict.Cursor = System.Windows.Forms.Cursors.Default;
this.HiddenPict.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.HiddenPict.TabStop = true;
this.HiddenPict.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.HiddenPict.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.HiddenPict.Name = "HiddenPict";
this.Status.Size = new System.Drawing.Size(289, 176);
this.Status.Location = new System.Drawing.Point(216, 128);
this.Status.TabIndex = 6;
this.Status.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Status.BackColor = System.Drawing.SystemColors.Window;
this.Status.CausesValidation = true;
this.Status.Enabled = true;
this.Status.ForeColor = System.Drawing.SystemColors.WindowText;
this.Status.IntegralHeight = true;
this.Status.Cursor = System.Windows.Forms.Cursors.Default;
this.Status.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.Status.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Status.Sorted = false;
this.Status.TabStop = true;
this.Status.Visible = true;
this.Status.MultiColumn = false;
this.Status.Name = "Status";
this.Close_Renamed.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.Close_Renamed.Text = "Close";
this.Close_Renamed.Size = new System.Drawing.Size(81, 25);
this.Close_Renamed.Location = new System.Drawing.Point(416, 320);
this.Close_Renamed.TabIndex = 4;
this.Close_Renamed.Visible = false;
this.Close_Renamed.BackColor = System.Drawing.SystemColors.Control;
this.Close_Renamed.CausesValidation = true;
this.Close_Renamed.Enabled = true;
this.Close_Renamed.ForeColor = System.Drawing.SystemColors.ControlText;
this.Close_Renamed.Cursor = System.Windows.Forms.Cursors.Default;
this.Close_Renamed.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Close_Renamed.TabStop = true;
this.Close_Renamed.Name = "Close_Renamed";
this.Picture1.Size = new System.Drawing.Size(185, 185);
this.Picture1.Location = new System.Drawing.Point(16, 72);
this.Picture1.TabIndex = 0;
this.Picture1.Dock = System.Windows.Forms.DockStyle.None;
this.Picture1.BackColor = System.Drawing.SystemColors.Control;
this.Picture1.CausesValidation = true;
this.Picture1.Enabled = true;
this.Picture1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Picture1.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture1.TabStop = true;
this.Picture1.Visible = true;
this.Picture1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Normal;
this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Picture1.Name = "Picture1";
this.Samples.Size = new System.Drawing.Size(41, 25);
this.Samples.Location = new System.Drawing.Point(160, 272);
this.Samples.TabIndex = 7;
this.Samples.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Samples.BackColor = System.Drawing.SystemColors.Control;
this.Samples.Enabled = true;
this.Samples.ForeColor = System.Drawing.SystemColors.ControlText;
this.Samples.Cursor = System.Windows.Forms.Cursors.Default;
this.Samples.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Samples.UseMnemonic = true;
this.Samples.Visible = true;
this.Samples.AutoSize = false;
this.Samples.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Samples.Name = "Samples";
this.Label3.Text = "Fingerprint samples needed:";
this.Label3.Size = new System.Drawing.Size(145, 25);
this.Label3.Location = new System.Drawing.Point(16, 272);
this.Label3.TabIndex = 5;
this.Label3.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label3.BackColor = System.Drawing.SystemColors.Control;
this.Label3.Enabled = true;
this.Label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label3.Cursor = System.Windows.Forms.Cursors.Default;
this.Label3.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label3.UseMnemonic = true;
this.Label3.Visible = true;
this.Label3.AutoSize = false;
this.Label3.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label3.Name = "Label3";
this.Label2.Text = "Status:";
this.Label2.Size = new System.Drawing.Size(177, 17);
this.Label2.Location = new System.Drawing.Point(216, 112);
this.Label2.TabIndex = 3;
this.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label2.BackColor = System.Drawing.SystemColors.Control;
this.Label2.Enabled = true;
this.Label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label2.Cursor = System.Windows.Forms.Cursors.Default;
this.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label2.UseMnemonic = true;
this.Label2.Visible = true;
this.Label2.AutoSize = false;
this.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label2.Name = "Label2";
this.Prompt.Text = "Touch the fingerprint reader.";
this.Prompt.Size = new System.Drawing.Size(289, 17);
this.Prompt.Location = new System.Drawing.Point(216, 88);
this.Prompt.TabIndex = 2;
this.Prompt.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Prompt.BackColor = System.Drawing.SystemColors.Control;
this.Prompt.Enabled = true;
this.Prompt.ForeColor = System.Drawing.SystemColors.ControlText;
this.Prompt.Cursor = System.Windows.Forms.Cursors.Default;
this.Prompt.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Prompt.UseMnemonic = true;
this.Prompt.Visible = true;
this.Prompt.AutoSize = false;
this.Prompt.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Prompt.Name = "Prompt";
this.Label1.Text = "Prompt:";
this.Label1.Size = new System.Drawing.Size(177, 17);
this.Label1.Location = new System.Drawing.Point(216, 72);
this.Label1.TabIndex = 1;
this.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.Label1.BackColor = System.Drawing.SystemColors.Control;
this.Label1.Enabled = true;
this.Label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.Label1.Cursor = System.Windows.Forms.Cursors.Default;
this.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Label1.UseMnemonic = true;
this.Label1.Visible = true;
this.Label1.AutoSize = false;
this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.Label1.Name = "Label1";
this.Controls.Add(picButtons);
this.Controls.Add(eName);
this.Controls.Add(HiddenPict);
this.Controls.Add(Status);
this.Controls.Add(Close_Renamed);
this.Controls.Add(Picture1);
this.Controls.Add(Samples);
this.Controls.Add(Label3);
this.Controls.Add(Label2);
this.Controls.Add(Prompt);
this.Controls.Add(Label1);
this.picButtons.Controls.Add(cmdExit);
this.picButtons.Controls.Add(Label4);
this.picButtons.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenQA.Selenium.Environment;
namespace OpenQA.Selenium
{
[TestFixture]
public class CookieImplementationTest : DriverTestFixture
{
private Random random = new Random();
private bool isOnAlternativeHostName;
private string hostname;
[SetUp]
public void GoToSimplePageAndDeleteCookies()
{
GotoValidDomainAndClearCookies("animals");
AssertNoCookiesArePresent();
}
[Test]
[Category("JavaScript")]
public void ShouldGetCookieByName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = string.Format("key_{0}", new Random().Next());
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key);
Cookie cookie = driver.Manage().Cookies.GetCookieNamed(key);
Assert.AreEqual("set", cookie.Value);
}
[Test]
[Category("JavaScript")]
public void ShouldBeAbleToAddCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
Assert.That(driver.Manage().Cookies.AllCookies.Contains(cookie), "Cookie was not added successfully");
}
[Test]
public void GetAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsNotPresentWithName(key2);
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
int count = cookies.Count;
Cookie one = new Cookie(key1, "value");
Cookie two = new Cookie(key2, "value");
driver.Manage().Cookies.AddCookie(one);
driver.Manage().Cookies.AddCookie(two);
driver.Url = simpleTestPage;
cookies = driver.Manage().Cookies.AllCookies;
Assert.AreEqual(count + 2, cookies.Count);
Assert.IsTrue(cookies.Contains(one));
Assert.IsTrue(cookies.Contains(two));
}
[Test]
[Category("JavaScript")]
public void DeleteAllCookies()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = 'foo=set';");
AssertSomeCookiesArePresent();
driver.Manage().Cookies.DeleteAllCookies();
AssertNoCookiesArePresent();
}
[Test]
[Category("JavaScript")]
public void DeleteCookieWithName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key1 = GenerateUniqueKey();
string key2 = GenerateUniqueKey();
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key1);
((IJavaScriptExecutor)driver).ExecuteScript("document.cookie = arguments[0] + '=set';", key2);
AssertCookieIsPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
driver.Manage().Cookies.DeleteCookieNamed(key1);
AssertCookieIsNotPresentWithName(key1);
AssertCookieIsPresentWithName(key2);
}
[Test]
public void ShouldNotDeleteCookiesWithASimilarName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieOneName = "fish";
Cookie cookie1 = new Cookie(cookieOneName, "cod");
Cookie cookie2 = new Cookie(cookieOneName + "x", "earth");
IOptions options = driver.Manage();
AssertCookieIsNotPresentWithName(cookie1.Name);
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
AssertCookieIsPresentWithName(cookie1.Name);
options.Cookies.DeleteCookieNamed(cookieOneName);
Assert.IsFalse(driver.Manage().Cookies.AllCookies.Contains(cookie1));
Assert.IsTrue(driver.Manage().Cookies.AllCookies.Contains(cookie2));
}
[Test]
public void AddCookiesWithDifferentPathsThatAreRelatedToOurs()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
UrlBuilder builder = EnvironmentManager.Instance.UrlBuilder;
driver.Url = builder.WhereIs("animals");
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
AssertCookieIsPresentWithName(cookie1.Name);
AssertCookieIsPresentWithName(cookie2.Name);
driver.Url = builder.WhereIs("simplePage.html");
AssertCookieIsNotPresentWithName(cookie1.Name);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CannotGetCookiesWithPathDifferingOnlyInCase()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod", "/Common/animals"));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
Assert.IsNull(driver.Manage().Cookies.GetCookieNamed(cookieName));
}
[Test]
public void ShouldNotGetCookieOnDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "fish";
driver.Manage().Cookies.AddCookie(new Cookie(cookieName, "cod"));
AssertCookieIsPresentWithName(cookieName);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
[Ignore("Cannot run without creating subdomains in test environment")]
public void ShouldBeAbleToAddToADomainWhichIsRelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
AssertCookieIsNotPresentWithName("name");
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, "", 1);
Cookie cookie = new Cookie("name", "value", shorter, "/", GetTimeInTheFuture());
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
[Ignore("Cannot run without creating subdomains in test environment")]
public void ShouldNotGetCookiesRelatedToCurrentDomainWithoutLeadingPeriod()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".", 1);
Cookie cookie = new Cookie(cookieName, "value", shorter, "/", GetTimeInTheFuture());
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsNotPresentWithName(cookieName);
}
[Test]
public void ShouldBeAbleToIncludeLeadingPeriodInDomainName()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
AssertCookieIsNotPresentWithName("name");
// Replace the first part of the name with a period
Regex replaceRegex = new Regex(".*?\\.");
string shorter = replaceRegex.Replace(this.hostname, ".");
Cookie cookie = new Cookie("name", "value", shorter, "/", DateTime.Now.AddSeconds(100000));
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName("name");
}
[Test]
[IgnoreBrowser(Browser.IE, "IE cookies do not conform to RFC, so setting cookie on domain fails.")]
public void ShouldBeAbleToSetDomainToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Uri url = new Uri(driver.Url);
String host = url.Host + ":" + url.Port.ToString();
Cookie cookie1 = new Cookie("fish", "cod", host, "/", null);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
driver.Url = javascriptPage;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.IsTrue(cookies.Contains(cookie1));
}
[Test]
public void ShouldWalkThePathToDeleteACookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod");
driver.Manage().Cookies.AddCookie(cookie1);
int count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = childPage;
Cookie cookie2 = new Cookie("rodent", "hamster", "/" + basePath + "/child");
driver.Manage().Cookies.AddCookie(cookie2);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = grandchildPage;
Cookie cookie3 = new Cookie("dog", "dalmation", "/" + basePath + "/child/grandchild/");
driver.Manage().Cookies.AddCookie(cookie3);
count = driver.Manage().Cookies.AllCookies.Count;
driver.Url = (EnvironmentManager.Instance.UrlBuilder.WhereIs("child/grandchild"));
driver.Manage().Cookies.DeleteCookieNamed("rodent");
count = driver.Manage().Cookies.AllCookies.Count;
Assert.IsNull(driver.Manage().Cookies.GetCookieNamed("rodent"));
ReadOnlyCollection<Cookie> cookies = driver.Manage().Cookies.AllCookies;
Assert.AreEqual(2, cookies.Count);
Assert.IsTrue(cookies.Contains(cookie1));
Assert.IsTrue(cookies.Contains(cookie3));
driver.Manage().Cookies.DeleteAllCookies();
driver.Url = grandchildPage;
AssertNoCookiesArePresent();
}
[Test]
[IgnoreBrowser(Browser.IE, "IE cookies do not conform to RFC, so setting cookie on domain fails.")]
public void ShouldIgnoreThePortNumberOfTheHostWhenSettingTheCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Uri uri = new Uri(driver.Url);
string host = string.Format("{0}:{1}", uri.Host, uri.Port);
string cookieName = "name";
AssertCookieIsNotPresentWithName(cookieName);
Cookie cookie = new Cookie(cookieName, "value", host, "/", null);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieIsPresentWithName(cookieName);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
public void CookieEqualityAfterSetAndGet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime time = DateTime.Now.AddDays(1);
Cookie cookie1 = new Cookie("fish", "cod", null, "/common/animals", time);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Cookie retrievedCookie = null;
foreach (Cookie tempCookie in cookies)
{
if (cookie1.Equals(tempCookie))
{
retrievedCookie = tempCookie;
break;
}
}
Assert.IsNotNull(retrievedCookie);
//Cookie.equals only compares name, domain and path
Assert.AreEqual(cookie1, retrievedCookie);
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not return expiry info")]
[IgnoreBrowser(Browser.Android, "Chrome and Selenium, which use JavaScript to retrieve cookies, cannot return expiry info;")]
[IgnoreBrowser(Browser.Opera)]
public void ShouldRetainCookieExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
// DateTime.Now contains milliseconds; the returned cookie expire date
// will not. So we need to truncate the milliseconds.
DateTime current = DateTime.Now;
DateTime expireDate = new DateTime(current.Year, current.Month, current.Day, current.Hour, current.Minute, current.Second, DateTimeKind.Local).AddDays(1);
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", expireDate);
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.IsNotNull(retrieved);
Assert.AreEqual(addCookie.Expiry, retrieved.Expiry, "Cookies are not equal");
}
[Test]
public void SettingACookieThatExpiredInThePast()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
DateTime expires = DateTime.Now.AddSeconds(-1000);
Cookie cookie = new Cookie("expired", "yes", "/common/animals", expires);
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie);
cookie = options.Cookies.GetCookieNamed("expired");
Assert.IsNull(cookie, "Cookie expired before it was set, so nothing should be returned: " + cookie);
}
[Test]
public void CanSetCookieWithoutOptionalFieldsSet()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string key = GenerateUniqueKey();
string value = "foo";
Cookie cookie = new Cookie(key, value);
AssertCookieIsNotPresentWithName(key);
driver.Manage().Cookies.AddCookie(cookie);
AssertCookieHasValue(key, value);
}
//////////////////////////////////////////////
// Tests unique to the .NET language bindings
//////////////////////////////////////////////
[Test]
[IgnoreBrowser(Browser.Chrome)]
public void CanSetCookiesOnADifferentPathOfTheSameHost()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string basePath = EnvironmentManager.Instance.UrlBuilder.Path;
Cookie cookie1 = new Cookie("fish", "cod", "/" + basePath + "/animals");
Cookie cookie2 = new Cookie("planet", "earth", "/" + basePath + "/galaxy");
IOptions options = driver.Manage();
ReadOnlyCollection<Cookie> count = options.Cookies.AllCookies;
options.Cookies.AddCookie(cookie1);
options.Cookies.AddCookie(cookie2);
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("animals");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.IsTrue(cookies.Contains(cookie1));
Assert.IsFalse(cookies.Contains(cookie2));
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("galaxy");
cookies = options.Cookies.AllCookies;
Assert.IsFalse(cookies.Contains(cookie1));
Assert.IsTrue(cookies.Contains(cookie2));
}
[Test]
public void ShouldNotBeAbleToSetDomainToSomethingThatIsUnrelatedToTheCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("simpleTest.html");
driver.Url = url;
Assert.IsNull(options.Cookies.GetCookieNamed("fish"));
}
[Test]
public void GetCookieDoesNotRetriveBeyondCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
Cookie cookie1 = new Cookie("fish", "cod");
IOptions options = driver.Manage();
options.Cookies.AddCookie(cookie1);
String url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("");
driver.Url = url;
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.IsFalse(cookies.Contains(cookie1));
}
[Test]
public void ShouldAddCookieToCurrentDomainAndPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
// Cookies cannot be set on domain names with less than 2 dots, so
// localhost is out. If we are in that boat, bail the test.
string hostName = EnvironmentManager.Instance.UrlBuilder.HostName;
string[] hostNameParts = hostName.Split(new char[] { '.' });
if (hostNameParts.Length < 3)
{
Assert.Ignore("Skipping test: Cookies can only be set on fully-qualified domain names.");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Homer", "Simpson", this.hostname, "/" + EnvironmentManager.Instance.UrlBuilder.Path, null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
[IgnoreBrowser(Browser.IE, "Add cookie to unrelated domain silently fails for IE.")]
[ExpectedException(typeof(WebDriverException))]
public void ShouldNotShowCookieAddedToDifferentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
Assert.Ignore("Not on a standard domain for cookies (localhost doesn't count).");
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Bart", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName + ".com", EnvironmentManager.Instance.UrlBuilder.Path, null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned");
}
[Test]
public void ShouldNotShowCookieAddedToDifferentPath()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Lisa", "Simpson", EnvironmentManager.Instance.UrlBuilder.HostName, "/" + EnvironmentManager.Instance.UrlBuilder.Path + "IDoNotExist", null);
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.IsFalse(cookies.Contains(cookie), "Invalid cookie was returned");
}
// TODO(JimEvans): Disabling this test for now. If your network is using
// something like OpenDNS or Google DNS which you may be automatically
// redirected to a search page, which will be a valid page and will allow a
// cookie to be created. Need to investigate further.
// [Test]
// [ExpectedException(typeof(InvalidOperationException))]
public void ShouldThrowExceptionWhenAddingCookieToNonExistingDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
driver.Url = "doesnot.noireallyreallyreallydontexist.com";
IOptions options = driver.Manage();
Cookie cookie = new Cookie("question", "dunno");
options.Cookies.AddCookie(cookie);
}
[Test]
public void ShouldReturnNullBecauseCookieRetainsExpiry()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
string url = EnvironmentManager.Instance.UrlBuilder.WhereElseIs("animals");
driver.Url = url;
driver.Manage().Cookies.DeleteAllCookies();
Cookie addCookie = new Cookie("fish", "cod", "/common/animals", DateTime.Now.AddHours(-1));
IOptions options = driver.Manage();
options.Cookies.AddCookie(addCookie);
Cookie retrieved = options.Cookies.GetCookieNamed("fish");
Assert.IsNull(retrieved);
}
[Test]
public void ShouldAddCookieToCurrentDomain()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookie = new Cookie("Marge", "Simpson", "/");
options.Cookies.AddCookie(cookie);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
Assert.That(cookies.Contains(cookie), "Valid cookie was not returned");
}
[Test]
public void ShouldDeleteCookie()
{
if (!CheckIsOnValidHostNameForCookieTests())
{
return;
}
driver.Url = macbethPage;
IOptions options = driver.Manage();
Cookie cookieToDelete = new Cookie("answer", "42");
Cookie cookieToKeep = new Cookie("canIHaz", "Cheeseburguer");
options.Cookies.AddCookie(cookieToDelete);
options.Cookies.AddCookie(cookieToKeep);
ReadOnlyCollection<Cookie> cookies = options.Cookies.AllCookies;
options.Cookies.DeleteCookie(cookieToDelete);
ReadOnlyCollection<Cookie> cookies2 = options.Cookies.AllCookies;
Assert.IsFalse(cookies2.Contains(cookieToDelete), "Cookie was not deleted successfully");
Assert.That(cookies2.Contains(cookieToKeep), "Valid cookie was not returned");
}
//////////////////////////////////////////////
// Support functions
//////////////////////////////////////////////
private void GotoValidDomainAndClearCookies(string page)
{
this.hostname = null;
String hostname = EnvironmentManager.Instance.UrlBuilder.HostName;
if (IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = false;
this.hostname = hostname;
}
hostname = EnvironmentManager.Instance.UrlBuilder.AlternateHostName;
if (this.hostname == null && IsValidHostNameForCookieTests(hostname))
{
this.isOnAlternativeHostName = true;
this.hostname = hostname;
}
GoToPage(page);
driver.Manage().Cookies.DeleteAllCookies();
}
private bool CheckIsOnValidHostNameForCookieTests()
{
bool correct = this.hostname != null && IsValidHostNameForCookieTests(this.hostname);
if (!correct)
{
System.Console.WriteLine("Skipping test: unable to find domain name to use");
}
return correct;
}
private void GoToPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName);
}
private void GoToOtherPage(String pageName)
{
driver.Url = this.isOnAlternativeHostName ? EnvironmentManager.Instance.UrlBuilder.WhereIs(pageName) : EnvironmentManager.Instance.UrlBuilder.WhereElseIs(pageName);
}
private bool IsValidHostNameForCookieTests(string hostname)
{
// TODO(JimEvan): Some coverage is better than none, so we
// need to ignore the fact that localhost cookies are problematic.
// Reenable this when we have a better solution per DanielWagnerHall.
// ChromeDriver2 has trouble with localhost. IE and Firefox don't.
// return !IsIpv4Address(hostname) && "localhost" != hostname;
return !IsIpv4Address(hostname) && ("localhost" != hostname && TestUtilities.IsChrome(driver));
}
private static bool IsIpv4Address(string addrString)
{
return Regex.IsMatch(addrString, "\\d{1,3}(?:\\.\\d{1,3}){3}");
}
private string GenerateUniqueKey()
{
return string.Format("key_{0}", random.Next());
}
private string GetDocumentCookieOrNull()
{
IJavaScriptExecutor jsDriver = driver as IJavaScriptExecutor;
if (jsDriver == null)
{
return null;
}
try
{
return (string)jsDriver.ExecuteScript("return document.cookie");
}
catch (InvalidOperationException)
{
return null;
}
}
private void AssertNoCookiesArePresent()
{
Assert.IsTrue(driver.Manage().Cookies.AllCookies.Count == 0, "Cookies were not empty");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreEqual(string.Empty, documentCookie, "Cookies were not empty");
}
}
private void AssertSomeCookiesArePresent()
{
Assert.IsFalse(driver.Manage().Cookies.AllCookies.Count == 0, "Cookies were empty");
String documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.AreNotEqual(string.Empty, documentCookie, "Cookies were empty");
}
}
private void AssertCookieIsNotPresentWithName(string key)
{
Assert.IsNull(driver.Manage().Cookies.GetCookieNamed(key), "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.IsFalse(documentCookie.Contains(key + "="), "Cookie was present with name " + key);
}
}
private void AssertCookieIsPresentWithName(string key)
{
Assert.IsNotNull(driver.Manage().Cookies.GetCookieNamed(key), "Cookie was present with name " + key);
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.IsTrue(documentCookie.Contains(key + "="), "Cookie was present with name " + key);
}
}
private void AssertCookieHasValue(string key, string value)
{
Assert.AreEqual(value, driver.Manage().Cookies.GetCookieNamed(key).Value, "Cookie had wrong value");
string documentCookie = GetDocumentCookieOrNull();
if (documentCookie != null)
{
Assert.IsTrue(documentCookie.Contains(key + "=" + value), "Cookie was present with name " + key);
}
}
private DateTime GetTimeInTheFuture()
{
return DateTime.Now.Add(TimeSpan.FromMilliseconds(100000));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics;
using System.Security;
using System.Security.Cryptography;
namespace Security.Cryptography
{
/// <summary>
/// Generic implementation of an authenticated symmetric algorithm which is provided by the BCrypt
/// layer of CNG. Concrete AuthenticatedSymmetricAlgorithm classes should contain an instance of this
/// type and delegate all of their work to that object.
///
/// Most of the real encryption work occurs in the BCryptAuthenticatedCryptoTransform class. (see
/// code:code:Microsoft.Security.Cryptography.BCryptAuthenticatedSymmetricCryptoTransform).
/// </summary>
internal sealed class BCryptAuthenticatedSymmetricAlgorithm : AuthenticatedSymmetricAlgorithm, ICngSymmetricAlgorithm
{
private CngAlgorithm m_algorithm;
private CngChainingMode m_chainingMode;
private CngProvider m_implementation;
[SecurityCritical]
[SecuritySafeCritical]
internal BCryptAuthenticatedSymmetricAlgorithm(CngAlgorithm algorithm,
CngProvider implementation,
KeySizes[] legalBlockSizes,
KeySizes[] legalKeySizes)
{
Debug.Assert(algorithm != null, "algorithm != null");
Debug.Assert(implementation != null, "implementation != null");
Debug.Assert(legalBlockSizes != null, "legalBlockSizes != null");
Debug.Assert(legalKeySizes != null, "legalKeySizes != null");
m_algorithm = algorithm;
m_implementation = implementation;
m_chainingMode = CngChainingMode.Gcm;
LegalBlockSizesValue = legalBlockSizes;
LegalKeySizesValue = legalKeySizes;
// Create a temporary algorithm handle so that we can query it for some properties - such as the
// block and tag sizes.
using (SafeBCryptAlgorithmHandle algorithmHandle = SetupAlgorithm())
{
// Get block size in bits
BlockSize = BCryptNative.GetInt32Property(algorithmHandle, BCryptNative.ObjectPropertyName.BlockLength) * 8;
UpdateLegalTagSizes(algorithmHandle);
}
}
/// <summary>
/// Determine if the current mode supports calculating the authenticated cipher across multiple
/// transform calls, or must the entire cipher be calculated at once.
/// </summary>
public bool ChainingSupported
{
get
{
// Currently only CCM does not support chaining.
return m_chainingMode != CngChainingMode.Ccm;
}
}
/// <summary>
/// Chaining mode to use for chaining in the authenticated algorithm. This value should be one
/// of the CNG modes that is an authenticated chaining mode such as CCM or GCM.
/// </summary>
public CngChainingMode CngMode
{
get { return m_chainingMode; }
set
{
if (value == null)
throw new ArgumentNullException("value");
// Updating the chaining mode requires doing other work, such as figuring out the new set of
// legal tag sizes. If we're just setting to the same value we already were in, then don't
// bother changing the value.
if (m_chainingMode != value)
{
// Don't do a direct check for GCM or CCM since we want to allow expansion to future
// authenticated chaining modes.
m_chainingMode = value;
// Legal tag sizes vary with chaining mode, so we need to update them when we update the
// chaining mode. Preserve the existing tag in case it's still legal in the new mode.
byte[] tag = Tag;
try
{
UpdateLegalTagSizes();
// If the old tag is still of a legal tag size, restore it as the new tag now.
if (ValidTagSize(tag.Length * 8))
{
Tag = tag;
}
}
finally
{
Array.Clear(tag, 0, tag.Length);
}
}
}
}
/// <summary>
/// Algorithm provider which is implementing the authenticated transform
/// </summary>
public CngProvider Provider
{
get { return m_implementation; }
}
[SecurityCritical]
[SecuritySafeCritical]
public override IAuthenticatedCryptoTransform CreateAuthenticatedEncryptor(byte[] rgbKey,
byte[] rgbIV,
byte[] rgbAuthenticatedData)
{
return new BCryptAuthenticatedSymmetricCryptoTransform(SetupAlgorithm(),
rgbKey,
rgbIV,
rgbAuthenticatedData,
ChainingSupported,
TagSize);
}
[SecurityCritical]
[SecuritySafeCritical]
public override ICryptoTransform CreateDecryptor(byte[] rgbKey,
byte[] rgbIV,
byte[] rgbAuthenticatedData,
byte[] rgbTag)
{
if (rgbKey == null)
throw new ArgumentNullException("rgbKey");
if (rgbTag == null)
throw new ArgumentNullException("rgbTag");
return new BCryptAuthenticatedSymmetricCryptoTransform(SetupAlgorithm(),
rgbKey,
rgbIV,
rgbAuthenticatedData,
rgbTag,
ChainingSupported);
}
/// <summary>
/// Build an algorithm handle setup according to the parameters of this AES object
/// </summary>
[SecurityCritical]
private SafeBCryptAlgorithmHandle SetupAlgorithm()
{
// Open the algorithm handle
SafeBCryptAlgorithmHandle algorithm =
BCryptNative.OpenAlgorithm(m_algorithm.Algorithm, m_implementation.Provider);
// Set the chaining mode
BCryptNative.SetStringProperty(algorithm,
BCryptNative.ObjectPropertyName.ChainingMode,
m_chainingMode.ChainingMode);
return algorithm;
}
public override void GenerateIV()
{
// Both GCM and CCM work well with 12 byte nonces, so use that by default.
IVValue = RNGCng.GenerateKey(12);
}
public override void GenerateKey()
{
KeyValue = RNGCng.GenerateKey(KeySizeValue / 8);
}
/// <summary>
/// Update the legal tag sizes for this algorithm
/// </summary>
[SecurityCritical]
[SecuritySafeCritical]
private void UpdateLegalTagSizes()
{
using (SafeBCryptAlgorithmHandle algorithm = SetupAlgorithm())
{
UpdateLegalTagSizes(algorithm);
}
}
/// <summary>
/// Update the legal tag sizes for this algortithm from an already opened algorithm handle
/// </summary>
[SecurityCritical]
private void UpdateLegalTagSizes(SafeBCryptAlgorithmHandle algorithm)
{
Debug.Assert(algorithm != null, "algorithm != null");
Debug.Assert(!algorithm.IsClosed && !algorithm.IsInvalid, "!algorithm.IsClosed && !algorithm.IsInvalid");
// Get the authentication tag length structure.
BCryptNative.BCRYPT_KEY_LENGTHS_STRUCT tagLengths =
BCryptNative.GetValueTypeProperty<SafeBCryptAlgorithmHandle, BCryptNative.BCRYPT_KEY_LENGTHS_STRUCT>(
algorithm,
BCryptNative.ObjectPropertyName.AuthTagLength);
// BCrypt returns the tag sizes in bytes, convert them to bits for the LegalTagSizes property
LegalTagSizesValue = new KeySizes[]
{
new KeySizes(tagLengths.dwMinLength * 8, tagLengths.dwMaxLength * 8, tagLengths.dwIncrement * 8)
};
// By default, generate the maximum authentication tag length possible for this algorithm
TagSize = tagLengths.dwMaxLength * 8;
}
}
}
| |
using System;
using System.Text;
using Lucene.Net.Analysis;
using Lucene.Net.Index;
using Lucene.Net.Util;
namespace Lucene.Net.Documents
{
/*
* 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.
*/
/// <summary>
/// Describes the properties of a field.
/// </summary>
public class FieldType : IndexableFieldType
{
/// <summary>
/// Data type of the numeric value
/// @since 3.2
/// </summary>
public enum NumericType
{
/// <summary>
/// 32-bit integer numeric type </summary>
INT,
/// <summary>
/// 64-bit long numeric type </summary>
LONG,
/// <summary>
/// 32-bit float numeric type </summary>
FLOAT,
/// <summary>
/// 64-bit double numeric type </summary>
DOUBLE
}
private bool Indexed_Renamed;
private bool Stored_Renamed;
private bool Tokenized_Renamed = true;
private bool StoreTermVectors_Renamed;
private bool StoreTermVectorOffsets_Renamed;
private bool StoreTermVectorPositions_Renamed;
private bool StoreTermVectorPayloads_Renamed;
private bool OmitNorms_Renamed;
private FieldInfo.IndexOptions? _indexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
private NumericType? numericType;
private bool Frozen;
private int NumericPrecisionStep_Renamed = NumericUtils.PRECISION_STEP_DEFAULT;
private FieldInfo.DocValuesType_e? docValueType;
/// <summary>
/// Create a new mutable FieldType with all of the properties from <code>ref</code>
/// </summary>
public FieldType(FieldType @ref)
{
this.Indexed_Renamed = @ref.Indexed;
this.Stored_Renamed = @ref.Stored;
this.Tokenized_Renamed = @ref.Tokenized;
this.StoreTermVectors_Renamed = @ref.StoreTermVectors;
this.StoreTermVectorOffsets_Renamed = @ref.StoreTermVectorOffsets;
this.StoreTermVectorPositions_Renamed = @ref.StoreTermVectorPositions;
this.StoreTermVectorPayloads_Renamed = @ref.StoreTermVectorPayloads;
this.OmitNorms_Renamed = @ref.OmitNorms;
this._indexOptions = @ref.IndexOptions;
this.docValueType = @ref.DocValueType;
this.numericType = @ref.NumericTypeValue;
// Do not copy frozen!
}
/// <summary>
/// Create a new FieldType with default properties.
/// </summary>
public FieldType()
{
}
private void CheckIfFrozen()
{
if (Frozen)
{
throw new Exception("this FieldType is already frozen and cannot be changed");
}
}
/// <summary>
/// Prevents future changes. Note, it is recommended that this is called once
/// the FieldTypes's properties have been set, to prevent unintentional state
/// changes.
/// </summary>
public virtual void Freeze()
{
this.Frozen = true;
}
/// <summary>
/// Set to <code>true</code> to index (invert) this field. </summary>
/// <param name="value"> true if this field should be indexed. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #indexed() </seealso>
public bool Indexed
{
get { return this.Indexed_Renamed; }
set
{
CheckIfFrozen();
this.Indexed_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to store this field. </summary>
/// <param name="value"> true if this field should be stored. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #stored() </seealso>
public bool Stored
{
get
{
return this.Stored_Renamed;
}
set
{
CheckIfFrozen();
this.Stored_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to tokenize this field's contents via the
/// configured <seealso cref="Analyzer"/>. </summary>
/// <param name="value"> true if this field should be tokenized. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #tokenized() </seealso>
public virtual bool Tokenized
{
get
{
return this.Tokenized_Renamed;
}
set
{
CheckIfFrozen();
this.Tokenized_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> if this field's indexed form should be also stored
/// into term vectors. </summary>
/// <param name="value"> true if this field should store term vectors. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #storeTermVectors() </seealso>
public bool StoreTermVectors
{
get { return this.StoreTermVectors_Renamed; }
set
{
CheckIfFrozen();
this.StoreTermVectors_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to also store token character offsets into the term
/// vector for this field. </summary>
/// <param name="value"> true if this field should store term vector offsets. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #storeTermVectorOffsets() </seealso>
public virtual bool StoreTermVectorOffsets
{
get
{
return this.StoreTermVectorOffsets_Renamed;
}
set
{
CheckIfFrozen();
this.StoreTermVectorOffsets_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to also store token positions into the term
/// vector for this field. </summary>
/// <param name="value"> true if this field should store term vector positions. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #storeTermVectorPositions() </seealso>
public virtual bool StoreTermVectorPositions
{
get
{
return this.StoreTermVectorPositions_Renamed;
}
set
{
CheckIfFrozen();
this.StoreTermVectorPositions_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to also store token payloads into the term
/// vector for this field. </summary>
/// <param name="value"> true if this field should store term vector payloads. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #storeTermVectorPayloads() </seealso>
public virtual bool StoreTermVectorPayloads
{
get
{
return this.StoreTermVectorPayloads_Renamed;
}
set
{
CheckIfFrozen();
this.StoreTermVectorPayloads_Renamed = value;
}
}
/// <summary>
/// Set to <code>true</code> to omit normalization values for the field. </summary>
/// <param name="value"> true if this field should omit norms. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #omitNorms() </seealso>
public bool OmitNorms
{
get { return this.OmitNorms_Renamed; }
set
{
CheckIfFrozen();
this.OmitNorms_Renamed = value;
}
}
/// <summary>
/// Sets the indexing options for the field: </summary>
/// <param name="value"> indexing options </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #indexOptions() </seealso>
public virtual FieldInfo.IndexOptions? IndexOptions
{
get
{
return this._indexOptions;
}
set
{
CheckIfFrozen();
this._indexOptions = value;
}
}
/// <summary>
/// Specifies the field's numeric type. </summary>
/// <param name="type"> numeric type, or null if the field has no numeric type. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #numericType() </seealso>
public virtual NumericType? NumericTypeValue
{
get
{
return this.numericType;
}
set
{
CheckIfFrozen();
numericType = value;
}
}
/// <summary>
/// Sets the numeric precision step for the field. </summary>
/// <param name="precisionStep"> numeric precision step for the field </param>
/// <exception cref="ArgumentException"> if precisionStep is less than 1. </exception>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #numericPrecisionStep() </seealso>
public virtual int NumericPrecisionStep
{
set
{
CheckIfFrozen();
if (value < 1)
{
throw new System.ArgumentException("precisionStep must be >= 1 (got " + value + ")");
}
this.NumericPrecisionStep_Renamed = value;
}
get
{
return NumericPrecisionStep_Renamed;
}
}
/// <summary>
/// Prints a Field for human consumption. </summary>
public override sealed string ToString()
{
var result = new StringBuilder();
if (Stored)
{
result.Append("stored");
}
if (Indexed)
{
if (result.Length > 0)
{
result.Append(",");
}
result.Append("indexed");
if (Tokenized)
{
result.Append(",tokenized");
}
if (StoreTermVectors)
{
result.Append(",termVector");
}
if (StoreTermVectorOffsets)
{
result.Append(",termVectorOffsets");
}
if (StoreTermVectorPositions)
{
result.Append(",termVectorPosition");
if (StoreTermVectorPayloads)
{
result.Append(",termVectorPayloads");
}
}
if (OmitNorms)
{
result.Append(",omitNorms");
}
if (_indexOptions != FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS)
{
result.Append(",indexOptions=");
result.Append(_indexOptions);
}
if (numericType != null)
{
result.Append(",numericType=");
result.Append(numericType);
result.Append(",numericPrecisionStep=");
result.Append(NumericPrecisionStep_Renamed);
}
}
if (docValueType != null)
{
if (result.Length > 0)
{
result.Append(",");
}
result.Append("docValueType=");
result.Append(docValueType);
}
return result.ToString();
}
/// <summary>
/// {@inheritDoc}
/// <p>
/// The default is <code>null</code> (no docValues) </summary>
/// <seealso cref= #setDocValueType(Lucene.Net.Index.FieldInfo.DocValuesType) </seealso>
/*public override DocValuesType DocValueType()
{
return DocValueType_Renamed;
}*/
/// <summary>
/// Set's the field's DocValuesType </summary>
/// <param name="type"> DocValues type, or null if no DocValues should be stored. </param>
/// <exception cref="InvalidOperationException"> if this FieldType is frozen against
/// future modifications. </exception>
/// <seealso cref= #docValueType() </seealso>
public FieldInfo.DocValuesType_e? DocValueType
{
get
{
return docValueType;
}
set
{
CheckIfFrozen();
docValueType = value;
}
}
}
}
| |
/*
Copyright [2016] [Arsene Tochemey GANDOTE]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using DotNetFreeSwitch.Commands;
using DotNetFreeSwitch.Common;
using DotNetFreeSwitch.Events;
using DotNetFreeSwitch.Messages;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using NLog;
namespace DotNetFreeSwitch.Handlers.inbound
{
public abstract class InboundSession : IInboundListener
{
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
protected IChannel Channel;
protected InboundCall InboundCall;
/// <summary>
/// This property holds any additional data that it is required by the InboundSession to run smoothly
/// </summary>
public Dictionary<object, object> Meta = new Dictionary<object, object>();
public async Task OnConnected(InboundCall connectedInfo,
IChannel channel)
{
InboundCall = connectedInfo;
Channel = channel;
await ResumeAsync();
await MyEventsAsync();
await DivertEventsAsync(true);
await PreHandleAsync();
await AnswerAsync();
await HandleAsync();
}
public Task OnDisconnectNotice(Message message,
EndPoint channelEndPoint)
{
_logger.Debug("received disconnection message : {0}",
message);
_logger.Warn("channel {0} disconnected",
channelEndPoint);
return Task.CompletedTask;
}
public async Task OnError(Exception exception)
{
switch (exception)
{
case DecoderException _:
_logger.Warn($"Encountered an issue during encoding: {exception}. shutting down...");
await Channel.CloseAsync();
return;
case SocketException _:
_logger.Warn($"Encountered an issue on the channel: {exception}. shutting down...");
await Channel.CloseAsync();
return;
default:
_logger.Error($"Encountered an issue : {exception}");
break;
}
}
public void OnEventReceived(Message message)
{
var eslEvent = new FsEvent(message);
var eventName = eslEvent.EventName;
var eventType = EnumExtensions.Parse<EventType>(eventName);
switch (eventType)
{
case EventType.BACKGROUND_JOB:
var backgroundJob = new BackgroundJob(message);
eslEvent = backgroundJob;
break;
case EventType.CALL_UPDATE:
var callUpdate = new CallUpdate(message);
eslEvent = callUpdate;
break;
case EventType.CHANNEL_BRIDGE:
var channelBridge = new ChannelBridge(message);
eslEvent = channelBridge;
break;
case EventType.CHANNEL_HANGUP:
case EventType.CHANNEL_HANGUP_COMPLETE:
var channelHangup = new ChannelHangup(message);
eslEvent = channelHangup;
break;
case EventType.CHANNEL_PROGRESS:
var channelProgress = new ChannelProgress(message);
eslEvent = channelProgress;
break;
case EventType.CHANNEL_PROGRESS_MEDIA:
var channelProgressMedia = new ChannelProgressMedia(message);
eslEvent = channelProgressMedia;
break;
case EventType.CHANNEL_EXECUTE:
var channelExecute = new ChannelExecute(message);
eslEvent = channelExecute;
break;
case EventType.CHANNEL_EXECUTE_COMPLETE:
var channelExecuteComplete = new ChannelExecuteComplete(message);
eslEvent = channelExecuteComplete;
break;
case EventType.CHANNEL_UNBRIDGE:
var channelUnbridge = new ChannelUnbridge(message);
eslEvent = channelUnbridge;
break;
case EventType.SESSION_HEARTBEAT:
var sessionHeartbeat = new SessionHeartbeat(message);
eslEvent = sessionHeartbeat;
break;
case EventType.DTMF:
var dtmf = new Dtmf(message);
eslEvent = dtmf;
break;
case EventType.RECORD_STOP:
var recordStop = new RecordStop(message);
eslEvent = recordStop;
break;
case EventType.CUSTOM:
var custom = new Custom(message);
eslEvent = custom;
break;
case EventType.CHANNEL_STATE:
var channelState = new ChannelStateEvent(message);
eslEvent = channelState;
break;
case EventType.CHANNEL_ANSWER:
eslEvent = new FsEvent(message);
break;
case EventType.CHANNEL_ORIGINATE:
eslEvent = new FsEvent(message);
break;
case EventType.CHANNEL_PARK:
var channelPark = new ChannelPark(message);
eslEvent = channelPark;
break;
case EventType.CHANNEL_UNPARK:
eslEvent = new FsEvent(message);
break;
default:
OnUnhandledEvents(new FsEvent(message));
break;
}
HandleEvents(eslEvent,
eventType);
}
public async Task OnRudeRejection()
{
if (Channel != null) await Channel.CloseAsync();
}
public async Task AnswerAsync()
{
await ExecuteAsync("answer",
true);
}
public async Task BindDigitActionAsync(string command,
bool eventLock = true)
{
await ExecuteAsync("bind_digit_action",
command,
eventLock);
}
public async Task BridgeAsync(string bridgeText,
bool eventLock = false)
{
await ExecuteAsync("bridge",
bridgeText,
eventLock);
}
public bool CanHandleEvent(FsEvent @event)
{
return @event.UniqueId == InboundCall.UniqueId && @event.CallerGuid == InboundCall.CallerGuid;
}
public bool IsChannelReady()
{
return Channel != null && Channel.Active;
}
public async Task DivertEventsAsync(bool flag)
{
var command = new DivertEventsCommand(flag);
await SendCommandAsync(command);
}
public async Task<CommandReply> ExecuteAsync(string application,
string arguments,
bool eventLock)
{
var command = new SendMsgCommand(InboundCall.CallerGuid,
SendMsgCommand.CallCommand,
application,
arguments,
eventLock);
return await SendCommandAsync(command);
}
public async Task<CommandReply> ExecuteAsync(string application,
string arguments,
int loop,
bool eventLock)
{
var command = new SendMsgCommand(InboundCall.CallerGuid,
SendMsgCommand.CallCommand,
application,
arguments,
eventLock,
loop);
return await SendCommandAsync(command);
}
public async Task<CommandReply> ExecuteAsync(string application)
{
return await ExecuteAsync(application,
string.Empty,
false);
}
public async Task<CommandReply> ExecuteAsync(string application,
bool eventLock)
{
return await ExecuteAsync(application,
string.Empty,
eventLock);
}
protected abstract Task HandleAsync();
protected abstract Task HandleEvents(FsEvent @event,
EventType eventType);
public async Task LingerAsync()
{
await SendCommandAsync(new LingerCommand());
}
public async Task MyEventsAsync()
{
await SendCommandAsync(new MyEventsCommand(InboundCall.CallerGuid));
}
protected virtual Task OnUnhandledEvents(FsEvent fsEvent)
{
_logger.Debug("received unhandled freeSwitch event {0}",
fsEvent);
return Task.CompletedTask;
}
protected async Task PlayAsync(string audioFile,
bool eventLock = false)
{
await ExecuteAsync("playback",
audioFile,
eventLock);
}
public async Task PreAnswerAsync()
{
await ExecuteAsync("pre_answer");
}
protected abstract Task PreHandleAsync();
public async Task ResumeAsync()
{
await SendCommandAsync(new ResumeCommand());
}
public async Task RingReadyAsync()
{
await ExecuteAsync("ring_ready",
true);
}
public async Task RingReadyAsync(bool eventLock)
{
await ExecuteAsync("ring_ready",
eventLock);
}
public async Task SayAsync(string language,
SayTypes type,
SayMethods method,
SayGenders gender,
string text,
int loop,
bool eventLock)
{
await ExecuteAsync("say",
language + " " + type + " " + method.ToString().Replace("_",
"/") + " " + gender + " " + text,
loop,
eventLock);
}
public async Task<ApiResponse> SendApiAsync(ApiCommand apiCommand)
{
if (!IsChannelReady()) return null;
var handler = (InboundSessionHandler) Channel.Pipeline.Last();
var response = await handler.SendApiAsync(apiCommand,
Channel);
return response;
}
public async Task<Guid> SendBgApiAsync(BgApiCommand bgApiCommand)
{
if (!IsChannelReady()) return Guid.Empty;
var handler = (InboundSessionHandler) Channel.Pipeline.Last();
return await handler.SendBgApiAsync(bgApiCommand,
Channel);
}
public async Task<CommandReply> SendCommandAsync(BaseCommand command)
{
if (!IsChannelReady()) return null;
var handler = (InboundSessionHandler) Channel.Pipeline.Last();
var reply = await handler.SendCommandAsync(command,
Channel);
return reply;
}
public async Task SetAsync(string variableName,
string variableValue)
{
await ExecuteAsync("set",
variableName + "=" + variableValue,
false);
}
public async Task SetAsync(string variableName,
string variableValue,
bool eventLock)
{
await ExecuteAsync("set",
variableName + "=" + variableValue,
eventLock);
}
public async Task SleepAsync(int millisecond,
bool eventLock = false)
{
await ExecuteAsync("sleep",
Convert.ToString(millisecond),
eventLock);
}
public async Task SpeakAsync(string engine,
string voice,
string text,
string timerName = null,
int loop = 1,
bool eventLock = false)
{
await ExecuteAsync("speak",
engine + "|" + voice + "|" + text + (!string.IsNullOrEmpty(timerName) ? "|" + timerName : ""),
loop,
eventLock);
}
public async Task SpeakAsync(string engine,
int loop = 1,
bool eventLock = false)
{
await ExecuteAsync("speak",
engine,
loop,
eventLock);
}
public async Task StartDtmfAsync(bool eventLock)
{
await ExecuteAsync("start_dtmf",
eventLock);
}
public async Task StopAsync(bool eventLock = false)
{
await ExecuteAsync("stop_dtmf",
eventLock);
}
public async Task StopDtmfAsync(bool eventLock = false)
{
await ExecuteAsync("stop_dtmf",
eventLock);
}
public async Task UnsetAsync(string variableName,
bool eventLock)
{
await ExecuteAsync("unset",
variableName,
eventLock);
}
public async Task UnsetAsync(string variableName)
{
await ExecuteAsync("unset",
variableName,
false);
}
}
}
| |
//
// Term.cs
//
// Author:
// Gabriel Burt <gabriel.burt@gmail.com>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2007-2009 Novell, Inc.
// Copyright (C) 2007 Gabriel Burt
// Copyright (C) 2007-2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Mono.Unix;
using Gtk;
using Gdk;
using Hyena;
using FSpot.Core;
namespace FSpot {
public abstract class Term {
private ArrayList sub_terms = new ArrayList ();
private Term parent = null;
protected bool is_negated = false;
protected Tag tag = null;
public Term (Term parent, Literal after)
{
this.parent = parent;
if (parent != null) {
if (after == null)
parent.Add (this);
else
parent.SubTerms.Insert (parent.SubTerms.IndexOf (after) + 1, this);
}
}
/** Properties **/
public bool HasMultiple {
get {
return (SubTerms.Count > 1);
}
}
public ArrayList SubTerms {
get {
return sub_terms;
}
}
public Term Last {
get {
// Return the last Literal in this term
if (SubTerms.Count > 0)
return SubTerms[SubTerms.Count - 1] as Term;
else
return null;
}
}
public int Count {
get {
return SubTerms.Count;
}
}
public Term Parent {
get { return parent; }
set {
if (parent == value)
return;
// If our parent was already set, remove ourself from it
if (parent != null)
parent.Remove(this);
// Add ourself to our new parent
parent = value;
parent.Add(this);
}
}
public virtual bool IsNegated {
get { return is_negated; }
set {
if (is_negated != value)
Invert(false);
is_negated = value;
}
}
/** Methods **/
public void Add (Term term)
{
SubTerms.Add (term);
}
public void Remove (Term term)
{
SubTerms.Remove (term);
// Remove ourselves if we're now empty
if (SubTerms.Count == 0)
if (Parent != null)
Parent.Remove (this);
}
public void CopyAndInvertSubTermsFrom (Term term, bool recurse)
{
is_negated = true;
ArrayList termsToMove = new ArrayList(term.SubTerms);
foreach (Term subterm in termsToMove) {
if (recurse)
subterm.Invert(true).Parent = this;
else
subterm.Parent = this;
}
}
public ArrayList FindByTag (Tag t)
{
return FindByTag (t, true);
}
public ArrayList FindByTag (Tag t, bool recursive)
{
ArrayList results = new ArrayList ();
if (tag != null && tag == t)
results.Add (this);
if (recursive)
foreach (Term term in SubTerms)
results.AddRange (term.FindByTag (t, true));
else
foreach (Term term in SubTerms) {
foreach (Term literal in SubTerms) {
if (literal.tag != null && literal.tag == t) {
results.Add (literal);
}
}
if (term.tag != null && term.tag == t) {
results.Add (term);
}
}
return results;
}
public ArrayList LiteralParents ()
{
ArrayList results = new ArrayList ();
bool meme = false;
foreach (Term term in SubTerms) {
if (term is Literal)
meme = true;
results.AddRange (term.LiteralParents ());
}
if (meme)
results.Add (this);
return results;
}
public bool TagIncluded(Tag t)
{
ArrayList parents = LiteralParents ();
if (parents.Count == 0)
return false;
foreach (Term term in parents) {
bool termHasTag = false;
bool onlyTerm = true;
foreach (Term literal in term.SubTerms) {
if (literal.tag != null) {
if (literal.tag == t) {
termHasTag = true;
} else {
onlyTerm = false;
}
}
}
if (termHasTag && onlyTerm)
return true;
}
return false;
}
public bool TagRequired(Tag t)
{
int count, grouped_with;
return TagRequired(t, out count, out grouped_with);
}
public bool TagRequired(Tag t, out int num_terms, out int grouped_with)
{
ArrayList parents = LiteralParents ();
num_terms = 0;
grouped_with = 100;
int min_grouped_with = 100;
if (parents.Count == 0)
return false;
foreach (Term term in parents) {
bool termHasTag = false;
// Don't count it as required if it's the only subterm..though it is..
// it is more clearly identified as Included at that point.
if (term.Count > 1) {
foreach (Term literal in term.SubTerms) {
if (literal.tag != null) {
if (literal.tag == t) {
num_terms++;
termHasTag = true;
grouped_with = term.SubTerms.Count;
break;
}
}
}
}
if (grouped_with < min_grouped_with)
min_grouped_with = grouped_with;
if (!termHasTag)
return false;
}
grouped_with = min_grouped_with;
return true;
}
public abstract Term Invert(bool recurse);
// Recursively generate the SQL condition clause that this
// term represents.
public virtual string SqlCondition ()
{
StringBuilder condition = new StringBuilder ("(");
for (int i = 0; i < SubTerms.Count; i++) {
Term term = SubTerms[i] as Term;
condition.Append (term.SqlCondition ());
if (i != SubTerms.Count - 1)
condition.Append (SQLOperator ());
}
condition.Append(")");
return condition.ToString ();
}
public virtual Gtk.Widget SeparatorWidget ()
{
return null;
}
public virtual string SQLOperator ()
{
return String.Empty;
}
protected static Hashtable op_term_lookup = new Hashtable();
public static Term TermFromOperator (string op, Term parent, Literal after)
{
//Console.WriteLine ("finding type for operator {0}", op);
//op = op.Trim ();
op = op.ToLower ();
if (AndTerm.Operators.Contains (op)) {
//Console.WriteLine ("AND!");
return new AndTerm (parent, after);
} else if (OrTerm.Operators.Contains (op)) {
//Console.WriteLine ("OR!");
return new OrTerm (parent, after);
}
Log.DebugFormat ("Do not have Term for operator {0}", op);
return null;
}
}
public class AndTerm : Term {
static ArrayList operators = new ArrayList ();
static AndTerm () {
operators.Add (Catalog.GetString (" and "));
//operators.Add (Catalog.GetString (" && "));
operators.Add (Catalog.GetString (", "));
}
public static ArrayList Operators {
get { return operators; }
}
public AndTerm (Term parent, Literal after) : base (parent, after) {}
public override Term Invert (bool recurse)
{
OrTerm newme = new OrTerm(Parent, null);
newme.CopyAndInvertSubTermsFrom(this, recurse);
if (Parent != null)
Parent.Remove(this);
return newme;
}
public override Widget SeparatorWidget ()
{
Widget sep = new Label (String.Empty);
sep.SetSizeRequest (3, 1);
sep.Show ();
return sep;
//return null;
}
public override string SqlCondition ()
{
StringBuilder condition = new StringBuilder ("(");
condition.Append (base.SqlCondition());
Tag hidden = App.Instance.Database.Tags.Hidden;
if (hidden != null) {
if (FindByTag (hidden, true).Count == 0) {
condition.Append (String.Format (
" AND id NOT IN (SELECT photo_id FROM photo_tags WHERE tag_id = {0})", hidden.Id
));
}
}
condition.Append (")");
return condition.ToString ();
}
public override string SQLOperator ()
{
return " AND ";
}
}
public class OrTerm : Term {
static ArrayList operators = new ArrayList ();
static OrTerm () {
operators.Add (Catalog.GetString (" or "));
//operators.Add (Catalog.GetString (" || "));
}
public static OrTerm FromTags(Tag [] from_tags)
{
if (from_tags == null || from_tags.Length == 0)
return null;
OrTerm or = new OrTerm(null, null);
foreach (Tag t in from_tags) {
Literal l = new Literal(t);
l.Parent = or;
}
return or;
}
public static ArrayList Operators {
get { return operators; }
}
public OrTerm (Term parent, Literal after) : base (parent, after) {}
private static string OR = Catalog.GetString ("or");
public override Term Invert (bool recurse)
{
AndTerm newme = new AndTerm(Parent, null);
newme.CopyAndInvertSubTermsFrom(this, recurse);
if (Parent != null)
Parent.Remove(this);
return newme;
}
public override Gtk.Widget SeparatorWidget ()
{
Widget label = new Label (" " + OR + " ");
label.Show ();
return label;
}
public override string SQLOperator ()
{
return " OR ";
}
}
public abstract class AbstractLiteral : Term {
public AbstractLiteral(Term parent, Literal after) : base (parent, after) {}
public override Term Invert (bool recurse)
{
is_negated = !is_negated;
return this;
}
}
// TODO rename to TagLiteral?
public class Literal : AbstractLiteral {
public Literal (Tag tag) : this (null, tag, null)
{
}
public Literal (Term parent, Tag tag, Literal after) : base (parent, after) {
this.tag = tag;
}
/** Properties **/
public static ArrayList FocusedLiterals
{
get {
return focusedLiterals;
}
set {
focusedLiterals = value;
}
}
public Tag Tag {
get {
return tag;
}
}
public override bool IsNegated {
get {
return is_negated;
}
set {
if (is_negated == value)
return;
is_negated = value;
NormalIcon = null;
NegatedIcon = null;
Update ();
if (NegatedToggled != null)
NegatedToggled (this);
}
}
private Pixbuf NegatedIcon
{
get {
if (negated_icon != null)
return negated_icon;
if (NormalIcon == null)
return null;
negated_icon = NormalIcon.Copy ();
int offset = ICON_SIZE - overlay_size;
NegatedOverlay.Composite (negated_icon, offset, 0, overlay_size, overlay_size, offset, 0, 1.0, 1.0, InterpType.Bilinear, 200);
return negated_icon;
}
set {
negated_icon = null;
}
}
public Widget Widget {
get {
if (widget != null)
return widget;
container = new EventBox ();
box = new HBox ();
handle_box = new LiteralBox ();
handle_box.BorderWidth = 1;
label = new Label (System.Web.HttpUtility.HtmlEncode (tag.Name));
label.UseMarkup = true;
image = new Gtk.Image (NormalIcon);
container.CanFocus = true;
container.KeyPressEvent += KeyHandler;
container.ButtonPressEvent += HandleButtonPress;
container.ButtonReleaseEvent += HandleButtonRelease;
container.EnterNotifyEvent += HandleMouseIn;
container.LeaveNotifyEvent += HandleMouseOut;
//new PopupManager (new LiteralPopup (container, this));
// Setup this widget as a drag source (so tags can be moved after being placed)
container.DragDataGet += HandleDragDataGet;
container.DragBegin += HandleDragBegin;
container.DragEnd += HandleDragEnd;
Gtk.Drag.SourceSet (container, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask,
tag_target_table, DragAction.Copy | DragAction.Move);
// Setup this widget as a drag destination (so tags can be added to our parent's Term)
container.DragDataReceived += HandleDragDataReceived;
container.DragMotion += HandleDragMotion;
container.DragLeave += HandleDragLeave;
Gtk.Drag.DestSet (container, DestDefaults.All, tag_dest_target_table,
DragAction.Copy | DragAction.Move );
container.TooltipText = tag.Name;
label.Show ();
image.Show ();
if (tag.Icon == null) {
handle_box.Add (label);
} else {
handle_box.Add (image);
}
handle_box.Show ();
box.Add (handle_box);
box.Show ();
container.Add (box);
widget = container;
return widget;
}
}
private Pixbuf NormalIcon
{
get {
if (normal_icon != null)
return normal_icon;
Pixbuf scaled = null;
scaled = tag.Icon;
for (Category category = tag.Category; category != null && scaled == null; category = category.Category)
scaled = category.Icon;
if (scaled == null)
return null;
if (scaled.Width != ICON_SIZE) {
scaled = scaled.ScaleSimple (ICON_SIZE, ICON_SIZE, InterpType.Bilinear);
}
normal_icon = scaled;
return normal_icon;
}
set {
normal_icon = null;
}
}
/** Methods **/
public void Update ()
{
// Clear out the old icons
normal_icon = null;
negated_icon = null;
if (IsNegated) {
widget.TooltipText = String.Format (Catalog.GetString ("Not {0}"), tag.Name);
label.Text = "<s>" + System.Web.HttpUtility.HtmlEncode (tag.Name) + "</s>";
image.Pixbuf = NegatedIcon;
} else {
widget.TooltipText = tag.Name;
label.Text = System.Web.HttpUtility.HtmlEncode (tag.Name);
image.Pixbuf = NormalIcon;
}
label.UseMarkup = true;
// Show the icon unless it's null
if (tag.Icon == null && container.Children [0] == image) {
container.Remove (image);
container.Add (label);
} else if (tag.Icon != null && container.Children [0] == label) {
container.Remove (label);
container.Add (image);
}
if (isHoveredOver && image.Pixbuf != null ) {
// Brighten the image slightly
Pixbuf brightened = image.Pixbuf.Copy ();
image.Pixbuf.SaturateAndPixelate (brightened, 1.85f, false);
//Pixbuf brightened = PixbufUtils.Glow (image.Pixbuf, .6f);
image.Pixbuf = brightened;
}
}
public void RemoveSelf ()
{
if (Removing != null)
Removing (this);
if (Parent != null)
Parent.Remove (this);
if (Removed != null)
Removed (this);
}
public override string SqlCondition ()
{
StringBuilder ids = new StringBuilder (tag.Id.ToString ());
if (tag is Category) {
List<Tag> tags = new List<Tag> ();
(tag as Category).AddDescendentsTo (tags);
for (int i = 0; i < tags.Count; i++)
ids.Append (", " + (tags [i] as Tag).Id.ToString ());
}
return String.Format (
"id {0}IN (SELECT photo_id FROM photo_tags WHERE tag_id IN ({1}))",
(IsNegated ? "NOT " : String.Empty), ids.ToString ());
}
public override Gtk.Widget SeparatorWidget ()
{
return new Label ("ERR");
}
private static Pixbuf NegatedOverlay
{
get {
if (negated_overlay == null) {
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly ();
negated_overlay = new Pixbuf (assembly.GetManifestResourceStream ("f-spot-not.png"));
negated_overlay = negated_overlay.ScaleSimple (overlay_size, overlay_size, InterpType.Bilinear);
}
return negated_overlay;
}
}
public static void RemoveFocusedLiterals ()
{
if (focusedLiterals != null)
foreach (Literal literal in focusedLiterals)
literal.RemoveSelf ();
}
/** Handlers **/
private void KeyHandler (object o, KeyPressEventArgs args)
{
args.RetVal = false;
switch (args.Event.Key) {
case Gdk.Key.Delete:
RemoveFocusedLiterals ();
args.RetVal = true;
return;
}
}
private void HandleButtonPress (object o, ButtonPressEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
if (args.Event.Button == 1)
IsNegated = !IsNegated;
else
args.RetVal = false;
return;
case EventType.ButtonPress:
Widget.GrabFocus ();
if (args.Event.Button == 1) {
// TODO allow multiple selection of literals so they can be deleted, modified all at once
//if ((args.Event.State & ModifierType.ControlMask) != 0) {
//}
}
else if (args.Event.Button == 3)
{
LiteralPopup popup = new LiteralPopup ();
popup.Activate (args.Event, this);
}
return;
default:
args.RetVal = false;
return;
}
}
private void HandleButtonRelease (object o, ButtonReleaseEventArgs args)
{
args.RetVal = true;
switch (args.Event.Type) {
case EventType.TwoButtonPress:
args.RetVal = false;
return;
case EventType.ButtonPress:
if (args.Event.Button == 1) {
}
return;
default:
args.RetVal = false;
return;
}
}
private void HandleMouseIn (object o, EnterNotifyEventArgs args)
{
isHoveredOver = true;
Update ();
}
private void HandleMouseOut (object o, LeaveNotifyEventArgs args)
{
isHoveredOver = false;
Update ();
}
void HandleDragDataGet (object sender, DragDataGetArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info || args.Info == DragDropTargets.TagQueryEntry.Info) {
// FIXME: do really write data
Byte [] data = Encoding.UTF8.GetBytes (String.Empty);
Atom [] targets = args.Context.Targets;
args.SelectionData.Set (targets[0], 8, data, data.Length);
return;
}
// Drop cancelled
args.RetVal = false;
foreach (Widget w in hiddenWidgets)
w.Visible = true;
focusedLiterals = null;
}
void HandleDragBegin (object sender, DragBeginArgs args)
{
Gtk.Drag.SetIconPixbuf (args.Context, image.Pixbuf, 0, 0);
focusedLiterals.Add (this);
// Hide the tag and any separators that only exist because of it
container.Visible = false;
hiddenWidgets.Add (container);
foreach (Widget w in LogicWidget.Box.HangersOn (this)) {
hiddenWidgets.Add (w);
w.Visible = false;
}
}
void HandleDragEnd (object sender, DragEndArgs args)
{
// Remove any literals still marked as focused, because
// the user is throwing them away.
RemoveFocusedLiterals ();
focusedLiterals = new ArrayList();
args.RetVal = true;
}
private void HandleDragDataReceived (object o, DragDataReceivedArgs args)
{
args.RetVal = true;
if (args.Info == DragDropTargets.TagListEntry.Info) {
if (TagsAdded != null)
TagsAdded (args.SelectionData.GetTagsData (), Parent, this);
return;
}
if (args.Info == DragDropTargets.TagQueryEntry.Info) {
if (! focusedLiterals.Contains(this))
if (LiteralsMoved != null)
LiteralsMoved (focusedLiterals, Parent, this);
// Unmark the literals as focused so they don't get nixed
focusedLiterals = null;
}
}
private bool preview = false;
private Gtk.Widget preview_widget;
private void HandleDragMotion (object o, DragMotionArgs args)
{
if (!preview) {
if (preview_widget == null) {
preview_widget = new Gtk.Label (" | ");
box.Add (preview_widget);
}
preview_widget.Show ();
}
}
private void HandleDragLeave (object o, EventArgs args)
{
preview = false;
preview_widget.Hide ();
}
public void HandleToggleNegatedCommand (object o, EventArgs args)
{
IsNegated = !IsNegated;
}
public void HandleRemoveCommand (object o, EventArgs args)
{
RemoveSelf ();
}
public void HandleAttachTagCommand (Tag t)
{
if (AttachTag != null)
AttachTag (t, Parent, this);
}
public void HandleRequireTag (object sender, EventArgs args)
{
if (RequireTag != null)
RequireTag (new Tag [] {this.Tag});
}
public void HandleUnRequireTag (object sender, EventArgs args)
{
if (UnRequireTag != null)
UnRequireTag (new Tag [] {this.Tag});
}
private const int ICON_SIZE = 24;
private const int overlay_size = (int) (.40 * ICON_SIZE);
private static TargetEntry [] tag_target_table =
new TargetEntry [] { DragDropTargets.TagQueryEntry };
private static TargetEntry [] tag_dest_target_table =
new TargetEntry [] {
DragDropTargets.TagListEntry,
DragDropTargets.TagQueryEntry
};
private static ArrayList focusedLiterals = new ArrayList();
private static ArrayList hiddenWidgets = new ArrayList();
private Gtk.Container container;
private LiteralBox handle_box;
private Gtk.Box box;
private Gtk.Image image;
private Gtk.Label label;
private Pixbuf normal_icon;
//private EventBox widget;
private Widget widget;
private Pixbuf negated_icon;
private static Pixbuf negated_overlay;
private bool isHoveredOver = false;
public delegate void NegatedToggleHandler (Literal group);
public event NegatedToggleHandler NegatedToggled;
public delegate void RemovingHandler (Literal group);
public event RemovingHandler Removing;
public delegate void RemovedHandler (Literal group);
public event RemovedHandler Removed;
public delegate void TagsAddedHandler (Tag[] tags, Term parent, Literal after);
public event TagsAddedHandler TagsAdded;
public delegate void AttachTagHandler (Tag tag, Term parent, Literal after);
public event AttachTagHandler AttachTag;
public delegate void TagRequiredHandler (Tag [] tags);
public event TagRequiredHandler RequireTag;
public delegate void TagUnRequiredHandler (Tag [] tags);
public event TagUnRequiredHandler UnRequireTag;
public delegate void LiteralsMovedHandler (ArrayList literals, Term parent, Literal after);
public event LiteralsMovedHandler LiteralsMoved;
}
public class TextLiteral : AbstractLiteral {
private string text;
public TextLiteral (Term parent, string text) : base (parent, null)
{
this.text = text;
}
public override string SqlCondition ()
{
return String.Format (
"id {0}IN (SELECT id FROM photos WHERE base_uri LIKE '%{1}%' OR filename LIKE '%{1}%' OR description LIKE '%{1}%')",
(IsNegated ? "NOT " : ""), EscapeQuotes(text)
);
}
protected static string EscapeQuotes (string v)
{
return v == null ? String.Empty : v.Replace("'", "''");
}
}
}
| |
//
// ContextBackendHandler.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
// Alex Corrado <corrado@xamarin.com>
//
// Copyright (c) 2011 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using MonoMac.AppKit;
using Xwt.Drawing;
using MonoMac.Foundation;
using MonoMac.CoreGraphics;
using System.Drawing;
using System.Collections.Generic;
namespace Xwt.Mac
{
class CGContextBackend {
public CGContext Context;
public SizeF Size;
public CGAffineTransform? InverseViewTransform;
public Stack<ContextStatus> StatusStack = new Stack<ContextStatus> ();
public ContextStatus CurrentStatus = new ContextStatus ();
public double ScaleFactor = 1;
}
class ContextStatus
{
public object Pattern;
}
public class MacContextBackendHandler: ContextBackendHandler
{
const double degrees = System.Math.PI / 180d;
public override double GetScaleFactor (object backend)
{
var ct = (CGContextBackend) backend;
return ct.ScaleFactor;
}
public override void Save (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.SaveState ();
ct.StatusStack.Push (ct.CurrentStatus);
var newStatus = new ContextStatus ();
newStatus.Pattern = ct.CurrentStatus.Pattern;
ct.CurrentStatus = newStatus;
}
public override void Restore (object backend)
{
var ct = (CGContextBackend) backend;
ct.Context.RestoreState ();
ct.CurrentStatus = ct.StatusStack.Pop ();
}
public override void SetGlobalAlpha (object backend, double alpha)
{
((CGContextBackend)backend).Context.SetAlpha ((float)alpha);
}
public override void Arc (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), false);
}
public override void ArcNegative (object backend, double xc, double yc, double radius, double angle1, double angle2)
{
CGContext ctx = ((CGContextBackend)backend).Context;
ctx.AddArc ((float)xc, (float)yc, (float)radius, (float)(angle1 * degrees), (float)(angle2 * degrees), true);
}
public override void Clip (object backend)
{
((CGContextBackend)backend).Context.Clip ();
}
public override void ClipPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.Clip ();
ctx.AddPath (oldPath);
}
}
public override void ClosePath (object backend)
{
((CGContextBackend)backend).Context.ClosePath ();
}
public override void CurveTo (object backend, double x1, double y1, double x2, double y2, double x3, double y3)
{
((CGContextBackend)backend).Context.AddCurveToPoint ((float)x1, (float)y1, (float)x2, (float)y2, (float)x3, (float)y3);
}
public override void Fill (object backend)
{
CGContextBackend gc = (CGContextBackend)backend;
CGContext ctx = gc.Context;
SetupContextForDrawing (ctx);
if (gc.CurrentStatus.Pattern is GradientInfo) {
MacGradientBackendHandler.Draw (ctx, ((GradientInfo)gc.CurrentStatus.Pattern));
}
else if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
SetupPattern (gc);
ctx.DrawPath (CGPathDrawingMode.Fill);
}
else {
ctx.DrawPath (CGPathDrawingMode.Fill);
}
}
public override void FillPreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
using (CGPath oldPath = ctx.CopyPath ()) {
Fill (backend);
ctx.AddPath (oldPath);
}
}
public override void LineTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.AddLineToPoint ((float)x, (float)y);
}
public override void MoveTo (object backend, double x, double y)
{
((CGContextBackend)backend).Context.MoveTo ((float)x, (float)y);
}
public override void NewPath (object backend)
{
((CGContextBackend)backend).Context.BeginPath ();
}
public override void Rectangle (object backend, double x, double y, double width, double height)
{
((CGContextBackend)backend).Context.AddRect (new RectangleF ((float)x, (float)y, (float)width, (float)height));
}
public override void RelCurveTo (object backend, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3)
{
CGContext ctx = ((CGContextBackend)backend).Context;
PointF p = ctx.GetPathCurrentPoint ();
ctx.AddCurveToPoint ((float)(p.X + dx1), (float)(p.Y + dy1), (float)(p.X + dx2), (float)(p.Y + dy2), (float)(p.X + dx3), (float)(p.Y + dy3));
}
public override void RelLineTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
PointF p = ctx.GetPathCurrentPoint ();
ctx.AddLineToPoint ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void RelMoveTo (object backend, double dx, double dy)
{
CGContext ctx = ((CGContextBackend)backend).Context;
PointF p = ctx.GetPathCurrentPoint ();
ctx.MoveTo ((float)(p.X + dx), (float)(p.Y + dy));
}
public override void Stroke (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
ctx.DrawPath (CGPathDrawingMode.Stroke);
}
public override void StrokePreserve (object backend)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
using (CGPath oldPath = ctx.CopyPath ()) {
ctx.DrawPath (CGPathDrawingMode.Stroke);
ctx.AddPath (oldPath);
}
}
public override void SetColor (object backend, Xwt.Drawing.Color color)
{
CGContextBackend gc = (CGContextBackend)backend;
gc.CurrentStatus.Pattern = null;
CGContext ctx = gc.Context;
ctx.SetFillColorSpace (Util.DeviceRGBColorSpace);
ctx.SetStrokeColorSpace (Util.DeviceRGBColorSpace);
ctx.SetFillColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
ctx.SetStrokeColor ((float)color.Red, (float)color.Green, (float)color.Blue, (float)color.Alpha);
}
public override void SetLineWidth (object backend, double width)
{
((CGContextBackend)backend).Context.SetLineWidth ((float)width);
}
public override void SetLineDash (object backend, double offset, params double[] pattern)
{
float[] array = new float[pattern.Length];
for (int n=0; n<pattern.Length; n++)
array [n] = (float) pattern[n];
if (array.Length == 0)
array = new float [] { 1 };
((CGContextBackend)backend).Context.SetLineDash ((float)offset, array);
}
public override void SetPattern (object backend, object p)
{
CGContextBackend gc = (CGContextBackend)backend;
gc.CurrentStatus.Pattern = p;
}
void SetupPattern (CGContextBackend gc)
{
gc.Context.SetPatternPhase (new SizeF (0, 0));
if (gc.CurrentStatus.Pattern is GradientInfo)
return;
if (gc.CurrentStatus.Pattern is ImagePatternInfo) {
var pi = (ImagePatternInfo) gc.CurrentStatus.Pattern;
RectangleF bounds = new RectangleF (PointF.Empty, new SizeF (pi.Image.Size.Width, pi.Image.Size.Height));
var t = CGAffineTransform.Multiply (CGAffineTransform.MakeScale (1f, -1f), gc.Context.GetCTM ());
CGPattern pattern;
if (pi.Image is CustomImage) {
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height, CGPatternTiling.ConstantSpacing, true, c => {
c.TranslateCTM (0, bounds.Height);
c.ScaleCTM (1f, -1f);
((CustomImage)pi.Image).DrawInContext (c);
});
} else {
RectangleF empty = RectangleF.Empty;
CGImage cgimg = ((NSImage)pi.Image).AsCGImage (ref empty, null, null);
pattern = new CGPattern (bounds, t, bounds.Width, bounds.Height,
CGPatternTiling.ConstantSpacing, true, c => c.DrawImage (bounds, cgimg));
}
CGContext ctx = gc.Context;
float[] alpha = new[] { (float)pi.Alpha };
ctx.SetFillColorSpace (Util.PatternColorSpace);
ctx.SetStrokeColorSpace (Util.PatternColorSpace);
ctx.SetFillPattern (pattern, alpha);
ctx.SetStrokePattern (pattern, alpha);
}
}
public override void DrawTextLayout (object backend, TextLayout layout, double x, double y)
{
CGContext ctx = ((CGContextBackend)backend).Context;
SetupContextForDrawing (ctx);
MacTextLayoutBackendHandler.Draw (ctx, Toolkit.GetBackend (layout), x, y);
}
public override void DrawImage (object backend, ImageDescription img, double x, double y)
{
var srcRect = new Rectangle (Point.Zero, img.Size);
var destRect = new Rectangle (x, y, img.Size.Width, img.Size.Height);
DrawImage (backend, img, srcRect, destRect);
}
public override void DrawImage (object backend, ImageDescription img, Rectangle srcRect, Rectangle destRect)
{
CGContext ctx = ((CGContextBackend)backend).Context;
NSImage image = img.ToNSImage ();
ctx.SaveState ();
ctx.SetAlpha ((float)img.Alpha);
double rx = destRect.Width / srcRect.Width;
double ry = destRect.Height / srcRect.Height;
ctx.AddRect (new RectangleF ((float)destRect.X, (float)destRect.Y, (float)destRect.Width, (float)destRect.Height));
ctx.Clip ();
ctx.TranslateCTM ((float)(destRect.X - (srcRect.X * rx)), (float)(destRect.Y - (srcRect.Y * ry)));
ctx.ScaleCTM ((float)rx, (float)ry);
if (image is CustomImage) {
((CustomImage)image).DrawInContext ((CGContextBackend)backend);
} else {
RectangleF rr = new RectangleF (0, 0, (float)image.Size.Width, image.Size.Height);
ctx.ScaleCTM (1f, -1f);
ctx.DrawImage (new RectangleF (0, -image.Size.Height, image.Size.Width, image.Size.Height), image.AsCGImage (ref rr, NSGraphicsContext.CurrentContext, null));
}
ctx.RestoreState ();
}
public override void Rotate (object backend, double angle)
{
((CGContextBackend)backend).Context.RotateCTM ((float)(angle * degrees));
}
public override void Scale (object backend, double scaleX, double scaleY)
{
((CGContextBackend)backend).Context.ScaleCTM ((float)scaleX, (float)scaleY);
}
public override void Translate (object backend, double tx, double ty)
{
((CGContextBackend)backend).Context.TranslateCTM ((float)tx, (float)ty);
}
public override void ModifyCTM (object backend, Matrix m)
{
CGAffineTransform t = new CGAffineTransform ((float)m.M11, (float)m.M12,
(float)m.M21, (float)m.M22,
(float)m.OffsetX, (float)m.OffsetY);
((CGContextBackend)backend).Context.ConcatCTM (t);
}
public override Matrix GetCTM (object backend)
{
CGAffineTransform t = GetContextTransform ((CGContextBackend)backend);
Matrix ctm = new Matrix (t.xx, t.yx, t.xy, t.yy, t.x0, t.y0);
return ctm;
}
public override object CreatePath ()
{
return new CGPath ();
}
public override object CopyPath (object backend)
{
return ((CGContextBackend)backend).Context.CopyPath ();
}
public override void AppendPath (object backend, object otherBackend)
{
CGContext dest = ((CGContextBackend)backend).Context;
CGContextBackend src = otherBackend as CGContextBackend;
if (src != null) {
using (var path = src.Context.CopyPath ())
dest.AddPath (path);
} else {
dest.AddPath ((CGPath)otherBackend);
}
}
public override bool IsPointInFill (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new PointF ((float)x, (float)y), CGPathDrawingMode.Fill);
}
public override bool IsPointInStroke (object backend, double x, double y)
{
return ((CGContextBackend)backend).Context.PathContainsPoint (new PointF ((float)x, (float)y), CGPathDrawingMode.Stroke);
}
public override void Dispose (object backend)
{
((CGContextBackend)backend).Context.Dispose ();
}
static CGAffineTransform GetContextTransform (CGContextBackend gc)
{
CGAffineTransform t = gc.Context.GetCTM ();
// The CTM returned above actually includes the full view transform.
// We only want the transform that is applied to the context, so concat
// the inverse of the view transform to nullify that part.
if (gc.InverseViewTransform.HasValue)
t.Multiply (gc.InverseViewTransform.Value);
return t;
}
static void SetupContextForDrawing (CGContext ctx)
{
if (ctx.IsPathEmpty ())
return;
// setup pattern drawing to better match the behavior of Cairo
var drawPoint = ctx.GetCTM ().TransformPoint (ctx.GetPathBoundingBox ().Location);
var patternPhase = new SizeF (drawPoint.X, drawPoint.Y);
if (patternPhase != SizeF.Empty)
ctx.SetPatternPhase (patternPhase);
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using AutoMapper;
using Microsoft.Azure.Commands.Network.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.Tags;
using Microsoft.Azure.Management.Network;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using MNM = Microsoft.Azure.Management.Network.Models;
namespace Microsoft.Azure.Commands.Network
{
[Cmdlet(VerbsCommon.New, "AzureRmNetworkInterface", SupportsShouldProcess = true,
DefaultParameterSetName = "SetByIpConfigurationResource"), OutputType(typeof(PSNetworkInterface))]
public class NewAzureNetworkInterfaceCommand : NetworkInterfaceBaseCmdlet
{
[Alias("ResourceName")]
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource name.")]
[ValidateNotNullOrEmpty]
public virtual string Name { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The resource group name.")]
[ValidateNotNullOrEmpty]
public virtual string ResourceGroupName { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The public IP address location.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByIpConfigurationResourceId",
HelpMessage = "List of IpConfigurations")]
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByIpConfigurationResource",
HelpMessage = "List of IpConfigurations")]
[ValidateNotNullOrEmpty]
public List<PSNetworkInterfaceIPConfiguration> IpConfiguration { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "SubnetId")]
[ValidateNotNullOrEmpty]
public string SubnetId { get; set; }
[Parameter(
Mandatory = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "Subnet")]
public PSSubnet Subnet { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "PublicIpAddressId")]
public string PublicIpAddressId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "PublicIpAddress")]
public PSPublicIpAddress PublicIpAddress { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByIpConfigurationResourceId",
HelpMessage = "NetworkSecurityGroup")]
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "NetworkSecurityGroupId")]
public string NetworkSecurityGroupId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByIpConfigurationResourceId",
HelpMessage = "NetworkSecurityGroup")]
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "NetworkSecurityGroup")]
public PSNetworkSecurityGroup NetworkSecurityGroup { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "LoadBalancerBackendAddressPoolId")]
public List<string> LoadBalancerBackendAddressPoolId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "LoadBalancerBackendAddressPools")]
public List<PSBackendAddressPool> LoadBalancerBackendAddressPool { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "LoadBalancerInboundNatRuleId")]
public List<string> LoadBalancerInboundNatRuleId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "LoadBalancerInboundNatRule")]
public List<PSInboundNatRule> LoadBalancerInboundNatRule { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "ApplicationGatewayBackendAddressPoolId")]
public List<string> ApplicationGatewayBackendAddressPoolId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "ApplicationGatewayBackendAddressPools")]
public List<PSApplicationGatewayBackendAddressPool> ApplicationGatewayBackendAddressPool { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResourceId",
HelpMessage = "The private ip address of the Network Interface " +
"if static allocation is specified.")]
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
ParameterSetName = "SetByResource",
HelpMessage = "The private ip address of the Network Interface " +
"if static allocation is specified.")]
public string PrivateIpAddress { get; set; }
[Parameter(
Mandatory = false,
ParameterSetName = "SetByResourceId",
ValueFromPipelineByPropertyName = true,
HelpMessage = "The IpConfiguration name." +
"default value: ipconfig1")]
[Parameter(
Mandatory = false,
ParameterSetName = "SetByResource",
ValueFromPipelineByPropertyName = true,
HelpMessage = "The IpConfiguration name." +
"default value: ipconfig1")]
[ValidateNotNullOrEmpty]
public string IpConfigurationName { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The list of Dns Servers")]
public List<string> DnsServer { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The Internal Dns name")]
public string InternalDnsNameLabel { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "EnableIPForwarding")]
public SwitchParameter EnableIPForwarding { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "EnableAcceleratedNetworking")]
public SwitchParameter EnableAcceleratedNetworking { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true,
HelpMessage = "A hashtable which represents resource tags.")]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
HelpMessage = "Do not ask for confirmation if you want to overrite a resource")]
public SwitchParameter Force { get; set; }
public override void Execute()
{
base.Execute();
WriteWarning("The output object type of this cmdlet will be modified in a future release.");
var present = this.IsNetworkInterfacePresent(this.ResourceGroupName, this.Name);
ConfirmAction(
Force.IsPresent,
string.Format(Properties.Resources.OverwritingResource, Name),
Properties.Resources.CreatingResourceMessage,
Name,
() =>
{
var networkInterface = CreateNetworkInterface();
if (present)
{
networkInterface = this.GetNetworkInterface(this.ResourceGroupName, this.Name);
}
WriteObject(networkInterface);
},
() => present);
}
private PSNetworkInterface CreateNetworkInterface()
{
var networkInterface = new PSNetworkInterface();
networkInterface.Name = this.Name;
networkInterface.Location = this.Location;
networkInterface.EnableIPForwarding = this.EnableIPForwarding.IsPresent;
networkInterface.EnableAcceleratedNetworking = this.EnableAcceleratedNetworking.IsPresent;
// Get the subnetId and publicIpAddressId from the object if specified
if (ParameterSetName.Contains(Microsoft.Azure.Commands.Network.Properties.Resources.SetByIpConfiguration))
{
networkInterface.IpConfigurations = this.IpConfiguration;
if (string.Equals(ParameterSetName, Microsoft.Azure.Commands.Network.Properties.Resources.SetByIpConfigurationResourceId))
{
if (this.NetworkSecurityGroup != null)
{
this.NetworkSecurityGroupId = this.NetworkSecurityGroup.Id;
}
}
}
else
{
if (string.Equals(ParameterSetName, Microsoft.Azure.Commands.Network.Properties.Resources.SetByResource))
{
this.SubnetId = this.Subnet.Id;
if (this.PublicIpAddress != null)
{
this.PublicIpAddressId = this.PublicIpAddress.Id;
}
if (this.NetworkSecurityGroup != null)
{
this.NetworkSecurityGroupId = this.NetworkSecurityGroup.Id;
}
if (this.LoadBalancerBackendAddressPool != null)
{
this.LoadBalancerBackendAddressPoolId = new List<string>();
foreach (var bepool in this.LoadBalancerBackendAddressPool)
{
this.LoadBalancerBackendAddressPoolId.Add(bepool.Id);
}
}
if (this.LoadBalancerInboundNatRule != null)
{
this.LoadBalancerInboundNatRuleId = new List<string>();
foreach (var natRule in this.LoadBalancerInboundNatRule)
{
this.LoadBalancerInboundNatRuleId.Add(natRule.Id);
}
}
if (this.ApplicationGatewayBackendAddressPool != null)
{
this.ApplicationGatewayBackendAddressPoolId = new List<string>();
foreach (var appgwBepool in this.ApplicationGatewayBackendAddressPool)
{
this.ApplicationGatewayBackendAddressPoolId.Add(appgwBepool.Id);
}
}
}
var nicIpConfiguration = new PSNetworkInterfaceIPConfiguration();
nicIpConfiguration.Name = string.IsNullOrEmpty(this.IpConfigurationName) ? "ipconfig1" : this.IpConfigurationName;
nicIpConfiguration.PrivateIpAllocationMethod = MNM.IPAllocationMethod.Dynamic;
nicIpConfiguration.Primary = true;
// Uncomment when ipv6 is supported as standalone ipconfig in a nic
// nicIpConfiguration.PrivateIpAddressVersion = this.PrivateIpAddressVersion;
if (!string.IsNullOrEmpty(this.PrivateIpAddress))
{
nicIpConfiguration.PrivateIpAddress = this.PrivateIpAddress;
nicIpConfiguration.PrivateIpAllocationMethod = MNM.IPAllocationMethod.Static;
}
nicIpConfiguration.Subnet = new PSSubnet();
nicIpConfiguration.Subnet.Id = this.SubnetId;
if (!string.IsNullOrEmpty(this.PublicIpAddressId))
{
nicIpConfiguration.PublicIpAddress = new PSPublicIpAddress();
nicIpConfiguration.PublicIpAddress.Id = this.PublicIpAddressId;
}
if (this.LoadBalancerBackendAddressPoolId != null)
{
nicIpConfiguration.LoadBalancerBackendAddressPools = new List<PSBackendAddressPool>();
foreach (var bepoolId in this.LoadBalancerBackendAddressPoolId)
{
nicIpConfiguration.LoadBalancerBackendAddressPools.Add(new PSBackendAddressPool { Id = bepoolId });
}
}
if (this.LoadBalancerInboundNatRuleId != null)
{
nicIpConfiguration.LoadBalancerInboundNatRules = new List<PSInboundNatRule>();
foreach (var natruleId in this.LoadBalancerInboundNatRuleId)
{
nicIpConfiguration.LoadBalancerInboundNatRules.Add(new PSInboundNatRule { Id = natruleId });
}
}
if (this.ApplicationGatewayBackendAddressPoolId != null)
{
nicIpConfiguration.ApplicationGatewayBackendAddressPools = new List<PSApplicationGatewayBackendAddressPool>();
foreach (var appgwBepoolId in this.ApplicationGatewayBackendAddressPoolId)
{
nicIpConfiguration.ApplicationGatewayBackendAddressPools.Add(new PSApplicationGatewayBackendAddressPool { Id = appgwBepoolId });
}
}
networkInterface.IpConfigurations = new List<PSNetworkInterfaceIPConfiguration>();
networkInterface.IpConfigurations.Add(nicIpConfiguration);
}
if (this.DnsServer != null || this.InternalDnsNameLabel != null)
{
networkInterface.DnsSettings = new PSNetworkInterfaceDnsSettings();
if (this.DnsServer != null)
{
networkInterface.DnsSettings.DnsServers = this.DnsServer;
}
if (this.InternalDnsNameLabel != null)
{
networkInterface.DnsSettings.InternalDnsNameLabel = this.InternalDnsNameLabel;
}
}
if (!string.IsNullOrEmpty(this.NetworkSecurityGroupId))
{
networkInterface.NetworkSecurityGroup = new PSNetworkSecurityGroup();
networkInterface.NetworkSecurityGroup.Id = this.NetworkSecurityGroupId;
}
var networkInterfaceModel = Mapper.Map<MNM.NetworkInterface>(networkInterface);
networkInterfaceModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true);
this.NetworkInterfaceClient.CreateOrUpdate(this.ResourceGroupName, this.Name, networkInterfaceModel);
var getNetworkInterface = this.GetNetworkInterface(this.ResourceGroupName, this.Name);
return getNetworkInterface;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="Preprocessor.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Schema {
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Runtime.Versioning;
#pragma warning disable 618
internal sealed class SchemaCollectionPreprocessor : BaseProcessor {
enum Compositor {
Root,
Include,
Import
};
XmlSchema schema;
string targetNamespace;
bool buildinIncluded = false;
XmlSchemaForm elementFormDefault;
XmlSchemaForm attributeFormDefault;
XmlSchemaDerivationMethod blockDefault;
XmlSchemaDerivationMethod finalDefault;
//Dictionary<Uri, Uri> schemaLocations;
Hashtable schemaLocations;
Hashtable referenceNamespaces;
string Xmlns;
const XmlSchemaDerivationMethod schemaBlockDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution;
const XmlSchemaDerivationMethod schemaFinalDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union;
const XmlSchemaDerivationMethod elementBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution;
const XmlSchemaDerivationMethod elementFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
const XmlSchemaDerivationMethod simpleTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union;
const XmlSchemaDerivationMethod complexTypeBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
const XmlSchemaDerivationMethod complexTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension;
private XmlResolver xmlResolver = null;
public SchemaCollectionPreprocessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
: base(nameTable, schemaNames, eventHandler) {
}
public bool Execute(XmlSchema schema, string targetNamespace, bool loadExternals, XmlSchemaCollection xsc) {
this.schema = schema;
Xmlns = NameTable.Add("xmlns");
Cleanup(schema);
if (loadExternals && xmlResolver != null) {
schemaLocations = new Hashtable(); //new Dictionary<Uri, Uri>();
if (schema.BaseUri != null) {
schemaLocations.Add(schema.BaseUri, schema.BaseUri);
}
LoadExternals(schema, xsc);
}
ValidateIdAttribute(schema);
Preprocess(schema, targetNamespace, Compositor.Root);
if (!HasErrors) {
schema.IsPreprocessed = true;
for (int i = 0; i < schema.Includes.Count; ++i) {
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include.Schema != null) {
include.Schema.IsPreprocessed = true;
}
}
}
return !HasErrors;
}
private void Cleanup(XmlSchema schema) {
if (schema.IsProcessing) {
return;
}
schema.IsProcessing = true;
for (int i = 0; i < schema.Includes.Count; ++i) {
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include.Schema != null) {
Cleanup(include.Schema);
}
if (include is XmlSchemaRedefine) {
XmlSchemaRedefine rdef = include as XmlSchemaRedefine;
rdef.AttributeGroups.Clear();
rdef.Groups.Clear();
rdef.SchemaTypes.Clear();
}
}
schema.Attributes.Clear();
schema.AttributeGroups.Clear();
schema.SchemaTypes.Clear();
schema.Elements.Clear();
schema.Groups.Clear();
schema.Notations.Clear();
schema.Ids.Clear();
schema.IdentityConstraints.Clear();
schema.IsProcessing = false;
}
internal XmlResolver XmlResolver {
set {
xmlResolver = value;
}
}
// SxS: This method reads resource names from the source documents and does not return any resources to the caller
// It's fine to suppress the SxS warning
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
private void LoadExternals(XmlSchema schema, XmlSchemaCollection xsc) {
if (schema.IsProcessing) {
return;
}
schema.IsProcessing = true;
for (int i = 0; i < schema.Includes.Count; ++i) {
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
Uri includeLocation = null;
//CASE 1: If the Schema object of the include has been set
if (include.Schema != null) {
// already loaded
if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml) {
buildinIncluded = true;
}
else {
includeLocation = include.BaseUri;
if (includeLocation != null && schemaLocations[includeLocation] == null) {
schemaLocations.Add(includeLocation, includeLocation);
}
LoadExternals(include.Schema, xsc);
}
continue;
}
//CASE 2: If the include has been already added to the schema collection directly
if (xsc != null && include is XmlSchemaImport) { //Added for SchemaCollection compatibility
XmlSchemaImport import = (XmlSchemaImport)include;
string importNS = import.Namespace != null ? import.Namespace : string.Empty;
include.Schema = xsc[importNS]; //Fetch it from the collection
if (include.Schema != null) {
include.Schema = include.Schema.Clone();
if (include.Schema.BaseUri != null && schemaLocations[include.Schema.BaseUri] == null) {
schemaLocations.Add(include.Schema.BaseUri, include.Schema.BaseUri);
}
//To avoid re-including components that were already included through a different path
Uri subUri = null;
for (int j = 0; j < include.Schema.Includes.Count; ++j) {
XmlSchemaExternal subInc = (XmlSchemaExternal)include.Schema.Includes[j];
if (subInc is XmlSchemaImport) {
XmlSchemaImport subImp = (XmlSchemaImport)subInc;
subUri = subImp.BaseUri != null ? subImp.BaseUri : (subImp.Schema != null && subImp.Schema.BaseUri != null ? subImp.Schema.BaseUri : null);
if (subUri != null) {
if(schemaLocations[subUri] != null) {
subImp.Schema = null; //So that the components are not included again
}
else { //if its not there already, add it
schemaLocations.Add(subUri, subUri); //The schema for that location is available
}
}
}
}
continue;
}
}
//CASE 3: If the imported namespace is the XML namespace, load built-in schema
if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml) {
if (!buildinIncluded) {
buildinIncluded = true;
include.Schema = Preprocessor.GetBuildInSchema();
}
continue;
}
//CASE4: Parse schema from the provided location
string schemaLocation = include.SchemaLocation;
if (schemaLocation == null) {
continue;
}
Uri ruri = ResolveSchemaLocationUri(schema, schemaLocation);
if (ruri != null && schemaLocations[ruri] == null) {
Stream stream = GetSchemaEntity(ruri);
if (stream != null) {
include.BaseUri = ruri;
schemaLocations.Add(ruri, ruri);
XmlTextReader reader = new XmlTextReader(ruri.ToString(), stream, NameTable);
reader.XmlResolver = xmlResolver;
try {
Parser parser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler);
parser.Parse(reader, null);
while(reader.Read());// wellformness check
include.Schema = parser.XmlSchema;
LoadExternals(include.Schema, xsc);
}
catch(XmlSchemaException e) {
SendValidationEventNoThrow(new XmlSchemaException(Res.Sch_CannotLoadSchema, new string[] {schemaLocation, e.Message}, e.SourceUri, e.LineNumber, e.LinePosition), XmlSeverityType.Error);
}
catch(Exception) {
SendValidationEvent(Res.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning);
}
finally {
reader.Close();
}
}
else {
SendValidationEvent(Res.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning);
}
}
}
schema.IsProcessing = false;
}
private void BuildRefNamespaces(XmlSchema schema) {
referenceNamespaces = new Hashtable();
XmlSchemaImport import;
string ns;
//Add XSD namespace
referenceNamespaces.Add(XmlReservedNs.NsXs,XmlReservedNs.NsXs);
referenceNamespaces.Add(string.Empty, string.Empty);
for (int i = 0; i < schema.Includes.Count; ++i) {
import = schema.Includes[i] as XmlSchemaImport;
if (import != null) {
ns = import.Namespace;
if(ns != null && referenceNamespaces[ns] == null)
referenceNamespaces.Add(ns,ns);
}
}
//Add the schema's targetnamespace
if(schema.TargetNamespace != null && referenceNamespaces[schema.TargetNamespace] == null)
referenceNamespaces.Add(schema.TargetNamespace,schema.TargetNamespace);
}
private void Preprocess(XmlSchema schema, string targetNamespace, Compositor compositor) {
if (schema.IsProcessing) {
return;
}
schema.IsProcessing = true;
string tns = schema.TargetNamespace;
if (tns != null) {
schema.TargetNamespace = tns = NameTable.Add(tns);
if (tns.Length == 0) {
SendValidationEvent(Res.Sch_InvalidTargetNamespaceAttribute, schema);
}
else {
try {
XmlConvert.ToUri(tns); // can throw
}
catch {
SendValidationEvent(Res.Sch_InvalidNamespace, schema.TargetNamespace, schema);
}
}
}
if (schema.Version != null) {
try {
XmlConvert.VerifyTOKEN(schema.Version); // can throw
}
catch (Exception) {
SendValidationEvent(Res.Sch_AttributeValueDataType, "version", schema);
}
}
switch (compositor) {
case Compositor.Root:
if (targetNamespace == null && schema.TargetNamespace != null) { // not specified
targetNamespace = schema.TargetNamespace;
}
else if (schema.TargetNamespace == null && targetNamespace != null && targetNamespace.Length == 0) { // no namespace schema
targetNamespace = null;
}
if (targetNamespace != schema.TargetNamespace) {
SendValidationEvent(Res.Sch_MismatchTargetNamespaceEx, targetNamespace, schema.TargetNamespace, schema);
}
break;
case Compositor.Import:
if (targetNamespace != schema.TargetNamespace) {
SendValidationEvent(Res.Sch_MismatchTargetNamespaceImport, targetNamespace, schema.TargetNamespace, schema);
}
break;
case Compositor.Include:
if (schema.TargetNamespace != null) {
if (targetNamespace != schema.TargetNamespace) {
SendValidationEvent(Res.Sch_MismatchTargetNamespaceInclude, targetNamespace, schema.TargetNamespace, schema);
}
}
break;
}
for (int i = 0; i < schema.Includes.Count; ++i) {
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
SetParent(include, schema);
PreprocessAnnotation(include);
string loc = include.SchemaLocation;
if (loc != null) {
try {
XmlConvert.ToUri(loc); // can throw
}
catch {
SendValidationEvent(Res.Sch_InvalidSchemaLocation, loc, include);
}
}
else if((include is XmlSchemaRedefine || include is XmlSchemaInclude) && include.Schema == null) {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "schemaLocation", include);
}
if (include.Schema != null) {
if (include is XmlSchemaRedefine) {
Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include);
}
else if (include is XmlSchemaImport) {
if (((XmlSchemaImport)include).Namespace == null && schema.TargetNamespace == null) {
SendValidationEvent(Res.Sch_ImportTargetNamespaceNull, include);
}
else if (((XmlSchemaImport)include).Namespace == schema.TargetNamespace) {
SendValidationEvent(Res.Sch_ImportTargetNamespace, include);
}
Preprocess(include.Schema, ((XmlSchemaImport)include).Namespace, Compositor.Import);
}
else {
Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include);
}
}
else if (include is XmlSchemaImport) {
string ns = ((XmlSchemaImport)include).Namespace;
if (ns != null) {
if (ns.Length == 0) {
SendValidationEvent(Res.Sch_InvalidNamespaceAttribute, ns, include);
}
else {
try {
XmlConvert.ToUri(ns); //can throw
}
catch(FormatException) {
SendValidationEvent(Res.Sch_InvalidNamespace, ns, include);
}
}
}
}
}
//Begin processing the current schema passed to preprocess
//Build the namespaces that can be referenced in the current schema
BuildRefNamespaces(schema);
this.targetNamespace = targetNamespace == null ? string.Empty : targetNamespace;
if (schema.BlockDefault == XmlSchemaDerivationMethod.All) {
this.blockDefault = XmlSchemaDerivationMethod.All;
}
else if (schema.BlockDefault == XmlSchemaDerivationMethod.None) {
this.blockDefault = XmlSchemaDerivationMethod.Empty;
}
else {
if ((schema.BlockDefault & ~schemaBlockDefaultAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidBlockDefaultValue, schema);
}
this.blockDefault = schema.BlockDefault & schemaBlockDefaultAllowed;
}
if (schema.FinalDefault == XmlSchemaDerivationMethod.All) {
this.finalDefault = XmlSchemaDerivationMethod.All;
}
else if (schema.FinalDefault == XmlSchemaDerivationMethod.None) {
this.finalDefault = XmlSchemaDerivationMethod.Empty;
}
else {
if ((schema.FinalDefault & ~schemaFinalDefaultAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidFinalDefaultValue, schema);
}
this.finalDefault = schema.FinalDefault & schemaFinalDefaultAllowed;
}
this.elementFormDefault = schema.ElementFormDefault;
if (this.elementFormDefault == XmlSchemaForm.None) {
this.elementFormDefault = XmlSchemaForm.Unqualified;
}
this.attributeFormDefault = schema.AttributeFormDefault;
if (this.attributeFormDefault == XmlSchemaForm.None) {
this.attributeFormDefault = XmlSchemaForm.Unqualified;
}
for (int i = 0; i < schema.Includes.Count; ++i) {
XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i];
if (include is XmlSchemaRedefine) {
XmlSchemaRedefine redefine = (XmlSchemaRedefine)include;
if (include.Schema != null) {
PreprocessRedefine(redefine);
}
else {
for (int j = 0; j < redefine.Items.Count; ++j) {
if (!(redefine.Items[j] is XmlSchemaAnnotation)) {
SendValidationEvent(Res.Sch_RedefineNoSchema, redefine);
break;
}
}
}
}
XmlSchema includedSchema = include.Schema;
if (includedSchema != null) {
foreach (XmlSchemaElement element in includedSchema.Elements.Values) {
AddToTable(schema.Elements, element.QualifiedName, element);
}
foreach (XmlSchemaAttribute attribute in includedSchema.Attributes.Values) {
AddToTable(schema.Attributes, attribute.QualifiedName, attribute);
}
foreach (XmlSchemaGroup group in includedSchema.Groups.Values) {
AddToTable(schema.Groups, group.QualifiedName, group);
}
foreach (XmlSchemaAttributeGroup attributeGroup in includedSchema.AttributeGroups.Values) {
AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
}
foreach (XmlSchemaType type in includedSchema.SchemaTypes.Values) {
AddToTable(schema.SchemaTypes, type.QualifiedName, type);
}
foreach (XmlSchemaNotation notation in includedSchema.Notations.Values) {
AddToTable(schema.Notations, notation.QualifiedName, notation);
}
}
ValidateIdAttribute(include);
}
List<XmlSchemaObject> removeItemsList = new List<XmlSchemaObject>();
for (int i = 0; i < schema.Items.Count; ++i) {
SetParent(schema.Items[i], schema);
XmlSchemaAttribute attribute = schema.Items[i] as XmlSchemaAttribute;
if (attribute != null) {
PreprocessAttribute(attribute);
AddToTable(schema.Attributes, attribute.QualifiedName, attribute);
}
else if (schema.Items[i] is XmlSchemaAttributeGroup) {
XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)schema.Items[i];
PreprocessAttributeGroup(attributeGroup);
AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
}
else if (schema.Items[i] is XmlSchemaComplexType) {
XmlSchemaComplexType complexType = (XmlSchemaComplexType)schema.Items[i];
PreprocessComplexType(complexType, false);
AddToTable(schema.SchemaTypes, complexType.QualifiedName, complexType);
}
else if (schema.Items[i] is XmlSchemaSimpleType) {
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schema.Items[i];
PreprocessSimpleType(simpleType, false);
AddToTable(schema.SchemaTypes, simpleType.QualifiedName, simpleType);
}
else if (schema.Items[i] is XmlSchemaElement) {
XmlSchemaElement element = (XmlSchemaElement)schema.Items[i];
PreprocessElement(element);
AddToTable(schema.Elements, element.QualifiedName, element);
}
else if (schema.Items[i] is XmlSchemaGroup) {
XmlSchemaGroup group = (XmlSchemaGroup)schema.Items[i];
PreprocessGroup(group);
AddToTable(schema.Groups, group.QualifiedName, group);
}
else if (schema.Items[i] is XmlSchemaNotation) {
XmlSchemaNotation notation = (XmlSchemaNotation)schema.Items[i];
PreprocessNotation(notation);
AddToTable(schema.Notations, notation.QualifiedName, notation);
}
else if(!(schema.Items[i] is XmlSchemaAnnotation)) {
SendValidationEvent(Res.Sch_InvalidCollection, schema.Items[i]);
removeItemsList.Add(schema.Items[i]);
}
}
for (int i = 0; i < removeItemsList.Count; ++i) {
schema.Items.Remove(removeItemsList[i]);
}
schema.IsProcessing = false;
}
private void PreprocessRedefine(XmlSchemaRedefine redefine) {
for (int i = 0; i < redefine.Items.Count; ++i) {
SetParent(redefine.Items[i], redefine);
XmlSchemaGroup group = redefine.Items[i] as XmlSchemaGroup;
if (group != null) {
PreprocessGroup(group);
if (redefine.Groups[group.QualifiedName] != null) {
SendValidationEvent(Res.Sch_GroupDoubleRedefine, group);
}
else {
AddToTable(redefine.Groups, group.QualifiedName, group);
group.Redefined = (XmlSchemaGroup)redefine.Schema.Groups[group.QualifiedName];
if (group.Redefined != null) {
CheckRefinedGroup(group);
}
else {
SendValidationEvent(Res.Sch_GroupRedefineNotFound, group);
}
}
}
else if (redefine.Items[i] is XmlSchemaAttributeGroup) {
XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)redefine.Items[i];
PreprocessAttributeGroup(attributeGroup);
if (redefine.AttributeGroups[attributeGroup.QualifiedName] != null) {
SendValidationEvent(Res.Sch_AttrGroupDoubleRedefine, attributeGroup);
}
else {
AddToTable(redefine.AttributeGroups, attributeGroup.QualifiedName, attributeGroup);
attributeGroup.Redefined = (XmlSchemaAttributeGroup)redefine.Schema.AttributeGroups[attributeGroup.QualifiedName];
if (attributeGroup.Redefined != null) {
CheckRefinedAttributeGroup(attributeGroup);
}
else {
SendValidationEvent(Res.Sch_AttrGroupRedefineNotFound, attributeGroup);
}
}
}
else if (redefine.Items[i] is XmlSchemaComplexType) {
XmlSchemaComplexType complexType = (XmlSchemaComplexType)redefine.Items[i];
PreprocessComplexType(complexType, false);
if (redefine.SchemaTypes[complexType.QualifiedName] != null) {
SendValidationEvent(Res.Sch_ComplexTypeDoubleRedefine, complexType);
}
else {
AddToTable(redefine.SchemaTypes, complexType.QualifiedName, complexType);
XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[complexType.QualifiedName];
if (type != null) {
if (type is XmlSchemaComplexType) {
complexType.Redefined = type;
CheckRefinedComplexType(complexType);
}
else {
SendValidationEvent(Res.Sch_SimpleToComplexTypeRedefine, complexType);
}
}
else {
SendValidationEvent(Res.Sch_ComplexTypeRedefineNotFound, complexType);
}
}
}
else if (redefine.Items[i] is XmlSchemaSimpleType) {
XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)redefine.Items[i];
PreprocessSimpleType(simpleType, false);
if (redefine.SchemaTypes[simpleType.QualifiedName] != null) {
SendValidationEvent(Res.Sch_SimpleTypeDoubleRedefine, simpleType);
}
else {
AddToTable(redefine.SchemaTypes, simpleType.QualifiedName, simpleType);
XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[simpleType.QualifiedName];
if (type != null) {
if (type is XmlSchemaSimpleType) {
simpleType.Redefined = type;
CheckRefinedSimpleType(simpleType);
}
else {
SendValidationEvent(Res.Sch_ComplexToSimpleTypeRedefine, simpleType);
}
}
else {
SendValidationEvent(Res.Sch_SimpleTypeRedefineNotFound, simpleType);
}
}
}
}
foreach (DictionaryEntry entry in redefine.Groups) {
redefine.Schema.Groups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
foreach (DictionaryEntry entry in redefine.AttributeGroups) {
redefine.Schema.AttributeGroups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
foreach (DictionaryEntry entry in redefine.SchemaTypes) {
redefine.Schema.SchemaTypes.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value);
}
}
private int CountGroupSelfReference(XmlSchemaObjectCollection items, XmlQualifiedName name) {
int count = 0;
for (int i = 0; i < items.Count; ++i) {
XmlSchemaGroupRef groupRef = items[i] as XmlSchemaGroupRef;
if (groupRef != null) {
if (groupRef.RefName == name) {
if (groupRef.MinOccurs != decimal.One || groupRef.MaxOccurs != decimal.One) {
SendValidationEvent(Res.Sch_MinMaxGroupRedefine, groupRef);
}
count ++;
}
}
else if (items[i] is XmlSchemaGroupBase) {
count += CountGroupSelfReference(((XmlSchemaGroupBase) items[i]).Items, name);
}
if (count > 1) {
break;
}
}
return count;
}
private void CheckRefinedGroup(XmlSchemaGroup group) {
int count = 0;
if (group.Particle != null) {
count = CountGroupSelfReference(group.Particle.Items, group.QualifiedName);
}
if (count > 1) {
SendValidationEvent(Res.Sch_MultipleGroupSelfRef, group);
}
}
private void CheckRefinedAttributeGroup(XmlSchemaAttributeGroup attributeGroup) {
int count = 0;
for (int i = 0; i < attributeGroup.Attributes.Count; ++i) {
XmlSchemaAttributeGroupRef groupRef = attributeGroup.Attributes[i] as XmlSchemaAttributeGroupRef;
if (groupRef != null && groupRef.RefName == attributeGroup.QualifiedName) {
count++;
}
}
if (count > 1) {
SendValidationEvent(Res.Sch_MultipleAttrGroupSelfRef, attributeGroup);
}
}
private void CheckRefinedSimpleType(XmlSchemaSimpleType stype) {
if (stype.Content != null && stype.Content is XmlSchemaSimpleTypeRestriction) {
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)stype.Content;
if (restriction.BaseTypeName == stype.QualifiedName) {
return;
}
}
SendValidationEvent(Res.Sch_InvalidTypeRedefine, stype);
}
private void CheckRefinedComplexType(XmlSchemaComplexType ctype) {
if (ctype.ContentModel != null) {
XmlQualifiedName baseName;
if (ctype.ContentModel is XmlSchemaComplexContent) {
XmlSchemaComplexContent content = (XmlSchemaComplexContent)ctype.ContentModel;
if (content.Content is XmlSchemaComplexContentRestriction) {
baseName = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName;
}
else {
baseName = ((XmlSchemaComplexContentExtension)content.Content).BaseTypeName;
}
}
else {
XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)ctype.ContentModel;
if (content.Content is XmlSchemaSimpleContentRestriction) {
baseName = ((XmlSchemaSimpleContentRestriction)content.Content).BaseTypeName;
}
else {
baseName = ((XmlSchemaSimpleContentExtension)content.Content).BaseTypeName;
}
}
if (baseName == ctype.QualifiedName) {
return;
}
}
SendValidationEvent(Res.Sch_InvalidTypeRedefine, ctype);
}
private void PreprocessAttribute(XmlSchemaAttribute attribute) {
if (attribute.Name != null) {
ValidateNameAttribute(attribute);
attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", attribute);
}
if (attribute.Use != XmlSchemaUse.None) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "use", attribute);
}
if (attribute.Form != XmlSchemaForm.None) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "form", attribute);
}
PreprocessAttributeContent(attribute);
ValidateIdAttribute(attribute);
}
private void PreprocessLocalAttribute(XmlSchemaAttribute attribute) {
if (attribute.Name != null) { // name
ValidateNameAttribute(attribute);
PreprocessAttributeContent(attribute);
attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, (attribute.Form == XmlSchemaForm.Qualified || (attribute.Form == XmlSchemaForm.None && this.attributeFormDefault == XmlSchemaForm.Qualified)) ? this.targetNamespace : null));
}
else { // ref
PreprocessAnnotation(attribute); //set parent of annotation child of ref
if (attribute.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_AttributeNameRef, "???", attribute);
}
else {
ValidateQNameAttribute(attribute, "ref", attribute.RefName);
}
if (!attribute.SchemaTypeName.IsEmpty ||
attribute.SchemaType != null ||
attribute.Form != XmlSchemaForm.None /*||
attribute.DefaultValue != null ||
attribute.FixedValue != null*/
) {
SendValidationEvent(Res.Sch_InvalidAttributeRef, attribute);
}
attribute.SetQualifiedName(attribute.RefName);
}
ValidateIdAttribute(attribute);
}
private void PreprocessAttributeContent(XmlSchemaAttribute attribute) {
PreprocessAnnotation(attribute);
if (schema.TargetNamespace == XmlReservedNs.NsXsi) {
SendValidationEvent(Res.Sch_TargetNamespaceXsi, attribute);
}
if (!attribute.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "ref", attribute);
}
if (attribute.DefaultValue != null && attribute.FixedValue != null) {
SendValidationEvent(Res.Sch_DefaultFixedAttributes, attribute);
}
if (attribute.DefaultValue != null && attribute.Use != XmlSchemaUse.Optional && attribute.Use != XmlSchemaUse.None) {
SendValidationEvent(Res.Sch_OptionalDefaultAttribute, attribute);
}
if (attribute.Name == Xmlns) {
SendValidationEvent(Res.Sch_XmlNsAttribute, attribute);
}
if (attribute.SchemaType != null) {
SetParent(attribute.SchemaType, attribute);
if (!attribute.SchemaTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_TypeMutualExclusive, attribute);
}
PreprocessSimpleType(attribute.SchemaType, true);
}
if (!attribute.SchemaTypeName.IsEmpty) {
ValidateQNameAttribute(attribute, "type", attribute.SchemaTypeName);
}
}
private void PreprocessAttributeGroup(XmlSchemaAttributeGroup attributeGroup) {
if (attributeGroup.Name != null) {
ValidateNameAttribute(attributeGroup);
attributeGroup.SetQualifiedName(new XmlQualifiedName(attributeGroup.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", attributeGroup);
}
PreprocessAttributes(attributeGroup.Attributes, attributeGroup.AnyAttribute, attributeGroup);
PreprocessAnnotation(attributeGroup);
ValidateIdAttribute(attributeGroup);
}
private void PreprocessElement(XmlSchemaElement element) {
if (element.Name != null) {
ValidateNameAttribute(element);
element.SetQualifiedName(new XmlQualifiedName(element.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", element);
}
PreprocessElementContent(element);
if (element.Final == XmlSchemaDerivationMethod.All) {
element.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (element.Final == XmlSchemaDerivationMethod.None) {
if (this.finalDefault == XmlSchemaDerivationMethod.All) {
element.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else {
element.SetFinalResolved(this.finalDefault & elementFinalAllowed);
}
}
else {
if ((element.Final & ~elementFinalAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidElementFinalValue, element);
}
element.SetFinalResolved(element.Final & elementFinalAllowed);
}
if (element.Form != XmlSchemaForm.None) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "form", element);
}
if (element.MinOccursString != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "minOccurs", element);
}
if (element.MaxOccursString != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "maxOccurs", element);
}
if (!element.SubstitutionGroup.IsEmpty) {
ValidateQNameAttribute(element, "type", element.SubstitutionGroup);
}
ValidateIdAttribute(element);
}
private void PreprocessLocalElement(XmlSchemaElement element) {
if (element.Name != null) { // name
ValidateNameAttribute(element);
PreprocessElementContent(element);
element.SetQualifiedName(new XmlQualifiedName(element.Name, (element.Form == XmlSchemaForm.Qualified || (element.Form == XmlSchemaForm.None && this.elementFormDefault == XmlSchemaForm.Qualified))? this.targetNamespace : null));
}
else { // ref
PreprocessAnnotation(element); //Check annotation child for ref and set parent
if (element.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_ElementNameRef, element);
}
else {
ValidateQNameAttribute(element, "ref", element.RefName);
}
if (!element.SchemaTypeName.IsEmpty ||
element.IsAbstract ||
element.Block != XmlSchemaDerivationMethod.None ||
element.SchemaType != null ||
element.HasConstraints ||
element.DefaultValue != null ||
element.Form != XmlSchemaForm.None ||
element.FixedValue != null ||
element.HasNillableAttribute) {
SendValidationEvent(Res.Sch_InvalidElementRef, element);
}
if (element.DefaultValue != null && element.FixedValue != null) {
SendValidationEvent(Res.Sch_DefaultFixedAttributes, element);
}
element.SetQualifiedName(element.RefName);
}
if (element.MinOccurs > element.MaxOccurs) {
element.MinOccurs = decimal.Zero;
SendValidationEvent(Res.Sch_MinGtMax, element);
}
if(element.IsAbstract) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "abstract", element);
}
if (element.Final != XmlSchemaDerivationMethod.None) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "final", element);
}
if (!element.SubstitutionGroup.IsEmpty) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "substitutionGroup", element);
}
ValidateIdAttribute(element);
}
private void PreprocessElementContent(XmlSchemaElement element) {
PreprocessAnnotation(element); //Set parent for Annotation child of element
if (!element.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "ref", element);
}
if (element.Block == XmlSchemaDerivationMethod.All) {
element.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else if (element.Block == XmlSchemaDerivationMethod.None) {
if (this.blockDefault == XmlSchemaDerivationMethod.All) {
element.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else {
element.SetBlockResolved(this.blockDefault & elementBlockAllowed);
}
}
else {
if ((element.Block & ~elementBlockAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidElementBlockValue, element);
}
element.SetBlockResolved(element.Block & elementBlockAllowed);
}
if (element.SchemaType != null) {
SetParent(element.SchemaType, element); //Set parent for simple / complex type child of element
if (!element.SchemaTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_TypeMutualExclusive, element);
}
if (element.SchemaType is XmlSchemaComplexType) {
PreprocessComplexType((XmlSchemaComplexType)element.SchemaType, true);
}
else {
PreprocessSimpleType((XmlSchemaSimpleType)element.SchemaType, true);
}
}
if (!element.SchemaTypeName.IsEmpty) {
ValidateQNameAttribute(element, "type", element.SchemaTypeName);
}
if (element.DefaultValue != null && element.FixedValue != null) {
SendValidationEvent(Res.Sch_DefaultFixedAttributes, element);
}
for (int i = 0; i < element.Constraints.Count; ++i) {
SetParent(element.Constraints[i], element);
PreprocessIdentityConstraint((XmlSchemaIdentityConstraint)element.Constraints[i]);
}
}
private void PreprocessIdentityConstraint(XmlSchemaIdentityConstraint constraint) {
bool valid = true;
PreprocessAnnotation(constraint); //Set parent of annotation child of key/keyref/unique
if (constraint.Name != null) {
ValidateNameAttribute(constraint);
constraint.SetQualifiedName(new XmlQualifiedName(constraint.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", constraint);
valid = false;
}
if (this.schema.IdentityConstraints[constraint.QualifiedName] != null) {
SendValidationEvent(Res.Sch_DupIdentityConstraint, constraint.QualifiedName.ToString(), constraint);
valid = false;
}
else {
this.schema.IdentityConstraints.Add(constraint.QualifiedName, constraint);
}
if (constraint.Selector == null) {
SendValidationEvent(Res.Sch_IdConstraintNoSelector, constraint);
valid = false;
}
if (constraint.Fields.Count == 0) {
SendValidationEvent(Res.Sch_IdConstraintNoFields, constraint);
valid = false;
}
if (constraint is XmlSchemaKeyref) {
XmlSchemaKeyref keyref = (XmlSchemaKeyref)constraint;
if (keyref.Refer.IsEmpty) {
SendValidationEvent(Res.Sch_IdConstraintNoRefer, constraint);
valid = false;
}
else {
ValidateQNameAttribute(keyref, "refer", keyref.Refer);
}
}
if (valid) {
ValidateIdAttribute(constraint);
ValidateIdAttribute(constraint.Selector);
SetParent(constraint.Selector, constraint);
for (int i = 0; i < constraint.Fields.Count; ++i) {
SetParent(constraint.Fields[i], constraint);
ValidateIdAttribute(constraint.Fields[i]);
}
}
}
private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) {
if (local) {
if (simpleType.Name != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "name", simpleType);
}
}
else {
if (simpleType.Name != null) {
ValidateNameAttribute(simpleType);
simpleType.SetQualifiedName(new XmlQualifiedName(simpleType.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", simpleType);
}
if (simpleType.Final == XmlSchemaDerivationMethod.All) {
simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (simpleType.Final == XmlSchemaDerivationMethod.None) {
if (this.finalDefault == XmlSchemaDerivationMethod.All) {
simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else {
simpleType.SetFinalResolved(this.finalDefault & simpleTypeFinalAllowed);
}
}
else {
if ((simpleType.Final & ~simpleTypeFinalAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidSimpleTypeFinalValue, simpleType);
}
simpleType.SetFinalResolved(simpleType.Final & simpleTypeFinalAllowed);
}
}
if (simpleType.Content == null) {
SendValidationEvent(Res.Sch_NoSimpleTypeContent, simpleType);
}
else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) {
XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content;
//SetParent
SetParent(restriction, simpleType);
for (int i = 0; i < restriction.Facets.Count; ++i) {
SetParent(restriction.Facets[i], restriction);
}
if (restriction.BaseType != null) {
if (!restriction.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_SimpleTypeRestRefBase, restriction);
}
PreprocessSimpleType(restriction.BaseType, true);
}
else {
if (restriction.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_SimpleTypeRestRefBaseNone, restriction);
}
else {
ValidateQNameAttribute(restriction, "base", restriction.BaseTypeName);
}
}
PreprocessAnnotation(restriction); //set parent of annotation child of simple type restriction
ValidateIdAttribute(restriction);
}
else if (simpleType.Content is XmlSchemaSimpleTypeList) {
XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content;
SetParent(list, simpleType);
if (list.ItemType != null) {
if (!list.ItemTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_SimpleTypeListRefBase, list);
}
SetParent(list.ItemType, list);
PreprocessSimpleType(list.ItemType, true);
}
else {
if (list.ItemTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_SimpleTypeListRefBaseNone, list);
}
else {
ValidateQNameAttribute(list, "itemType", list.ItemTypeName);
}
}
PreprocessAnnotation(list); //set parent of annotation child of simple type list
ValidateIdAttribute(list);
}
else { // union
XmlSchemaSimpleTypeUnion union1 = (XmlSchemaSimpleTypeUnion)simpleType.Content;
SetParent(union1, simpleType);
int baseTypeCount = union1.BaseTypes.Count;
if (union1.MemberTypes != null) {
baseTypeCount += union1.MemberTypes.Length;
for (int i = 0; i < union1.MemberTypes.Length; ++i) {
ValidateQNameAttribute(union1, "memberTypes", union1.MemberTypes[i]);
}
}
if (baseTypeCount == 0) {
SendValidationEvent(Res.Sch_SimpleTypeUnionNoBase, union1);
}
for (int i = 0; i < union1.BaseTypes.Count; ++i) {
SetParent(union1.BaseTypes[i], union1);
PreprocessSimpleType((XmlSchemaSimpleType)union1.BaseTypes[i], true);
}
PreprocessAnnotation(union1); //set parent of annotation child of simple type union
ValidateIdAttribute(union1);
}
ValidateIdAttribute(simpleType);
}
private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) {
if (local) {
if (complexType.Name != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "name", complexType);
}
}
else {
if (complexType.Name != null) {
ValidateNameAttribute(complexType);
complexType.SetQualifiedName(new XmlQualifiedName(complexType.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", complexType);
}
if (complexType.Block == XmlSchemaDerivationMethod.All) {
complexType.SetBlockResolved(XmlSchemaDerivationMethod.All);
}
else if (complexType.Block == XmlSchemaDerivationMethod.None) {
complexType.SetBlockResolved(this.blockDefault & complexTypeBlockAllowed);
}
else {
if ((complexType.Block & ~complexTypeBlockAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidComplexTypeBlockValue, complexType);
}
complexType.SetBlockResolved(complexType.Block & complexTypeBlockAllowed);
}
if (complexType.Final == XmlSchemaDerivationMethod.All) {
complexType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else if (complexType.Final == XmlSchemaDerivationMethod.None) {
if (this.finalDefault == XmlSchemaDerivationMethod.All) {
complexType.SetFinalResolved(XmlSchemaDerivationMethod.All);
}
else {
complexType.SetFinalResolved(this.finalDefault & complexTypeFinalAllowed);
}
}
else {
if ((complexType.Final & ~complexTypeFinalAllowed) != 0) {
SendValidationEvent(Res.Sch_InvalidComplexTypeFinalValue, complexType);
}
complexType.SetFinalResolved(complexType.Final & complexTypeFinalAllowed);
}
}
if (complexType.ContentModel != null) {
SetParent(complexType.ContentModel, complexType); //SimpleContent / complexCotent
PreprocessAnnotation(complexType.ContentModel);
if (complexType.Particle != null || complexType.Attributes != null) {
// this is illigal
}
if (complexType.ContentModel is XmlSchemaSimpleContent) {
XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)complexType.ContentModel;
if (content.Content == null) {
if (complexType.QualifiedName == XmlQualifiedName.Empty) {
SendValidationEvent(Res.Sch_NoRestOrExt, complexType);
}
else {
SendValidationEvent(Res.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType);
}
}
else {
SetParent(content.Content, content); //simplecontent extension / restriction
PreprocessAnnotation(content.Content); //annotation child of simple extension / restriction
if (content.Content is XmlSchemaSimpleContentExtension) {
XmlSchemaSimpleContentExtension contentExtension = (XmlSchemaSimpleContentExtension)content.Content;
if (contentExtension.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "base", contentExtension);
}
else {
ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName);
}
PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension);
ValidateIdAttribute(contentExtension);
}
else { //XmlSchemaSimpleContentRestriction
XmlSchemaSimpleContentRestriction contentRestriction = (XmlSchemaSimpleContentRestriction)content.Content;
if (contentRestriction.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "base", contentRestriction);
}
else {
ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName);
}
if (contentRestriction.BaseType != null) {
SetParent(contentRestriction.BaseType, contentRestriction);
PreprocessSimpleType(contentRestriction.BaseType, true);
}
PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction);
ValidateIdAttribute(contentRestriction);
}
}
ValidateIdAttribute(content);
}
else { // XmlSchemaComplexContent
XmlSchemaComplexContent content = (XmlSchemaComplexContent)complexType.ContentModel;
if (content.Content == null) {
if (complexType.QualifiedName == XmlQualifiedName.Empty) {
SendValidationEvent(Res.Sch_NoRestOrExt, complexType);
}
else {
SendValidationEvent(Res.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType);
}
}
else {
if ( !content.HasMixedAttribute && complexType.IsMixed) {
content.IsMixed = true; // fixup
}
SetParent(content.Content, content); //complexcontent extension / restriction
PreprocessAnnotation(content.Content); //Annotation child of extension / restriction
if (content.Content is XmlSchemaComplexContentExtension) {
XmlSchemaComplexContentExtension contentExtension = (XmlSchemaComplexContentExtension)content.Content;
if (contentExtension.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "base", contentExtension);
}
else {
ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName);
}
if (contentExtension.Particle != null) {
SetParent(contentExtension.Particle, contentExtension); //Group / all / choice / sequence
PreprocessParticle(contentExtension.Particle);
}
PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension);
ValidateIdAttribute(contentExtension);
}
else { // XmlSchemaComplexContentRestriction
XmlSchemaComplexContentRestriction contentRestriction = (XmlSchemaComplexContentRestriction)content.Content;
if (contentRestriction.BaseTypeName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "base", contentRestriction);
}
else {
ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName);
}
if (contentRestriction.Particle != null) {
SetParent(contentRestriction.Particle, contentRestriction); //Group / all / choice / sequence
PreprocessParticle(contentRestriction.Particle);
}
PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction);
ValidateIdAttribute(contentRestriction);
}
ValidateIdAttribute(content);
}
}
}
else {
if (complexType.Particle != null) {
SetParent(complexType.Particle, complexType);
PreprocessParticle(complexType.Particle);
}
PreprocessAttributes(complexType.Attributes, complexType.AnyAttribute, complexType);
}
ValidateIdAttribute(complexType);
}
private void PreprocessGroup(XmlSchemaGroup group) {
if (group.Name != null) {
ValidateNameAttribute(group);
group.SetQualifiedName(new XmlQualifiedName(group.Name, this.targetNamespace));
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", group);
}
if (group.Particle == null) {
SendValidationEvent(Res.Sch_NoGroupParticle, group);
return;
}
if (group.Particle.MinOccursString != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "minOccurs", group.Particle);
}
if (group.Particle.MaxOccursString != null) {
SendValidationEvent(Res.Sch_ForbiddenAttribute, "maxOccurs", group.Particle);
}
PreprocessParticle(group.Particle);
PreprocessAnnotation(group); //Set parent of annotation child of group
ValidateIdAttribute(group);
}
private void PreprocessNotation(XmlSchemaNotation notation) {
if (notation.Name != null) {
ValidateNameAttribute(notation);
notation.QualifiedName = new XmlQualifiedName(notation.Name, this.targetNamespace);
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "name", notation);
}
if (notation.Public != null) {
try {
XmlConvert.ToUri(notation.Public); // can throw
}
catch {
SendValidationEvent(Res.Sch_InvalidPublicAttribute, notation.Public, notation);
}
}
else {
SendValidationEvent(Res.Sch_MissRequiredAttribute, "public", notation);
}
if (notation.System != null) {
try {
XmlConvert.ToUri(notation.System); // can throw
}
catch {
SendValidationEvent(Res.Sch_InvalidSystemAttribute, notation.System, notation);
}
}
PreprocessAnnotation(notation); //Set parent of annotation child of notation
ValidateIdAttribute(notation);
}
private void PreprocessParticle(XmlSchemaParticle particle) {
XmlSchemaAll schemaAll = particle as XmlSchemaAll;
if (schemaAll != null) {
if (particle.MinOccurs != decimal.Zero && particle.MinOccurs != decimal.One) {
particle.MinOccurs = decimal.One;
SendValidationEvent(Res.Sch_InvalidAllMin, particle);
}
if (particle.MaxOccurs != decimal.One) {
particle.MaxOccurs = decimal.One;
SendValidationEvent(Res.Sch_InvalidAllMax, particle);
}
for (int i = 0; i < schemaAll.Items.Count; ++i) {
XmlSchemaElement element = (XmlSchemaElement)schemaAll.Items[i];
if (element.MaxOccurs != decimal.Zero && element.MaxOccurs != decimal.One) {
element.MaxOccurs = decimal.One;
SendValidationEvent(Res.Sch_InvalidAllElementMax, element);
}
SetParent(element, particle);
PreprocessLocalElement(element);
}
}
else {
if (particle.MinOccurs > particle.MaxOccurs) {
particle.MinOccurs = particle.MaxOccurs;
SendValidationEvent(Res.Sch_MinGtMax, particle);
}
XmlSchemaChoice choice = particle as XmlSchemaChoice;
if (choice != null) {
XmlSchemaObjectCollection choices = choice.Items;
for (int i = 0; i < choices.Count; ++i) {
SetParent(choices[i], particle);
XmlSchemaElement element = choices[i] as XmlSchemaElement;
if (element != null) {
PreprocessLocalElement(element);
}
else {
PreprocessParticle((XmlSchemaParticle)choices[i]);
}
}
}
else if (particle is XmlSchemaSequence) {
XmlSchemaObjectCollection sequences = ((XmlSchemaSequence) particle).Items;
for (int i = 0; i < sequences.Count; ++i) {
SetParent(sequences[i], particle);
XmlSchemaElement element = sequences[i] as XmlSchemaElement;
if (element != null) {
PreprocessLocalElement(element);
}
else {
PreprocessParticle((XmlSchemaParticle)sequences[i]);
}
}
}
else if (particle is XmlSchemaGroupRef) {
XmlSchemaGroupRef groupRef = (XmlSchemaGroupRef)particle;
if (groupRef.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "ref", groupRef);
}
else {
ValidateQNameAttribute(groupRef, "ref", groupRef.RefName);
}
}
else if (particle is XmlSchemaAny) {
try {
((XmlSchemaAny)particle).BuildNamespaceListV1Compat(this.targetNamespace);
}
catch {
SendValidationEvent(Res.Sch_InvalidAny, particle);
}
}
}
PreprocessAnnotation(particle); //set parent of annotation child of group / all/ choice / sequence
ValidateIdAttribute(particle);
}
private void PreprocessAttributes(XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlSchemaObject parent) {
for (int i = 0; i < attributes.Count; ++i) {
SetParent(attributes[i], parent);
XmlSchemaAttribute attribute = attributes[i] as XmlSchemaAttribute;
if (attribute != null) {
PreprocessLocalAttribute(attribute);
}
else { // XmlSchemaAttributeGroupRef
XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributes[i];
if (attributeGroupRef.RefName.IsEmpty) {
SendValidationEvent(Res.Sch_MissAttribute, "ref", attributeGroupRef);
}
else {
ValidateQNameAttribute(attributeGroupRef, "ref", attributeGroupRef.RefName);
}
PreprocessAnnotation(attributes[i]); //set parent of annotation child of attributeGroupRef
ValidateIdAttribute(attributes[i]);
}
}
if (anyAttribute != null) {
try {
SetParent(anyAttribute, parent);
PreprocessAnnotation(anyAttribute); //set parent of annotation child of any attribute
anyAttribute.BuildNamespaceListV1Compat(this.targetNamespace);
}
catch {
SendValidationEvent(Res.Sch_InvalidAnyAttribute, anyAttribute);
}
ValidateIdAttribute(anyAttribute);
}
}
private void ValidateIdAttribute(XmlSchemaObject xso) {
if (xso.IdAttribute != null) {
try {
xso.IdAttribute = NameTable.Add(XmlConvert.VerifyNCName(xso.IdAttribute));
if (this.schema.Ids[xso.IdAttribute] != null) {
SendValidationEvent(Res.Sch_DupIdAttribute, xso);
}
else {
this.schema.Ids.Add(xso.IdAttribute, xso);
}
}
catch (Exception ex){
SendValidationEvent(Res.Sch_InvalidIdAttribute, ex.Message, xso);
}
}
}
private void ValidateNameAttribute(XmlSchemaObject xso) {
string name = xso.NameAttribute;
if (name == null || name.Length == 0) {
SendValidationEvent(Res.Sch_InvalidNameAttributeEx, null, Res.GetString(Res.Sch_NullValue), xso);
}
//Normalize whitespace since NCName has whitespace facet="collapse"
name = XmlComplianceUtil.NonCDataNormalize(name);
int len = ValidateNames.ParseNCName(name, 0);
if (len != name.Length) { // If the string is not a valid NCName, then throw or return false
string[] invCharArgs = XmlException.BuildCharExceptionArgs(name, len);
string innerStr = Res.GetString(Res.Xml_BadNameCharWithPos, invCharArgs[0], invCharArgs[1], len);
SendValidationEvent(Res.Sch_InvalidNameAttributeEx, name, innerStr, xso);
}
else {
xso.NameAttribute = NameTable.Add(name);
}
}
private void ValidateQNameAttribute(XmlSchemaObject xso, string attributeName, XmlQualifiedName value) {
try {
value.Verify();
value.Atomize(NameTable);
if(referenceNamespaces[value.Namespace] == null) {
SendValidationEvent(Res.Sch_UnrefNS,value.Namespace,xso, XmlSeverityType.Warning);
}
}
catch (Exception ex){
SendValidationEvent(Res.Sch_InvalidAttribute, attributeName, ex.Message, xso);
}
}
private void SetParent(XmlSchemaObject child, XmlSchemaObject parent) {
child.Parent = parent;
}
private void PreprocessAnnotation(XmlSchemaObject schemaObject) {
XmlSchemaAnnotated annotated = schemaObject as XmlSchemaAnnotated;
if (annotated != null) {
if (annotated.Annotation != null) {
annotated.Annotation.Parent = schemaObject;
for (int i = 0; i < annotated.Annotation.Items.Count; ++i) {
annotated.Annotation.Items[i].Parent = annotated.Annotation; //Can be documentation or appInfo
}
}
}
}
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
private Uri ResolveSchemaLocationUri(XmlSchema enclosingSchema, string location) {
try {
return xmlResolver.ResolveUri(enclosingSchema.BaseUri, location);
}
catch {
return null;
}
}
private Stream GetSchemaEntity(Uri ruri) {
try {
return (Stream)xmlResolver.GetEntity(ruri, null, null);
}
catch {
return null;
}
}
};
#pragma warning restore 618
} // namespace System.Xml
| |
using NSubstitute;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Abstractions.Output;
using NuKeeper.Collaboration;
using NuKeeper.Commands;
using NuKeeper.GitHub;
using NuKeeper.Inspection.Logging;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using NuKeeper.Abstractions.Git;
using NuKeeper.AzureDevOps;
namespace NuKeeper.Tests.Commands
{
[TestFixture]
public class GlobalCommandTests
{
private static CollaborationFactory GetCollaborationFactory(Func<IGitDiscoveryDriver, IEnvironmentVariablesProvider, ISettingsReader> createSettingsReader)
{
var environmentVariablesProvider = Substitute.For<IEnvironmentVariablesProvider>();
var httpClientFactory = Substitute.For<IHttpClientFactory>();
httpClientFactory.CreateClient().Returns(new HttpClient());
return new CollaborationFactory(
new ISettingsReader[] { createSettingsReader(new MockedGitDiscoveryDriver(), environmentVariablesProvider) },
Substitute.For<INuKeeperLogger>(),
httpClientFactory
);
}
[Test]
public async Task ShouldCallEngineAndNotSucceedWithoutParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
var command = new GlobalCommand(engine, logger, fileSettings, collaborationFactory);
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(-1));
await engine
.DidNotReceive()
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldCallEngineAndSucceedWithRequiredGithubParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
var command = new GlobalCommand(engine, logger, fileSettings, collaborationFactory);
command.PersonalAccessToken = "testToken";
command.Include = "testRepos";
command.ApiEndpoint = "https://github.contoso.com";
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(0));
await engine
.Received(1)
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldCallEngineAndSucceedWithRequiredAzureDevOpsParams()
{
var engine = Substitute.For<ICollaborationEngine>();
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(FileSettings.Empty());
var collaborationFactory = GetCollaborationFactory((d, e) => new AzureDevOpsSettingsReader(d, e));
var command = new GlobalCommand(engine, logger, fileSettings, collaborationFactory);
command.PersonalAccessToken = "testToken";
command.Include = "testRepos";
command.ApiEndpoint = "https://dev.azure.com/org";
var status = await command.OnExecute();
Assert.That(status, Is.EqualTo(0));
await engine
.Received(1)
.Run(Arg.Any<SettingsContainer>());
}
[Test]
public async Task ShouldPopulateSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.Token, Is.Not.Null);
Assert.That(platformSettings.Token, Is.EqualTo("testToken"));
Assert.That(platformSettings.BaseApiUrl, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl.ToString(), Is.EqualTo("http://github.contoso.com/"));
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Repository, Is.Null);
Assert.That(settings.SourceControlServerSettings.OrganisationName, Is.Null);
}
[Test]
public async Task EmptyFileResultsInRequiredParams()
{
var fileSettings = FileSettings.Empty();
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.UserSettings, Is.Not.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(10));
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.Includes, Is.Not.Null);
Assert.That(settings.PackageFilters.Includes.ToString(), Is.EqualTo("testRepos"));
Assert.That(settings.BranchSettings, Is.Not.Null);
}
[Test]
public async Task EmptyFileResultsInDefaultSettings()
{
var fileSettings = FileSettings.Empty();
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.UserSettings, Is.Not.Null);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.PackageFilters.MinimumAge, Is.EqualTo(TimeSpan.FromDays(7)));
Assert.That(settings.PackageFilters.Excludes, Is.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(3));
Assert.That(settings.UserSettings.AllowedChange, Is.EqualTo(VersionChange.Major));
Assert.That(settings.UserSettings.NuGetSources, Is.Null);
Assert.That(settings.UserSettings.OutputDestination, Is.EqualTo(OutputDestination.Console));
Assert.That(settings.UserSettings.OutputFormat, Is.EqualTo(OutputFormat.Text));
Assert.That(settings.BranchSettings.BranchNameTemplate, Is.Null);
Assert.That(settings.BranchSettings.DeleteBranchAfterMerge, Is.EqualTo(true));
Assert.That(settings.SourceControlServerSettings.Scope, Is.EqualTo(ServerScope.Global));
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Null);
}
[Test]
public async Task WillReadApiFromFile()
{
var fileSettings = new FileSettings
{
Api = "http://github.fish.com/"
};
var (_, platformSettings) = await CaptureSettings(fileSettings);
Assert.That(platformSettings, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.Not.Null);
Assert.That(platformSettings.BaseApiUrl, Is.EqualTo(new Uri("http://github.fish.com/")));
}
[Test]
public async Task WillReadLabelFromFile()
{
var fileSettings = new FileSettings
{
Label = new List<string> { "testLabel" }
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.Labels, Has.Count.EqualTo(1));
Assert.That(settings.SourceControlServerSettings.Labels, Does.Contain("testLabel"));
}
[Test]
public async Task WillReadRepoFiltersFromFile()
{
var fileSettings = new FileSettings
{
IncludeRepos = "foo",
ExcludeRepos = "bar"
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.ExcludeRepos, Is.Not.Null);
Assert.That(settings.SourceControlServerSettings.IncludeRepos.ToString(), Is.EqualTo("foo"));
Assert.That(settings.SourceControlServerSettings.ExcludeRepos.ToString(), Is.EqualTo("bar"));
}
[Test]
public async Task WillReadMaxPackageUpdatesFromFile()
{
var fileSettings = new FileSettings
{
MaxPackageUpdates = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.PackageFilters.MaxPackageUpdates, Is.EqualTo(42));
}
[Test]
public async Task WillReadMaxRepoFromFile()
{
var fileSettings = new FileSettings
{
MaxRepo = 42
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.PackageFilters, Is.Not.Null);
Assert.That(settings.UserSettings.MaxRepositoriesChanged, Is.EqualTo(42));
}
[Test]
public async Task WillReadBranchNamePrefixFromFile()
{
var testTemplate = "nukeeper/MyBranch";
var fileSettings = new FileSettings
{
BranchNameTemplate = testTemplate
};
var (settings, _) = await CaptureSettings(fileSettings);
Assert.That(settings, Is.Not.Null);
Assert.That(settings.BranchSettings, Is.Not.Null);
Assert.That(settings.BranchSettings.BranchNameTemplate, Is.EqualTo(testTemplate));
}
public static async Task<(SettingsContainer settingsContainer, CollaborationPlatformSettings platformSettings)> CaptureSettings(FileSettings settingsIn)
{
var logger = Substitute.For<IConfigureLogger>();
var fileSettings = Substitute.For<IFileSettingsCache>();
fileSettings.GetSettings().Returns(settingsIn);
var collaborationFactory = GetCollaborationFactory((d, e) => new GitHubSettingsReader(d, e));
SettingsContainer settingsOut = null;
var engine = Substitute.For<ICollaborationEngine>();
await engine.Run(Arg.Do<SettingsContainer>(x => settingsOut = x));
var command = new GlobalCommand(engine, logger, fileSettings, collaborationFactory)
{
PersonalAccessToken = "testToken",
ApiEndpoint = settingsIn.Api ?? "http://github.contoso.com/",
Include = settingsIn.Include ?? "testRepos"
};
await command.OnExecute();
return (settingsOut, collaborationFactory.Settings);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using System.Diagnostics;
namespace CompactMovieManager
{
public class XMLManager
{
/// <summary>
/// Write a setting to an XML settings file.
/// </summary>
/// <param name="p_strFile">The XML settings file.</param>
/// <param name="p_strNodeStructure">The XML XPath to traverse.</param>
/// <param name="p_strAttribute">The attribute name of the final XML node element.</param>
/// <param name="p_Value">The settings value to write.</param>
public static void WriteSetting(string p_strFile, string p_strNodeStructure,
string p_strAttribute, string p_Value)
{
if (p_strFile != "")
{
if ((p_strNodeStructure != "") && (p_strAttribute != ""))
{
XmlDocument xmlDoc = new XmlDocument();
bool bFileExists = File.Exists(p_strFile);
string[] aNodes = p_strNodeStructure.Split('/');
string strMessage = "";
try
{
XmlNode xmlLastNode = null;
if (bFileExists)
{
xmlDoc.Load(p_strFile);
}
#region Add nodes if needed
try
{
foreach (string strNode in aNodes)
{
//first element ...
if (xmlLastNode == null)
{
xmlLastNode = xmlDoc.SelectSingleNode(strNode);
if (xmlLastNode == null)
{
xmlLastNode = xmlDoc.AppendChild(xmlDoc.CreateElement(strNode));
}
}
else
{
XmlNode xmlTempNode = xmlLastNode.SelectSingleNode(strNode);
if (xmlTempNode != null)
{
xmlLastNode = xmlTempNode;
}
else
{
xmlTempNode = xmlDoc.CreateElement(strNode);
xmlLastNode = xmlLastNode.AppendChild(xmlTempNode);
}
}
}
}
catch (XmlException xmlEx)
{
xmlLastNode = null;
strMessage = xmlEx.Message;
}
catch (Exception ex)
{
xmlLastNode = null;
strMessage = ex.Message;
}
#endregion
if (xmlLastNode != null)
{
#region insert attribute value
if (xmlLastNode.Attributes[p_strAttribute] == null)
{
xmlLastNode.Attributes.Append(xmlDoc.CreateAttribute(p_strAttribute));
}
xmlLastNode.Attributes[p_strAttribute].Value = p_Value;
#endregion
}
else
{
throw new Exception(strMessage);
}
xmlDoc.Save(p_strFile);
}
catch (XmlException xmlEx)
{
throw xmlEx;
}
catch (Exception ex)
{
throw ex;
}
}
else
{
throw new Exception("XML node structure or attribute not specified.");
}
}
else
{
throw new Exception("XML settings file not specified.");
}
}
protected static string _ReadSetting(string p_strFile, string p_strNodeStructure,
string p_strAttribute, ref string p_ErrorMessage)
{
if (p_strFile != "")
{
if (File.Exists(p_strFile))
{
if ((p_strNodeStructure != "") && (p_strAttribute != ""))
{
XmlDocument xmlDoc = new XmlDocument();
string[] aNodes = p_strNodeStructure.Split('/');
try
{
xmlDoc.Load(p_strFile);
XmlNode xmlLastNode = null;
foreach (string strNode in aNodes)
{
if (xmlLastNode == null)
{
xmlLastNode = xmlDoc.SelectSingleNode(strNode);
}
else
{
xmlLastNode = xmlLastNode.SelectSingleNode(strNode);
}
}
if (xmlLastNode != null)
{
if (xmlLastNode.Attributes[p_strAttribute] != null)
{
return xmlLastNode.Attributes[p_strAttribute].Value;
}
else
{
throw new Exception("Attribute: [" + p_strAttribute + "] not found.");
}
}
else
{
throw new Exception("One of the nodes in the XML XPath was not found.");
}
}
catch (XmlException xmlEx)
{
p_ErrorMessage = xmlEx.Message;
return null;
}
catch (Exception ex)
{
p_ErrorMessage = ex.Message;
return null;
}
finally
{
xmlDoc = null;
}
}
else
{
p_ErrorMessage = "XML node structure or attribute not specified.";
return null;
}
}
else
{
p_ErrorMessage = "XML settings file does not exist:\n[" + p_strFile + "]";
return null;
}
}
else
{
p_ErrorMessage = "XML settings file not specified.";
return null;
}
}
/// <summary>
/// Reads and returns a setting from an XML file.
/// </summary>
/// <param name="p_strFile">The XML settings file.</param>
/// <param name="p_strNodeStructure">The XML XPath to traverse.</param>
/// <param name="p_strAttribute">The attribute of the final XML node element.</param>
/// <returns>Return the specified setting value, or null if an error occurrs.</returns>
public static string ReadSetting(string p_strFile, string p_strNodeStructure,
string p_strAttribute)
{
string strErrorMessage = "";
return _ReadSetting(p_strFile, p_strNodeStructure,
p_strAttribute, ref strErrorMessage);
}
/// <summary>
/// Reads and returns a setting from an XML file.
/// </summary>
/// <param name="p_strFile">The XML settings file.</param>
/// <param name="p_strNodeStructure">The XML XPath to traverse.</param>
/// <param name="p_strAttribute">The attribute of the final XML node element.</param>
/// <param name="p_strMessage">The string where to store any error message generated by the method.</param>
/// <returns>Return the specified setting value, or null if an error occurrs.</returns>
public static string ReadSetting(string p_strFile, string p_strNodeStructure,
string p_strAttribute, ref string p_strMessage)
{
return _ReadSetting(p_strFile, p_strNodeStructure,
p_strAttribute, ref p_strMessage);
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitPeeringsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitPeeringsOperations
{
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified authorization from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified peering from the specified express route
/// circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a peering in the specified express route
/// circuits.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='peeringParameters'>
/// Parameters supplied to the create or update express route circuit
/// peering operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitPeering>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, ExpressRouteCircuitPeering peeringParameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all peerings in a specified express route circuit.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuitPeering>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using J2N;
using YAF.Lucene.Net.Codecs.Lucene40;
using YAF.Lucene.Net.Documents;
using YAF.Lucene.Net.Index;
using YAF.Lucene.Net.Store;
using YAF.Lucene.Net.Support;
using YAF.Lucene.Net.Util;
using YAF.Lucene.Net.Util.Packed;
using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using Document = YAF.Lucene.Net.Documents.Document;
namespace YAF.Lucene.Net.Codecs.Compressing
{
/*
* 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.
*/
/// <summary>
/// <see cref="StoredFieldsWriter"/> impl for <see cref="CompressingStoredFieldsFormat"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class CompressingStoredFieldsWriter : StoredFieldsWriter
{
// hard limit on the maximum number of documents per chunk
internal const int MAX_DOCUMENTS_PER_CHUNK = 128;
internal const int STRING = 0x00;
internal const int BYTE_ARR = 0x01;
/// <summary>
/// NOTE: This was NUMERIC_INT in Lucene
/// </summary>
internal const int NUMERIC_INT32 = 0x02;
/// <summary>
/// NOTE: This was NUMERIC_FLOAT in Lucene
/// </summary>
internal const int NUMERIC_SINGLE = 0x03;
/// <summary>
/// NOTE:This was NUMERIC_LONG in Lucene
/// </summary>
internal const int NUMERIC_INT64 = 0x04;
internal const int NUMERIC_DOUBLE = 0x05;
internal static readonly int TYPE_BITS = PackedInt32s.BitsRequired(NUMERIC_DOUBLE);
internal static readonly int TYPE_MASK = (int)PackedInt32s.MaxValue(TYPE_BITS);
internal const string CODEC_SFX_IDX = "Index";
internal const string CODEC_SFX_DAT = "Data";
internal const int VERSION_START = 0;
internal const int VERSION_BIG_CHUNKS = 1;
internal const int VERSION_CHECKSUM = 2;
internal const int VERSION_CURRENT = VERSION_CHECKSUM;
private readonly Directory directory;
private readonly string segment;
private readonly string segmentSuffix;
private CompressingStoredFieldsIndexWriter indexWriter;
private IndexOutput fieldsStream;
private readonly CompressionMode compressionMode;
private readonly Compressor compressor;
private readonly int chunkSize;
private readonly GrowableByteArrayDataOutput bufferedDocs;
private int[] numStoredFields; // number of stored fields
private int[] endOffsets; // end offsets in bufferedDocs
private int docBase; // doc ID at the beginning of the chunk
private int numBufferedDocs; // docBase + numBufferedDocs == current doc ID
/// <summary>
/// Sole constructor. </summary>
public CompressingStoredFieldsWriter(Directory directory, SegmentInfo si, string segmentSuffix, IOContext context, string formatName, CompressionMode compressionMode, int chunkSize)
{
Debug.Assert(directory != null);
this.directory = directory;
this.segment = si.Name;
this.segmentSuffix = segmentSuffix;
this.compressionMode = compressionMode;
this.compressor = compressionMode.NewCompressor();
this.chunkSize = chunkSize;
this.docBase = 0;
this.bufferedDocs = new GrowableByteArrayDataOutput(chunkSize);
this.numStoredFields = new int[16];
this.endOffsets = new int[16];
this.numBufferedDocs = 0;
bool success = false;
IndexOutput indexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION), context);
try
{
fieldsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION), context);
string codecNameIdx = formatName + CODEC_SFX_IDX;
string codecNameDat = formatName + CODEC_SFX_DAT;
CodecUtil.WriteHeader(indexStream, codecNameIdx, VERSION_CURRENT);
CodecUtil.WriteHeader(fieldsStream, codecNameDat, VERSION_CURRENT);
Debug.Assert(CodecUtil.HeaderLength(codecNameDat) == fieldsStream.GetFilePointer());
Debug.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer());
indexWriter = new CompressingStoredFieldsIndexWriter(indexStream);
indexStream = null;
fieldsStream.WriteVInt32(chunkSize);
fieldsStream.WriteVInt32(PackedInt32s.VERSION_CURRENT);
success = true;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(indexStream);
Abort();
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
try
{
IOUtils.Dispose(fieldsStream, indexWriter);
}
finally
{
fieldsStream = null;
indexWriter = null;
}
}
}
public override void StartDocument(int numStoredFields)
{
if (numBufferedDocs == this.numStoredFields.Length)
{
int newLength = ArrayUtil.Oversize(numBufferedDocs + 1, 4);
this.numStoredFields = Arrays.CopyOf(this.numStoredFields, newLength);
endOffsets = Arrays.CopyOf(endOffsets, newLength);
}
this.numStoredFields[numBufferedDocs] = numStoredFields;
++numBufferedDocs;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void FinishDocument()
{
endOffsets[numBufferedDocs - 1] = bufferedDocs.Length;
if (TriggerFlush())
{
Flush();
}
}
/// <summary>
/// NOTE: This was saveInts() in Lucene.
/// </summary>
private static void SaveInt32s(int[] values, int length, DataOutput @out)
{
Debug.Assert(length > 0);
if (length == 1)
{
@out.WriteVInt32(values[0]);
}
else
{
bool allEqual = true;
for (int i = 1; i < length; ++i)
{
if (values[i] != values[0])
{
allEqual = false;
break;
}
}
if (allEqual)
{
@out.WriteVInt32(0);
@out.WriteVInt32(values[0]);
}
else
{
long max = 0;
for (int i = 0; i < length; ++i)
{
max |= (uint)values[i];
}
int bitsRequired = PackedInt32s.BitsRequired(max);
@out.WriteVInt32(bitsRequired);
PackedInt32s.Writer w = PackedInt32s.GetWriterNoHeader(@out, PackedInt32s.Format.PACKED, length, bitsRequired, 1);
for (int i = 0; i < length; ++i)
{
w.Add(values[i]);
}
w.Finish();
}
}
}
private void WriteHeader(int docBase, int numBufferedDocs, int[] numStoredFields, int[] lengths)
{
// save docBase and numBufferedDocs
fieldsStream.WriteVInt32(docBase);
fieldsStream.WriteVInt32(numBufferedDocs);
// save numStoredFields
SaveInt32s(numStoredFields, numBufferedDocs, fieldsStream);
// save lengths
SaveInt32s(lengths, numBufferedDocs, fieldsStream);
}
private bool TriggerFlush()
{
return bufferedDocs.Length >= chunkSize || numBufferedDocs >= MAX_DOCUMENTS_PER_CHUNK; // chunks of at least chunkSize bytes
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Flush()
{
indexWriter.WriteIndex(numBufferedDocs, fieldsStream.GetFilePointer());
// transform end offsets into lengths
int[] lengths = endOffsets;
for (int i = numBufferedDocs - 1; i > 0; --i)
{
lengths[i] = endOffsets[i] - endOffsets[i - 1];
Debug.Assert(lengths[i] >= 0);
}
WriteHeader(docBase, numBufferedDocs, numStoredFields, lengths);
// compress stored fields to fieldsStream
if (bufferedDocs.Length >= 2 * chunkSize)
{
// big chunk, slice it
for (int compressed = 0; compressed < bufferedDocs.Length; compressed += chunkSize)
{
compressor.Compress(bufferedDocs.Bytes, compressed, Math.Min(chunkSize, bufferedDocs.Length - compressed), fieldsStream);
}
}
else
{
compressor.Compress(bufferedDocs.Bytes, 0, bufferedDocs.Length, fieldsStream);
}
// reset
docBase += numBufferedDocs;
numBufferedDocs = 0;
bufferedDocs.Length = 0;
}
public override void WriteField(FieldInfo info, IIndexableField field)
{
int bits = 0;
BytesRef bytes;
string @string;
// LUCENENET specific - To avoid boxing/unboxing, we don't
// call GetNumericValue(). Instead, we check the field.NumericType and then
// call the appropriate conversion method.
if (field.NumericType != NumericFieldType.NONE)
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
bits = NUMERIC_INT32;
break;
case NumericFieldType.INT64:
bits = NUMERIC_INT64;
break;
case NumericFieldType.SINGLE:
bits = NUMERIC_SINGLE;
break;
case NumericFieldType.DOUBLE:
bits = NUMERIC_DOUBLE;
break;
default:
throw new System.ArgumentException("cannot store numeric type " + field.NumericType);
}
@string = null;
bytes = null;
}
else
{
bytes = field.GetBinaryValue();
if (bytes != null)
{
bits = BYTE_ARR;
@string = null;
}
else
{
bits = STRING;
@string = field.GetStringValue();
if (@string == null)
{
throw new System.ArgumentException("field " + field.Name + " is stored but does not have BinaryValue, StringValue nor NumericValue");
}
}
}
long infoAndBits = (((long)info.Number) << TYPE_BITS) | (uint)bits;
bufferedDocs.WriteVInt64(infoAndBits);
if (bytes != null)
{
bufferedDocs.WriteVInt32(bytes.Length);
bufferedDocs.WriteBytes(bytes.Bytes, bytes.Offset, bytes.Length);
}
else if (@string != null)
{
bufferedDocs.WriteString(field.GetStringValue());
}
else
{
switch (field.NumericType)
{
case NumericFieldType.BYTE:
case NumericFieldType.INT16:
case NumericFieldType.INT32:
bufferedDocs.WriteInt32(field.GetInt32Value().Value);
break;
case NumericFieldType.INT64:
bufferedDocs.WriteInt64(field.GetInt64Value().Value);
break;
case NumericFieldType.SINGLE:
bufferedDocs.WriteInt32(BitConversion.SingleToInt32Bits(field.GetSingleValue().Value));
break;
case NumericFieldType.DOUBLE:
bufferedDocs.WriteInt64(BitConversion.DoubleToInt64Bits(field.GetDoubleValue().Value));
break;
default:
throw new Exception("Cannot get here");
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Abort()
{
IOUtils.DisposeWhileHandlingException(this);
IOUtils.DeleteFilesIgnoringExceptions(directory, IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION), IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION));
}
public override void Finish(FieldInfos fis, int numDocs)
{
if (numBufferedDocs > 0)
{
Flush();
}
else
{
Debug.Assert(bufferedDocs.Length == 0);
}
if (docBase != numDocs)
{
throw new Exception("Wrote " + docBase + " docs, finish called with numDocs=" + numDocs);
}
indexWriter.Finish(numDocs, fieldsStream.GetFilePointer());
CodecUtil.WriteFooter(fieldsStream);
Debug.Assert(bufferedDocs.Length == 0);
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override int Merge(MergeState mergeState)
{
int docCount = 0;
int idx = 0;
foreach (AtomicReader reader in mergeState.Readers)
{
SegmentReader matchingSegmentReader = mergeState.MatchingSegmentReaders[idx++];
CompressingStoredFieldsReader matchingFieldsReader = null;
if (matchingSegmentReader != null)
{
StoredFieldsReader fieldsReader = matchingSegmentReader.FieldsReader;
// we can only bulk-copy if the matching reader is also a CompressingStoredFieldsReader
if (fieldsReader != null && fieldsReader is CompressingStoredFieldsReader)
{
matchingFieldsReader = (CompressingStoredFieldsReader)fieldsReader;
}
}
int maxDoc = reader.MaxDoc;
IBits liveDocs = reader.LiveDocs;
if (matchingFieldsReader == null || matchingFieldsReader.Version != VERSION_CURRENT || matchingFieldsReader.CompressionMode != compressionMode || matchingFieldsReader.ChunkSize != chunkSize) // the way data is decompressed depends on the chunk size - means reader version is not the same as the writer version
{
// naive merge...
for (int i = NextLiveDoc(0, liveDocs, maxDoc); i < maxDoc; i = NextLiveDoc(i + 1, liveDocs, maxDoc))
{
Document doc = reader.Document(i);
AddDocument(doc, mergeState.FieldInfos);
++docCount;
mergeState.CheckAbort.Work(300);
}
}
else
{
int docID = NextLiveDoc(0, liveDocs, maxDoc);
if (docID < maxDoc)
{
// not all docs were deleted
CompressingStoredFieldsReader.ChunkIterator it = matchingFieldsReader.GetChunkIterator(docID);
int[] startOffsets = new int[0];
do
{
// go to the next chunk that contains docID
it.Next(docID);
// transform lengths into offsets
if (startOffsets.Length < it.chunkDocs)
{
startOffsets = new int[ArrayUtil.Oversize(it.chunkDocs, 4)];
}
for (int i = 1; i < it.chunkDocs; ++i)
{
startOffsets[i] = startOffsets[i - 1] + it.lengths[i - 1];
}
if (numBufferedDocs == 0 && startOffsets[it.chunkDocs - 1] < chunkSize && startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] >= chunkSize && NextDeletedDoc(it.docBase, liveDocs, it.docBase + it.chunkDocs) == it.docBase + it.chunkDocs) // no deletion in the chunk - chunk is large enough - chunk is small enough - starting a new chunk
{
Debug.Assert(docID == it.docBase);
// no need to decompress, just copy data
indexWriter.WriteIndex(it.chunkDocs, fieldsStream.GetFilePointer());
WriteHeader(this.docBase, it.chunkDocs, it.numStoredFields, it.lengths);
it.CopyCompressedData(fieldsStream);
this.docBase += it.chunkDocs;
docID = NextLiveDoc(it.docBase + it.chunkDocs, liveDocs, maxDoc);
docCount += it.chunkDocs;
mergeState.CheckAbort.Work(300 * it.chunkDocs);
}
else
{
// decompress
it.Decompress();
if (startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] != it.bytes.Length)
{
throw new CorruptIndexException("Corrupted: expected chunk size=" + startOffsets[it.chunkDocs - 1] + it.lengths[it.chunkDocs - 1] + ", got " + it.bytes.Length);
}
// copy non-deleted docs
for (; docID < it.docBase + it.chunkDocs; docID = NextLiveDoc(docID + 1, liveDocs, maxDoc))
{
int diff = docID - it.docBase;
StartDocument(it.numStoredFields[diff]);
bufferedDocs.WriteBytes(it.bytes.Bytes, it.bytes.Offset + startOffsets[diff], it.lengths[diff]);
FinishDocument();
++docCount;
mergeState.CheckAbort.Work(300);
}
}
} while (docID < maxDoc);
it.CheckIntegrity();
}
}
}
Finish(mergeState.FieldInfos, docCount);
return docCount;
}
private static int NextLiveDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return doc;
}
while (doc < maxDoc && !liveDocs.Get(doc))
{
++doc;
}
return doc;
}
private static int NextDeletedDoc(int doc, IBits liveDocs, int maxDoc)
{
if (liveDocs == null)
{
return maxDoc;
}
while (doc < maxDoc && liveDocs.Get(doc))
{
++doc;
}
return doc;
}
}
}
| |
// <copyright file="TFQMR.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra.Solvers;
using MathNet.Numerics.Properties;
namespace MathNet.Numerics.LinearAlgebra.Complex32.Solvers
{
/// <summary>
/// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver.
/// </summary>
/// <remarks>
/// <para>
/// The TFQMR algorithm was taken from: <br/>
/// Iterative methods for sparse linear systems.
/// <br/>
/// Yousef Saad
/// <br/>
/// Algorithm is described in Chapter 7, section 7.4.3, page 219
/// </para>
/// <para>
/// The example code below provides an indication of the possible use of the
/// solver.
/// </para>
/// </remarks>
public sealed class TFQMR : IIterativeSolver<Numerics.Complex32>
{
/// <summary>
/// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax
/// </summary>
/// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param>
/// <param name="residual">Residual values in <see cref="Vector"/>.</param>
/// <param name="x">Instance of the <see cref="Vector"/> x.</param>
/// <param name="b">Instance of the <see cref="Vector"/> b.</param>
static void CalculateTrueResidual(Matrix<Numerics.Complex32> matrix, Vector<Numerics.Complex32> residual, Vector<Numerics.Complex32> x, Vector<Numerics.Complex32> b)
{
// -Ax = residual
matrix.Multiply(x, residual);
residual.Multiply(-1, residual);
// residual + b
residual.Add(b, residual);
}
/// <summary>
/// Is <paramref name="number"/> even?
/// </summary>
/// <param name="number">Number to check</param>
/// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns>
static bool IsEven(int number)
{
return number % 2 == 0;
}
/// <summary>
/// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the
/// solution vector and x is the unknown vector.
/// </summary>
/// <param name="matrix">The coefficient matrix, <c>A</c>.</param>
/// <param name="input">The solution vector, <c>b</c></param>
/// <param name="result">The result vector, <c>x</c></param>
/// <param name="iterator">The iterator to use to control when to stop iterating.</param>
/// <param name="preconditioner">The preconditioner to use for approximations.</param>
public void Solve(Matrix<Numerics.Complex32> matrix, Vector<Numerics.Complex32> input, Vector<Numerics.Complex32> result, Iterator<Numerics.Complex32> iterator, IPreconditioner<Numerics.Complex32> preconditioner)
{
if (matrix.RowCount != matrix.ColumnCount)
{
throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix");
}
if (result.Count != input.Count)
{
throw new ArgumentException(Resources.ArgumentVectorsSameLength);
}
if (input.Count != matrix.RowCount)
{
throw Matrix.DimensionsDontMatch<ArgumentException>(input, matrix);
}
if (iterator == null)
{
iterator = new Iterator<Numerics.Complex32>();
}
if (preconditioner == null)
{
preconditioner = new UnitPreconditioner<Numerics.Complex32>();
}
preconditioner.Initialize(matrix);
var d = new DenseVector(input.Count);
var r = DenseVector.OfVector(input);
var uodd = new DenseVector(input.Count);
var ueven = new DenseVector(input.Count);
var v = new DenseVector(input.Count);
var pseudoResiduals = DenseVector.OfVector(input);
var x = new DenseVector(input.Count);
var yodd = new DenseVector(input.Count);
var yeven = DenseVector.OfVector(input);
// Temp vectors
var temp = new DenseVector(input.Count);
var temp1 = new DenseVector(input.Count);
var temp2 = new DenseVector(input.Count);
// Define the scalars
Numerics.Complex32 alpha = 0;
Numerics.Complex32 eta = 0;
float theta = 0;
// Initialize
var tau = (float) input.L2Norm();
Numerics.Complex32 rho = tau*tau;
// Calculate the initial values for v
// M temp = yEven
preconditioner.Approximate(yeven, temp);
// v = A temp
matrix.Multiply(temp, v);
// Set uOdd
v.CopyTo(ueven);
// Start the iteration
var iterationNumber = 0;
while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue)
{
// First part of the step, the even bit
if (IsEven(iterationNumber))
{
// sigma = (v, r)
var sigma = r.ConjugateDotProduct(v);
if (sigma.Real.AlmostEqualNumbersBetween(0, 1) && sigma.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
// alpha = rho / sigma
alpha = rho/sigma;
// yOdd = yEven - alpha * v
v.Multiply(-alpha, temp1);
yeven.Add(temp1, yodd);
// Solve M temp = yOdd
preconditioner.Approximate(yodd, temp);
// uOdd = A temp
matrix.Multiply(temp, uodd);
}
// The intermediate step which is equal for both even and
// odd iteration steps.
// Select the correct vector
var uinternal = IsEven(iterationNumber) ? ueven : uodd;
var yinternal = IsEven(iterationNumber) ? yeven : yodd;
// pseudoResiduals = pseudoResiduals - alpha * uOdd
uinternal.Multiply(-alpha, temp1);
pseudoResiduals.Add(temp1, temp2);
temp2.CopyTo(pseudoResiduals);
// d = yOdd + theta * theta * eta / alpha * d
d.Multiply(theta*theta*eta/alpha, temp);
yinternal.Add(temp, d);
// theta = ||pseudoResiduals||_2 / tau
theta = (float) pseudoResiduals.L2Norm()/tau;
var c = 1/(float) Math.Sqrt(1 + (theta*theta));
// tau = tau * theta * c
tau *= theta*c;
// eta = c^2 * alpha
eta = c*c*alpha;
// x = x + eta * d
d.Multiply(eta, temp1);
x.Add(temp1, temp2);
temp2.CopyTo(x);
// Check convergence and see if we can bail
if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue)
{
// Calculate the real values
preconditioner.Approximate(x, result);
// Calculate the true residual. Use the temp vector for that
// so that we don't pollute the pseudoResidual vector for no
// good reason.
CalculateTrueResidual(matrix, temp, result, input);
// Now recheck the convergence
if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue)
{
// We're all good now.
return;
}
}
// The odd step
if (!IsEven(iterationNumber))
{
if (rho.Real.AlmostEqualNumbersBetween(0, 1) && rho.Imaginary.AlmostEqualNumbersBetween(0, 1))
{
// FAIL HERE
iterator.Cancel();
break;
}
var rhoNew = r.ConjugateDotProduct(pseudoResiduals);
var beta = rhoNew/rho;
// Update rho for the next loop
rho = rhoNew;
// yOdd = pseudoResiduals + beta * yOdd
yodd.Multiply(beta, temp1);
pseudoResiduals.Add(temp1, yeven);
// Solve M temp = yOdd
preconditioner.Approximate(yeven, temp);
// uOdd = A temp
matrix.Multiply(temp, ueven);
// v = uEven + beta * (uOdd + beta * v)
v.Multiply(beta, temp1);
uodd.Add(temp1, temp);
temp.Multiply(beta, temp1);
ueven.Add(temp1, v);
}
// Calculate the real values
preconditioner.Approximate(x, result);
iterationNumber++;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.