context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; using UnityEngine.Networking; using UnityEngine.Rendering; namespace GLTF { public class GLTFLoader { public enum MaterialType { PbrMetallicRoughness, PbrSpecularGlossiness, CommonConstant, CommonPhong, CommonBlinn, CommonLambert } private struct MaterialCacheKey { public Material Material; public bool UseVertexColors; } public bool Multithreaded = true; public int MaximumLod = 300; public UnityEngine.Material ColorMaterial; public UnityEngine.Material NoColorMaterial; private readonly byte[] _gltfData; private GLTFRoot _root; private GameObject _lastLoadedScene; private AsyncAction asyncAction; private readonly Transform _sceneParent; private readonly Dictionary<Buffer, byte[]> _bufferCache = new Dictionary<Buffer, byte[]>(); private readonly Dictionary<MaterialCacheKey, UnityEngine.Material> _materialCache = new Dictionary<MaterialCacheKey, UnityEngine.Material>(); private readonly Dictionary<Image, Texture2D> _imageCache = new Dictionary<Image, Texture2D>(); private Dictionary<Mesh, GameObject> _meshCache = new Dictionary<Mesh, GameObject>(); private readonly Dictionary<MeshPrimitive, MeshPrimitiveAttributes> _attributesCache = new Dictionary<MeshPrimitive, MeshPrimitiveAttributes>(); private readonly Dictionary<MaterialType, Shader> _shaderCache = new Dictionary<MaterialType, Shader>(); public GLTFLoader(byte[] gltfData, Transform parent = null) { _gltfData = gltfData; _sceneParent = parent; asyncAction = new AsyncAction(); } public GameObject LastLoadedScene { get { return _lastLoadedScene; } } public void SetShaderForMaterialType(MaterialType type, Shader shader) { _shaderCache.Add(type, shader); } public IEnumerator Load(int sceneIndex = -1) { if (_root == null) { if (Multithreaded) { yield return asyncAction.RunOnWorkerThread(() => ParseGLTF(_gltfData)); } else { ParseGLTF(_gltfData); } } Scene scene; if (sceneIndex >= 0 && sceneIndex < _root.Scenes.Count) { scene = _root.Scenes[sceneIndex]; } else { scene = _root.GetDefaultScene(); } if (scene == null) { throw new Exception("No default scene in glTF file."); } if (_lastLoadedScene == null) { if (_root.Buffers != null) { foreach (var buffer in _root.Buffers) { yield return LoadBuffer(buffer); } } if (_root.Images != null) { foreach (var image in _root.Images) { yield return LoadImage(image); } } if (Multithreaded) { yield return asyncAction.RunOnWorkerThread(() => BuildMeshAttributes()); } else { BuildMeshAttributes(); } } else { _meshCache = new Dictionary<Mesh, GameObject>(); } var sceneObj = CreateScene(scene); if (_sceneParent != null) { sceneObj.transform.SetParent(_sceneParent, false); } _lastLoadedScene = sceneObj; } private void ParseGLTF(byte[] gltfData) { byte[] glbBuffer; _root = GLTFParser.ParseBinary(gltfData, out glbBuffer); if (glbBuffer != null) { _bufferCache[_root.Buffers[0]] = glbBuffer; } } private void BuildMeshAttributes() { foreach (var mesh in _root.Meshes) { foreach (var primitive in mesh.Primitives) { var attributes = primitive.BuildMeshAttributes(_bufferCache); _attributesCache[primitive] = attributes; } } } private GameObject CreateScene(Scene scene) { var sceneObj = new GameObject(scene.Name ?? "GLTFScene"); foreach (var node in scene.Nodes) { var nodeObj = CreateNode(node.Value); nodeObj.transform.SetParent(sceneObj.transform, false); } return sceneObj; } private GameObject CreateNode(Node node) { var nodeObj = new GameObject(node.Name ?? "GLTFNode"); Vector3 position; Quaternion rotation; Vector3 scale; node.GetUnityTRSProperties(out position, out rotation, out scale); nodeObj.transform.localPosition = position; nodeObj.transform.localRotation = rotation; nodeObj.transform.localScale = scale; // TODO: Add support for skin/morph targets if (node.Mesh != null) { var meshObj = FindOrCreateMeshObject(node.Mesh.Value); meshObj.transform.SetParent(nodeObj.transform, false); } /* TODO: implement camera (probably a flag to disable for VR as well) if (camera != null) { GameObject cameraObj = camera.Value.Create(); cameraObj.transform.parent = nodeObj.transform; } */ if (node.Children != null) { foreach (var child in node.Children) { var childObj = CreateNode(child.Value); childObj.transform.SetParent(nodeObj.transform, false); } } return nodeObj; } private GameObject FindOrCreateMeshObject(Mesh mesh) { GameObject meshObj; if (_meshCache.TryGetValue(mesh, out meshObj)) { return GameObject.Instantiate(meshObj); } meshObj = CreateMeshObject(mesh); _meshCache.Add(mesh, meshObj); return meshObj; } private GameObject CreateMeshObject(Mesh mesh) { var meshName = mesh.Name ?? "GLTFMesh"; var meshObj = new GameObject(meshName); foreach (var primitive in mesh.Primitives) { var primitiveObj = CreateMeshPrimitive(primitive); primitiveObj.transform.SetParent(meshObj.transform, false); } return meshObj; } private GameObject CreateMeshPrimitive(MeshPrimitive primitive) { var primitiveObj = new GameObject("Primitive"); var meshFilter = primitiveObj.AddComponent<MeshFilter>(); var attributes = _attributesCache[primitive]; var mesh = new UnityEngine.Mesh { vertices = attributes.Vertices, normals = attributes.Normals, uv = attributes.Uv, uv2 = attributes.Uv2, uv3 = attributes.Uv3, uv4 = attributes.Uv4, colors = attributes.Colors, triangles = attributes.Triangles, tangents = attributes.Tangents }; meshFilter.mesh = mesh; var meshRenderer = primitiveObj.AddComponent<MeshRenderer>(); UnityEngine.Material material = null; if (primitive.Material != null) { var materialCacheKey = new MaterialCacheKey { Material = primitive.Material.Value, UseVertexColors = attributes.Colors != null }; try { material = FindOrCreateMaterial(materialCacheKey); } catch (Exception e) { Debug.LogException(e); Debug.LogWarningFormat("Failed to create material from {0}, using default", materialCacheKey.Material.Name); } } if (material == null) { var materialCacheKey = new MaterialCacheKey { Material = new Material(), UseVertexColors = attributes.Colors != null }; material = FindOrCreateMaterial(materialCacheKey); } meshRenderer.material = material; return primitiveObj; } private UnityEngine.Material FindOrCreateMaterial(MaterialCacheKey materialKey) { UnityEngine.Material material; if (_materialCache.TryGetValue(materialKey, out material)) { return material; } material = CreateMaterial(materialKey.Material, materialKey.UseVertexColors); _materialCache.Add(materialKey, material); return material; } private UnityEngine.Material CreateMaterial(Material def, bool useVertexColors) { UnityEngine.Material material = new UnityEngine.Material(useVertexColors ? ColorMaterial : NoColorMaterial); material.shader.maximumLOD = MaximumLod; if (def.AlphaMode == AlphaMode.MASK) { material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; material.SetFloat("_Cutoff", (float)def.AlphaCutoff); } else if (def.AlphaMode == AlphaMode.BLEND) { material.SetOverrideTag("RenderType", "Transparent"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetInt("_ZWrite", 0); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; } else { material.SetOverrideTag("RenderType", "Opaque"); material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); material.SetInt("_ZWrite", 1); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = -1; } if (def.DoubleSided) { material.SetInt("_Cull", (int)CullMode.Off); } else { material.SetInt("_Cull", (int)CullMode.Back); } if (useVertexColors) { material.EnableKeyword("VERTEX_COLOR_ON"); } if (def.PbrMetallicRoughness != null) { var pbr = def.PbrMetallicRoughness; material.SetColor("_Color", pbr.BaseColorFactor); if (pbr.BaseColorTexture != null) { var texture = pbr.BaseColorTexture.Index.Value; material.SetTexture("_MainTex", _imageCache[texture.Source.Value]); } material.SetFloat("_Metallic", (float)pbr.MetallicFactor); if (pbr.MetallicRoughnessTexture != null) { var texture = pbr.MetallicRoughnessTexture.Index.Value; material.SetTexture("_MetallicRoughnessMap", _imageCache[texture.Source.Value]); } material.SetFloat("_Roughness", (float)pbr.RoughnessFactor); } if (def.CommonConstant != null) { material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor); if (def.CommonConstant.LightmapTexture != null) { material.EnableKeyword("LIGHTMAP_ON"); var texture = def.CommonConstant.LightmapTexture.Index.Value; material.SetTexture("_LightMap", _imageCache[texture.Source.Value]); material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord); } material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor); } if (def.NormalTexture != null) { var texture = def.NormalTexture.Index.Value; material.EnableKeyword("_NORMALMAP"); material.SetTexture("_BumpMap", _imageCache[texture.Source.Value]); material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale); } else { material.SetTexture("_BumpMap", null); material.DisableKeyword("_NORMALMAP"); } if (def.OcclusionTexture != null) { var texture = def.OcclusionTexture.Index; material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength); if (def.PbrMetallicRoughness != null && def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id) { material.EnableKeyword("OCC_METAL_ROUGH_ON"); } else { material.SetTexture("_OcclusionMap", _imageCache[texture.Value.Source.Value]); } } if (def.EmissiveTexture != null) { var texture = def.EmissiveTexture.Index.Value; material.EnableKeyword("_EMISSION"); material.EnableKeyword("EMISSION_MAP_ON"); material.SetTexture("_EmissionMap", _imageCache[texture.Source.Value]); material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord); } material.SetColor("_EmissionColor", def.EmissiveFactor); return material; } private const string Base64StringInitializer = "^data:[a-z-]+/[a-z-]+;base64,"; /// <summary> /// Get the absolute path to a glTF URI reference. /// </summary> /// <param name="relativePath">The relative path stored in the URI.</param> /// <returns></returns> private string AbsolutePath(string relativePath) { var uri = new Uri(relativePath); var partialPath = uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length - 1].Length); return partialPath + relativePath; } private IEnumerator LoadImage(Image image) { Texture2D texture; if (image.Uri != null) { var uri = image.Uri; Regex regex = new Regex(Base64StringInitializer); Match match = regex.Match(uri); if (match.Success) { var base64Data = uri.Substring(match.Length); var textureData = Convert.FromBase64String(base64Data); texture = new Texture2D(0, 0); texture.LoadImage(textureData); } else { var www = UnityWebRequest.Get(AbsolutePath(uri)); www.downloadHandler = new DownloadHandlerTexture(); #if UNITY_2017_2_OR_NEWER yield return www.SendWebRequest(); #else yield return www.Send(); #endif // HACK to enable mipmaps :( var tempTexture = DownloadHandlerTexture.GetContent(www); if (tempTexture != null) { texture = new Texture2D(tempTexture.width, tempTexture.height, tempTexture.format, true); texture.SetPixels(tempTexture.GetPixels()); texture.Apply(true); } else { Debug.LogFormat("{0} {1}", www.responseCode, www.url); texture = new Texture2D(16, 16); } } } else { texture = new Texture2D(0, 0); var bufferView = image.BufferView.Value; var buffer = bufferView.Buffer.Value; var bufferData = _bufferCache[buffer]; var data = new byte[bufferView.ByteLength]; System.Buffer.BlockCopy(bufferData, bufferView.ByteOffset, data, 0, data.Length); texture.LoadImage(data); } _imageCache[image] = texture; } /// <summary> /// Load the remote URI data into a byte array. /// </summary> private IEnumerator LoadBuffer(Buffer buffer) { if (buffer.Uri != null) { byte[] bufferData; var uri = buffer.Uri; Regex regex = new Regex(Base64StringInitializer); Match match = regex.Match(uri); if (match.Success) { var base64Data = uri.Substring(match.Length); bufferData = Convert.FromBase64String(base64Data); } else { var www = UnityWebRequest.Get(AbsolutePath(uri)); #if UNITY_2017_2_OR_NEWER yield return www.SendWebRequest(); #else yield return www.Send(); #endif bufferData = www.downloadHandler.data; } _bufferCache[buffer] = bufferData; } } } }
// // docfixer // // TODO: // Remove <h2...> Overview</h2> from merged docs // using System; using System.Collections.Generic; using System.Reflection; using System.IO; using System.Xml.Linq; using System.Linq; using System.Xml.XPath; using System.Xml; using System.Text; using System.Text.RegularExpressions; using HtmlAgilityPack; public partial class DocGenerator { static string DocBase = GetMostRecentDocBase (); public static bool DebugDocs; // // {0} is the DocBase // {1} is the framework name (Cocoa, GraphicsImaging, etc) without the MonoTouch/MonoMac prefix. // {2} is the TypeName // {3} is the first alternate name (for example fx=CoreAnimation sets alt=QuartzCore) // {4} is the second alternate name // {5} is the typename with 2 letters removed from the front (UIView -> View) static string [] patterns = { "{0}/{1}/Reference/{2}_Ref/Introduction/Introduction.html", "{0}/{1}/Reference/{2}/Introduction/Introduction.html", "{0}/{1}/Reference/{2}_Class/{2}/{2}.html", "{0}/{1}/Reference/{2}_Class/{2}.html", "{0}/{1}/Reference/{2}Request_Class/Reference/Reference.html", "{0}/{1}/Reference/{2}_Class/{2}ClassReference/{2}ClassReference.html", "{0}/{1}/Reference/{2}_Class/Reference/Reference.html", "{0}/{1}/Reference/{2}_Class/Reference/{5}.html", "{0}/{1}/Reference/{2}_Class/Reference/{2}.html", // UIKit/Reference/UIDevice_Class/Reference/UIDevice.html "{0}/{1}/Reference/{2}_Class/Reference.html", "{0}/{1}/Reference/{2}_ClassRef/Reference/{2}.html", "{0}/{1}/Reference/{2}_ClassRef/Reference/Reference.html", "{0}/{1}/Reference/{2}ClassRef/Reference/Reference.html", "{0}/{1}/Reference/{2}_Protocol/Introduction/Introduction.html", "{0}/{1}/Reference/{2}_Protocol/Reference/Reference.html", "{0}/{1}/Reference/{2}_Protocol/Reference/{2}.html", "{0}/{1}/Reference/{2}_Protocol/Reference.html", "{0}/{1}/Reference/{2}_Protocol/{2}/{2}.html", "{0}/{1}/Reference/{4}_Protocol/{2}/{2}.html", // UIModalViewDelegate_Protocol/UIActionSheetDelegate/UIActionSheetDelegate.html "{0}/{1}/Reference/Foundation/Classes/{2}_Class/{2}.html", "{0}/{1}/Reference/Foundation/Classes/{2}_Class/Reference/{2}.html", "{0}/{1}/Reference/Foundation/Classes/{2}_Class/Reference/Reference.html", "{0}/{1}/Reference/{2}_Class/Reference/Reference.html", "{0}/{1}/Reference/{2}_Class/Introduction/Introduction.html", "{0}/{1}/Reference/{2}Ref/Reference/Reference.html", "{0}/{1}/Reference/{2}ClassRef/{2}ClassReference/{2}ClassReference.html", "{0}/{1}/Reference/{2}_ClassReference/Reference/Reference.html", "{0}/{1}/Reference/{2}_Reference/Reference/Reference.html", // SKProduct_Reference/Reference/Reference.html "{0}/{1}/Reference/{2}/Reference/Reference.html", // SKProductsRequest/Reference/Reference.html "{0}/{1}/Reference/{2}_Ref/Reference/Reference.html", // GameKit/Reference/GKLeaderboard_Ref/Reference/Reference.html "{0}/{1}/Reference/{2}ClassReference/Reference/Reference.html", "{0}/{1}/Reference/{2}ProtocolReference/Reference/Reference.html", "{0}/{1}/Reference/{4}_Protocol/{1}/{1}.html", "{0}/{1}/Reference/{3}/Protocols/{2}_Protocol/Reference/Reference.html", "{0}/{1}/Reference/{2}_ProtocolReference/Reference/Reference.html", "{0}/{1}/Reference/{2}_Protocol/Reference/Reference.html", "{0}/iPhone/Reference/{2}_Class/{2}.html", "{0}/iPhone/Reference/{2}_Class/Reference/Reference.html", // UILocalReference // AppKit-style "{0}/{1}/Reference/{3}/Classes/{2}_Class/Reference/Reference.html", "{0}/{1}/Reference/{3}/Classes/{2}_Class/Reference/{2}.html", "{0}/{1}/Reference/{3}/{2}_h/Classes/{2}/index.html", "{0}/{3}/Reference/{2}_Protocol_iPhoneOS/Reference/Reference.html", "{0}/{3}/Reference/{2}/Reference/Reference.html", "{0}/{3}/Reference/{2}_Protocol/Reference/Reference.html", "{0}/{3}/Reference/{2}_Class/{2}/{2}.html", "{0}/{3}/Reference/{2}_ClassRef/Reference/Reference.html", "{0}/{3}/Reference/{2}_Class/Reference/Reference.html", "{0}/{3}/Reference/{2}ClassRef/Reference/Reference.html", "{0}/{3}/Reference/{2}_Class/{4}/{4}.html", "{0}/{3}/Reference/{2}_ClassRef/Reference/Reference.html", "{0}/{4}/Reference/{2}/Reference/Reference.html", "{0}/{4}/Reference/{2}/{2}_Reference.html", "{0}/{4}/Reference/{2}_Protocol/Reference/Reference.html", "{0}/{4}/Reference/{2}_Class/Introduction/Introduction.html", "{0}/{4}/Reference/{2}_Class/{2}/{2}_Reference.html", "{0}/{4}/Reference/{2}_Class/{2}_Reference.html", "{0}/{4}/Reference/{2}_Class/{2}_Ref.html", "{0}/{4}/Reference/{2}ClassRef/Reference/Reference.html", "{0}/{4}/Reference/{2}_Class/Reference/Reference.html", "{0}/{4}/Reference/{2}Ref/Reference/Reference.html", "{0}/{4}/Reference/{2}_Protocol/{2}_Reference.html" }; static Type export_attribute_type; public static string GetAppleDocFor (Type t) { string fx = t.Namespace; string alt = "", alt2 =""; if (fx.StartsWith (BaseNamespace)) fx = fx.Substring (BaseNamespace.Length+1); if (fx == "CoreWlan"){ fx = "Networking"; alt = "CoreWLanFrameworkRef"; } if (fx == "Foundation") fx = "Cocoa"; if (fx == "CoreAnimation"){ fx = "GraphicsImaging"; alt = "QuartzCore"; alt2 = "Cocoa"; } if (fx == "QuickLook"){ alt = "NetworkingInternet"; } if (fx == "EventKit"){ alt = "DataManagement"; alt2 = "EventKitUI"; } if (fx == "CoreTelephony"){ alt = "NetworkingInternet"; } if (fx == "iAd") fx = "UserExperience"; if (t.Name == "CAEAGLLayer") alt2 = "CAEGLLayer"; if (t.Name == "UIActionSheetDelegate") alt2 = "UIModalViewDelegate"; if (fx == "AppKit"){ fx = "Cocoa"; alt = "ApplicationKit"; alt2 = "AppKit"; } if (fx == "CoreImage"){ fx = "GraphicsImaging"; alt = "QuartzCoreFramework"; } if (fx == "ImageKit"){ fx = "Quartz"; alt2 = "GraphicsImaging"; alt = "QuartzCoreFramework"; } if (fx == "QTKit"){ fx = "QuickTime"; alt = "QTKitFramework"; } if (fx == "WebKit"){ fx = "Cocoa"; alt = "WebKit"; } if (fx == "PdfKit"){ fx = "GraphicsImaging"; alt = "QuartzFramework"; } foreach (string pattern in patterns){ string path = String.Format (pattern, DocBase, fx, t.Name, alt, alt2, t.Name.Substring (2)); if (File.Exists (path)) return path; } // Ignore known missing documents switch (t.Name){ case "CAAnimationDelegate": case "UITableViewSource": // This one was invented by us. return null; case "CLHeading": // This seems to be an internal Apple API, not documeted, but in the header files. return null; // public "delegate"/protocol types w/o explicit documentation case "CALayerDelegate": case "NSKeyedArchiverDelegate": case "NSKeyedUnarchiverDelegate": case "NSUrlConnectionDelegate": return null; // renames of ObjC types case "NSNetServiceDelegate": // ObjC NSNetServiceDelegateMethods [no docs] case "NSNetServiceBrowserDelegate": // ObjC NSNetServiceBrowserDelegateMethods [no docs] return null; case "UIPickerViewModel": // This was invented by us. return null; } Console.WriteLine ("NOT FOUND: {0}", t); if (DebugDocs){ Console.WriteLine ("DocBase: {0}", DocBase); foreach (string pattern in patterns){ string path = String.Format (pattern, "", fx, t.Name, alt, alt2, t.Name.Substring (2)); Console.WriteLine (" Tried: {0}", path); } } return null; } public static bool KnownIssues (string type, string selector) { // generator always generates this constructor from the NSCoding protocol if (selector == "initWithCoder:") return true; switch (type){ case "ABUnknownPersonViewControllerDelegate": switch (selector) { // Documented online, but not in the SDK docs. case "unknownPersonViewController:shouldPerformDefaultActionForPerson:property:identifier:": return true; } break; case "AVAudioSession": switch (selector) { // Documented online, but not in the SDK docs. case "delegate": return true; } break; case "CALayer": if (CAMediaTiming_Selector (selector)) return true; switch (selector) { // renamed property getter; TODO: make it grab the 'doubleSided' property docs case "isDoubleSided": // renamed property getter; TODO: make it grab the 'geometryFlipped' property docs case "isGeometryFlipped": // renamed property getter; TODO: make it grab the 'hidden' property docs case "isHidden": // renamed property getter; TODO: make it grab the 'opaque' property docs case "isOpaque": return true; } break; case "CAPropertyAnimation": switch (selector) { case "isAdditive": // TODO: additive property case "isCumulative": // TODO: cumulative property return true; } break; case "MPMoviePlayerController": switch (selector) { // Documentation online, but not locally case "play": case "stop": return true; } break; case "NSBundle": switch (selector) { // Extension method from UIKit case "loadNibNamed:owner:options:": // Extension methods from AppKit case "pathForImageResource:": case "pathForSoundResource:": return true; } break; case "NSIndexPath": // Documented in a separate file, .../NSIndexPath_UIKitAdditions/Reference/Reference.html switch (selector) { case "indexPathForRow:inSection:": case "row": case "section": return true; } break; case "UIDevice": // see TODO wrt Property handling. if (selector == "isGeneratingDeviceOrientationNotifications") return true; break; case "NSMutableUrlRequest": switch (selector) { // NSMutableUrlRequest provides setURL, but URL is provided from the // base NSUrlRequest method. This is a "wart" in our binding to make // for nicer code. case "URL": case "cachePolicy": case "timeoutInterval": case "mainDocumentURL": case "HTTPMethod": case "allHTTPHeaderFields": case "HTTPBody": case "HTTPBodyStream": case "HTTPShouldHandleCookies": return true; } break; case "NSUrlConnection": switch (selector) { // NSURLConnection adopts the NSUrlAuthenticationChallengeSender, but // docs don't mention it case "useCredential:forAuthenticationChallenge:": case "continueWithoutCredentialForAuthenticationChallenge:": case "cancelAuthenticationChallenge:": return true; } break; case "NSUserDefaults": switch (selector) { // Documentation online, but not locally case "doubleForKey:": case "setDouble:forKey:": return true; } break; case "NSValue": switch (selector) { // extension methods from various places... case "valueWithCGPoint:": case "valueWithCGRect:": case "valueWithCGSize:": case "valueWithCGAffineTransform:": case "valueWithUIEdgeInsets:": case "CGPointValue": case "CGRectValue": case "CGSizeValue": case "CGAffineTransformValue": case "UIEdgeInsetsValue": return true; } break; case "SKPaymentQueue": switch (selector) { // Documented online, but not locally case "restoreCompletedTransactions": return true; } break; case "SKPaymentTransaction": switch (selector) { // Documented online, but not locally case "originalTransaction": case "transactionDate": return true; } break; case "SKPaymentTransactionObserver": switch (selector) { // Documented online, but not locally case "paymentQueue:restoreCompletedTransactionsFailedWithError:": case "paymentQueueRestoreCompletedTransactionsFinished:": return true; } break; case "UIApplication": switch (selector) { // deprecated in iPhoneOS 3.2 case "setStatusBarHidden:animated:": return true; } break; case "UITableViewDelegate": // This is documented on a separate HTML file, deprecated file if (selector == "tableView:accessoryTypeForRowWithIndexPath:") return true; break; case "UISearchBar": // Online, but not local if (selector == "isTranslucent") return true; break; case "UISearchBarDelegate": // This was added to the 3.0 API, but was not documented. if (selector == "searchBar:shouldChangeTextInRange:replacementText:") return true; break; case "UITextField": case "UITextView": // These are from the UITextInputTraits protocol switch (selector) { case "autocapitalizationType": case "autocorrectionType": case "keyboardType": case "keyboardAppearance": case "returnKeyType": case "enablesReturnKeyAutomatically": case "isSecureTextEntry": return true; } break; case "UIImagePickerController": switch (selector) { // present online, but not locally case "allowsEditing": case "cameraOverlayView": case "cameraViewTransform": case "showsCameraControls": case "takePicture": case "videoMaximumDuration": case "videoQuality": return true; } break; case "UIImagePickerControllerDelegate": // Deprecated, but available if (selector == "imagePickerController:didFinishPickingImage:editingInfo:") return true; // Deprecated in iPhone 3.0 if (selector == "imagePickerController:didFinishPickingMediaWithInfo:") return true; break; case "UIViewController": switch (selector) { // present online, but not locally case "searchDisplayController": return true; } break; case "CLLocation": switch (selector) { // deprecated and moved into CLLocation_Class/DeprecationAppendix/AppendixADeprecatedAPI.html case "getDistanceFrom:": return true; } break; case "CLLocationManagerDelegate": // Added in 3.0, Not yet documented by apple if (selector == "locationManager:didUpdateHeading:") return true; // Added in 3.0, Not yet documented by apple if (selector == "locationManagerShouldDisplayHeadingCalibration:") return true; break; case "CLLocationManager": // Added in 3.0, but not documented if (selector == "startUpdatingHeading" || selector == "stopUpdatingHeading" || selector == "dismissHeadingCalibrationDisplay") return true; // present online, but not on local disk? if (selector == "headingFilter" || selector == "headingAvailable") return true; break; case "CAAnimation": // Not in the docs. if (selector == "willChangeValueForKey:" || selector == "didChangeValueForKey:") return true; if (CAMediaTiming_Selector (selector)) return true; break; case "NSObject": // Defined in the NSObject_UIKitAdditions/Introduction/Introduction.html instead of NSObject.html if (selector == "awakeFromNib") return true; // Kind of a hack; NSObject doesn't officially implement NSCoding, but // most types do, and it's a NOP on NSObject, so it's easier for // MonoTouch users if MonoTouch.Foundation.NSObject provides the method. if (selector == "encodeWithCoder:") return true; break; } return false; } static bool CAMediaTiming_Selector (string selector) { switch (selector) { case "autoreverses": case "beginTime": case "duration": case "fillMode": case "repeatCount": case "repeatDuration": case "speed": case "timeOffset": return true; } return false; } static bool KnownMissingReturnValue (Type type, string selector) { switch (type.Name) { case "AVAudioSession": switch (selector) { case "sharedInstance": return true; } break; case "GKPeerPickerControllerDelegate": switch (selector) { case "peerPickerController:sessionForConnectionType:": return true; } break; case "MPMediaItemArtwork": switch (selector) { case "imageWithSize:": return true; } break; case "NSCoder": switch (selector) { case "containsValueForKey:": case "decodeBoolForKey:": case "decodeDoubleForKey:": case "decodeFloatForKey:": case "decodeInt32ForKey:": case "decodeInt64ForKey:": case "decodeObject": case "decodeObjectForKey:": return true; } break; case "NSDecimalNumber": switch (selector) { case "decimalNumberByAdding:withBehavior:": case "decimalNumberBySubtracting:withBehavior:": case "decimalNumberByMultiplyingBy:withBehavior:": case "decimalNumberByDividingBy:withBehavior:": case "decimalNumberByRaisingToPower:withBehavior:": case "decimalNumberByMultiplyingByPowerOf10:": case "decimalNumberByMultiplyingByPowerOf10:withBehavior:": case "decimalNumberByRoundingAccordingToBehavior:": return true; } break; case "NSDictionary": switch (selector) { case "objectsForKeys:notFoundMarker:": return true; } break; case "NSNotification": switch (selector) { case "notificationWithName:object:": case "notificationWithName:object:userInfo:": return true; } break; case "NSUrlCredential": switch (selector) { case "credentialForTrust:": return true; } break; case "UIResponder": switch (selector) { case "resignFirstResponder": return true; } break; case "UIFont": switch (selector){ case "leading": // This one was deprecated return true; } break; case "UIImagePickerController": switch (selector){ case "allowsImageEditing": // This one was deprecated. return true; } break; } return false; } public static void ReportProblem (Type t, string docpath, string selector, string key) { Console.WriteLine (t); Console.WriteLine (" Error: did not find selector \"{0}\"", selector); Console.WriteLine (" File: {0}", docpath); Console.WriteLine (" key: {0}", key); Console.WriteLine (); } static Dictionary<string, Func<XElement, bool, object>> HtmlToMdocElementMapping = new Dictionary<string, Func<XElement, bool, object>> { { "section",(e, i) => new [] {new XElement ("para", HtmlToMdoc ((XElement)e.FirstNode))}.Concat (HtmlToMdoc (e.Nodes ().Skip (1), i)) }, { "a", (e, i) => ConvertLink (e, i) }, { "code", (e, i) => ConvertCode (e, i) }, { "div", (e, i) => HtmlToMdoc (e.Nodes (), i) }, { "em", (e, i) => new XElement ("i", HtmlToMdoc (e.Nodes (), i)) }, { "li", (e, i) => new XElement ("item", new XElement ("term", HtmlToMdoc (e.Nodes (), i))) }, { "ol", (e, i) => new XElement ("list", new XAttribute ("type", "number"), HtmlToMdoc (e.Nodes ())) }, { "p", (e, i) => new XElement ("para", HtmlToMdoc (e.Nodes (), i)) }, { "span", (e, i) => HtmlToMdoc (e.Nodes (), i) }, { "strong", (e, i) => new XElement ("i", HtmlToMdoc (e.Nodes (), i)) }, { "tt", (e, i) => new XElement ("c", HtmlToMdoc (e.Nodes (), i)) }, { "ul", (e, i) => new XElement ("list", new XAttribute ("type", "bullet"), HtmlToMdoc (e.Nodes ())) }, }; static Regex selectorInHref = new Regex ("(?<type>[^/]+)/(?<selector>[^/]+)$"); static object ConvertLink (XElement e, bool insideFormat) { var href = e.Attribute ("href"); if (href == null){ return ""; } var m = selectorInHref.Match (href.Value); if (!m.Success) return ""; var selType = m.Groups ["type"].Value; var selector = m.Groups ["selector"].Value; var type = assembly.GetTypes ().Where (t => t.Name == selType).FirstOrDefault (); if (type != null) { var typedocpath = GetMdocPath (type); if (File.Exists (typedocpath)) { XDocument typedocs; using (var f = File.OpenText (typedocpath)) typedocs = XDocument.Load (f); var member = GetMdocMember (typedocs, selector); if (member != null) return new XElement ("see", new XAttribute ("cref", CreateCref (typedocs, member))); } } if (!href.Value.StartsWith ("#")){ var r = Path.GetFullPath (Path.Combine (Path.GetDirectoryName (appledocpath), href.Value)); href.Value = r.Replace (DocBase, "http://developer.apple.com/iphone/library/documentation"); } return insideFormat ? e : new XElement ("format", new XAttribute ("type", "text/html"), e); } static string CreateCref (XDocument typedocs, XElement member) { var cref = new StringBuilder (); var memberType = member.Element ("MemberType").Value; switch (memberType) { case "Constructor": cref.Append ("C"); break; case "Event": cref.Append ("E"); break; case "Field": cref.Append ("F"); break; case "Method": cref.Append ("M"); break; case "Property": cref.Append ("P"); break; default: throw new InvalidOperationException (string.Format ("Unsupported member type '{0}' for member {1}.{2}.", memberType, typedocs.Root.Attribute ("FullName").Value, member.Attribute("MemberName").Value)); } cref.Append (":"); cref.Append (typedocs.Root.Attribute ("FullName").Value); if (memberType != "Constructor") { cref.Append ("."); cref.Append (member.Attribute ("MemberName").Value.Replace (".", "#")); } var p = member.Element ("Parameters"); if (p != null && p.Descendants ().Any ()) { cref.Append ("("); bool first = true; var ps = p.Descendants (); foreach (var pi in ps) { cref.AppendFormat ("{0}{1}", first ? "" : ",", pi.Attribute ("Type").Value); first = false; } cref.Append (")"); } return cref.ToString (); } static XElement ConvertCode (XElement e, bool insideFormat) { if (e.Value == "YES") return new XElement ("see", new XAttribute ("langword", "true")); if (e.Value == "NO") return new XElement ("see", new XAttribute ("langword", "false")); if (e.Value == "nil") return new XElement ("see", new XAttribute ("langword", "null")); return new XElement ("c", HtmlToMdoc (e.Nodes (), insideFormat)); } static IEnumerable<object> HtmlToMdoc (IEnumerable<XNode> rest) { return HtmlToMdoc (rest, false); } static IEnumerable<object> HtmlToMdoc (IEnumerable<XNode> rest, bool insideFormat) { foreach (var e in rest) yield return HtmlToMdoc (e, insideFormat); } static object HtmlToMdoc (XElement e) { return HtmlToMdoc (e, false); } static object HtmlToMdoc (XNode n, bool insideFormat) { #if false // the "cheap" "just wrap everything in <format/> w/o attempting to // translate" approach. It works...but e.g. embedded <a/> links to // members won't be converted into <see cref="..."/> links. if (!insideFormat) return new XElement ("format", new XAttribute ("type", "text/html"), n); return n; #else // Try to intelligently convert HTML into mdoc(5). object r = null; var e = n as XElement; if (e != null && HtmlToMdocElementMapping.ContainsKey (e.Name.LocalName)) r = HtmlToMdocElementMapping [e.Name.LocalName] (e, insideFormat); else if (e != null && !insideFormat) r = new XElement ("format", new XAttribute ("type", "text/html"), HtmlToMdoc (e, true)); else if (e != null) r = new XElement (e.Name, e.Attributes (), HtmlToMdoc (e.Nodes (), insideFormat)); else r = n; return r; #endif } static object HtmlToMdoc (XElement e, IEnumerable<XElement> rest) { return HtmlToMdoc (new[]{e}.Concat (rest).Cast<XNode> (), false); } class XElementDocumentOrderComparer : IComparer<XElement> { public static readonly IComparer<XElement> Default = new XElementDocumentOrderComparer (); public int Compare (XElement a, XElement b) { if (object.ReferenceEquals (a, b)) return 0; if (a.IsBefore (b)) return -1; return 1; } } static XElement FirstInDocument (params XElement[] elements) { IEnumerable<XElement> e = elements; return FirstInDocument (e); } static XElement FirstInDocument (IEnumerable<XElement> elements) { return elements .Where (e => e != null) .OrderBy (e => e, XElementDocumentOrderComparer.Default) .FirstOrDefault (); } public static object ExtractTypeOverview (XElement appledocs) { var overview = appledocs.Descendants("h2").Where(e => e.Value == "Overview").FirstOrDefault(); if (overview == null) return null; var end = FirstInDocument ( GetDocSections (appledocs) .Concat (new[]{ overview.ElementsAfterSelf ().Descendants ("hr").FirstOrDefault () })); if (end == null) return null; return HtmlToMdoc ( overview, overview.ElementsAfterSelf().Where(e => e.IsBefore(end)) ); } static IEnumerable<XElement> GetDocSections (XElement appledocs) { foreach (var e in appledocs.Descendants ("h2")) { if (e.Value == "Class Methods" || e.Value == "Instance Methods" || e.Value == "Properties") yield return e; } } public static object ExtractSummary (XElement member) { try { return HtmlToMdoc (member.ElementsAfterSelf ("p").First ()); } catch { return null; } } public static object ExtractSection (XElement member) { try { return HtmlToMdoc (member.ElementsAfterSelf ("section").First ()); } catch { return null; } } static XElement GetMemberDocEnd (XElement member) { return FirstInDocument ( member.ElementsAfterSelf ("h3").FirstOrDefault (), member.ElementsAfterSelf ("hr").FirstOrDefault ()); } static IEnumerable<XElement> ExtractSection (XElement member, string section) { return from x in member.ElementsAfterSelf ("div") let h5 = x.Descendants ("h5").FirstOrDefault (e => e.Value == section) where h5 != null from j in h5.ElementsAfterSelf () select j; #if false var docEnd = GetMemberDocEnd (member); var start = member.ElementsAfterSelf ("h5").FirstOrDefault (e => e.Value == section) ?? member.ElementsAfterSelf ("div") .SelectMany (e => e.Descendants ("h5")) .FirstOrDefault (e => e.Value == section); if (start == null || (docEnd != null && start.IsAfter (docEnd))) return null; var end = start.ElementsAfterSelf ("h5").FirstOrDefault () ?? start.ElementsAfterSelf ("div").SelectMany (e => e.Descendants ("h5")).FirstOrDefault () ?? docEnd; return end != null ? start.ElementsAfterSelf ().Where (e => e.IsBefore (end)) : start.ElementsAfterSelf (); #endif } public static IEnumerable<object> ExtractParams (XElement member) { var param = ExtractSection (member, "Parameters"); if (param == null || !param.Any ()){ return new object[0]; } return param.Elements ("dd").Select (d => HtmlToMdoc (d)); } public static object ExtractReturn (XElement member) { var e = ExtractSection (member, "Return Value"); if (e == null) return null; return HtmlToMdoc (e.Cast<XNode> ()); } public static object ExtractDiscussion (XElement member) { var discussion = from x in member.ElementsAfterSelf ("div") let h5 = x.Descendants ("h5").FirstOrDefault (e => e.Value == "Discussion") where h5 != null from j in h5.ElementsAfterSelf () select j; return HtmlToMdoc (discussion.Cast<XNode> ()); } static string GetMdocPath (Type t) { return string.Format ("{0}/{1}/{2}.xml", assembly_dir, t.Namespace, t.Name); } static XElement GetMdocMember (XDocument mdoc, string selector) { var exportAttr = BaseNamespace + ".Foundation.Export(\"" + selector + "\""; return (from m in mdoc.XPathSelectElements ("Type/Members/Member") where m.Descendants ("Attributes").Descendants ("Attribute").Descendants ("AttributeName") .Where (n => n.Value.StartsWith (exportAttr) || n.Value.StartsWith ("get: " + exportAttr) || n.Value.StartsWith ("set: " + exportAttr)).Any () select m ).FirstOrDefault (); } static string appledocpath; public static void ProcessNSO (Type t) { appledocpath = GetAppleDocFor (t); if (appledocpath == null) return; string xmldocpath = GetMdocPath (t); if (!File.Exists (xmldocpath)) { Console.WriteLine ("DOC REGEN PENDING for type: {0}", t.FullName); return; } XDocument xmldoc; using (var f = File.OpenText (xmldocpath)) xmldoc = XDocument.Load (f); //Console.WriteLine ("Opened {0}", appledocpath); var appledocs = LoadAppleDocumentation (appledocpath); var typeRemarks = xmldoc.Element ("Type").Element ("Docs").Element ("remarks"); var typeSummary = xmldoc.Element ("Type").Element ("Docs").Element ("summary"); if (typeRemarks != null || (quick_summaries && typeSummary != null)) { if (typeRemarks.Value == "To be added.") typeRemarks.Value = ""; var overview = ExtractTypeOverview (appledocs); typeRemarks.Add (overview); if (overview != null && quick_summaries){ // && typeSummary.Value == "To be added."){ foreach (var x in (System.Collections.IEnumerable) overview){ var xe = x as XElement; if (xe == null) continue; if (xe.Name == "para"){ var value = xe.Value; var dot = value.IndexOf ('.'); if (dot == -1) typeSummary.Value = value; else typeSummary.Value = value.Substring (0, dot+1); break; } } } } var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public; foreach (var method in t.GetMethods (flags).Cast<MethodBase> () .Concat(t.GetConstructors (flags).Cast<MethodBase> ())) { bool prop = false; if (method.IsSpecialName) prop = true; // Skip methods from the base class if (method.DeclaringType != t) continue; var attrs = method.GetCustomAttributes (export_attribute_type, true); if (attrs.Length == 0) continue; var selector = GetSelector (attrs [0]); bool overrides = (method.Attributes & MethodAttributes.Virtual) != 0 && (method.Attributes & MethodAttributes.NewSlot) == 0; string keyFormat = "<h3 class=\"verytight\">{0}</h3>"; string key = string.Format (keyFormat, selector); var mDoc = GetAppleMemberDocs (t, selector); //Console.WriteLine ("{0}", selector); if (mDoc == null){ // Don't report known issues if (!KnownIssues (t.Name, selector) && // don't report property setters !(prop && method.Name.StartsWith ("set_")) && // don't report overriding methods !overrides) ReportProblem (t, appledocpath, selector, key); continue; } //Console.WriteLine ("Contents at {0}", p); var summary = ExtractSummary (mDoc); if (summary == null) ReportProblem (t, appledocpath, selector, key); // // Now, plug the docs // var member = GetMdocMember (xmldoc, selector); if (member == null){ Console.WriteLine ("DOC REGEN PENDING for {0}.{1}", method.DeclaringType.Name, selector); continue; } // // Summary // var summaryNode = member.XPathSelectElement ("Docs/summary"); summaryNode.Value = ""; summaryNode.Add (summary); VerifyArgumentSemantic (mDoc, member, t, selector); // // Wipe out the value if it says "to be added" // var valueNode = member.XPathSelectElement ("Docs/value"); if (valueNode != null){ if (valueNode.Value == "To be added.") valueNode.Value = ""; } // // Merge parameters // var eParamNodes = member.XPathSelectElements ("Docs/param").GetEnumerator (); //Console.WriteLine ("{0}", selector); var eAppleParams= ExtractParams (mDoc).GetEnumerator (); for ( ; eParamNodes.MoveNext () && eAppleParams.MoveNext (); ) { eParamNodes.Current.Value = ""; eParamNodes.Current.Add (eAppleParams.Current); } // // Only extract the return value if there is a return in the type // var return_type = member.XPathSelectElement ("ReturnValue/ReturnType"); if (return_type != null && return_type.Value != "System.Void" && member.XPathSelectElement ("MemberType").Value == "Method") { //Console.WriteLine ("Scanning for return {0} {1}", t.FullName, selector); var ret = ExtractReturn (mDoc); if (ret == null && !KnownMissingReturnValue (t, selector)) Console.WriteLine ("Problem extracting a return value for type=\"{0}\" selector=\"{1}\"", t.FullName, selector); else { var retNode = prop ? member.XPathSelectElement ("Docs/value") : member.XPathSelectElement ("Docs/returns"); if (retNode != null && ret != null){ retNode.Value = ""; retNode.Add (ret); } } } var remarks = ExtractDiscussion (mDoc); if (remarks != null){ var remarksNode = member.XPathSelectElement ("Docs/remarks"); if (remarksNode.Value == "To be added.") remarksNode.Value = ""; remarksNode.Add (remarks); } } var s = new XmlWriterSettings (); s.Indent = true; s.Encoding = new UTF8Encoding (false); s.OmitXmlDeclaration = true; using (var output = File.CreateText (xmldocpath)){ var xmlw = XmlWriter.Create (output, s); xmldoc.Save (xmlw); output.WriteLine (); } } static Regex propertyAttrs = new Regex (@"^@property\((?<attrs>[^)]*)\)"); static void VerifyArgumentSemantic (XElement mDoc, XElement member, Type t, string selector) { // ArgumentSemantic validation XElement code; var codeDeclaration = mDoc.ElementsAfterSelf ("pre").FirstOrDefault (); if (codeDeclaration == null || codeDeclaration.Attribute ("class") == null || codeDeclaration.Attribute ("class").Value != "declaration" || (code = codeDeclaration.Elements ("code").FirstOrDefault ()) == null) return; var decl = code.Value; var m = propertyAttrs.Match (decl); string attrs; if (!m.Success || string.IsNullOrEmpty (attrs = m.Groups ["attrs"].Value)) return; string semantic = null; if (attrs.Contains ("assign")) semantic = "ArgumentSemantic.Assign"; else if (attrs.Contains ("copy")) semantic = "ArgumentSemantic.Copy"; else if (attrs.Contains ("retain")) semantic = "ArgumentSemantic.Retain"; if (semantic != null && !member.XPathSelectElements ("Attributes/Attribute/AttributeName").Any (a => a.Value.Contains (semantic))) { Console.WriteLine ("Missing [Export (\"{0}\", {1})] on Type={2} Member='{3}'", selector, semantic, t.FullName, member.XPathSelectElement ("MemberSignature[@Language='C#']").Attribute ("Value").Value); } } public static XElement GetAppleMemberDocs(Type t, string selector) { foreach (var appledocs in GetAppleDocumentationSources (t)) { var mDoc = appledocs.Descendants ("h3").Where (e => e.Value == selector).FirstOrDefault (); if (mDoc == null) { // Many read-only properties have an 'is' prefix on the selector // (which is removed on the docs), so try w/o the prefix, e.g. // @property(getter=isDoubleSided) BOOL doubleSided; var newSelector = char.ToLower (selector [2]) + selector.Substring (3); mDoc = appledocs.Descendants ("h3").Where (e => e.Value == newSelector).FirstOrDefault (); } if (mDoc != null) return mDoc; } return null; } public static IEnumerable<XElement> GetAppleDocumentationSources (Type t) { var path = GetAppleDocFor (t); if (path != null) yield return LoadAppleDocumentation (path); while ((t = t.BaseType) != typeof (object) && t != null) { path = GetAppleDocFor (t); if (path != null) yield return LoadAppleDocumentation (path); } } static Dictionary<string, XElement> loadedAppleDocs = new Dictionary<string, XElement> (); public static XElement LoadAppleDocumentation (string path) { XElement appledocs; if (loadedAppleDocs.TryGetValue (path, out appledocs)) return appledocs; var doc = new HtmlDocument(); doc.Load (path, Encoding.UTF8); doc.OptionOutputAsXml = true; var sw = new StringWriter (); doc.Save (sw); //doc.Save ("/tmp/foo-" + Path.GetFileName (path)); // minor global fixups var contents = sw.ToString () .Replace ("&amp;#160;", " ") .Replace ("&amp;#8211;", "-") .Replace ("&amp;#xA0;", " ") .Replace ("&amp;nbsp;", " "); // HtmlDocument wraps the <html/> with a <span/>; skip the <span/>. appledocs = XElement.Parse (contents).Elements().First(); // remove the xmlns element from everything... foreach (var e in appledocs.DescendantsAndSelf ()) { e.Name = XName.Get (e.Name.LocalName); } loadedAppleDocs [path] = appledocs; return appledocs; } static string assembly_dir; // If true, it extracts the first sentence from the remarks and sticks it in the summary. static bool quick_summaries; static void Help () { Console.WriteLine ("Usage is: docfixer [--summary] path-to-files"); } public static int Main (string [] args) { string dir = null; for (int i = 0; i < args.Length; i++){ var arg = args [i]; if (arg == "-h" || arg == "--help"){ Help (); return 0; } if (arg == "--summary"){ quick_summaries = true; continue; } dir = arg; } if (dir == null){ Help (); return 1; } var debug = Environment.GetEnvironmentVariable ("DOCFIXER"); if (File.Exists (Path.Combine (dir, "en"))){ Console.WriteLine ("The directory does not seem to be the root for documentation (missing `en' directory)"); return 1; } assembly_dir = Path.Combine (dir, "en"); Type nso = assembly.GetType (BaseNamespace + ".Foundation.NSObject"); export_attribute_type = assembly.GetType (BaseNamespace + ".Foundation.ExportAttribute"); if (nso == null || export_attribute_type == null){ Console.WriteLine ("Incomplete {0} assembly", BaseNamespace); return 1; } foreach (Type t in assembly.GetTypes ()){ if (t.IsNotPublic || t.IsNested) continue; if (debug != null && t.FullName != debug) continue; if (t == nso || t.IsSubclassOf (nso)){ // Useful to debug, uncomment, and examine one class: //if (t.Name != "CALayer") //continue; try { ProcessNSO (t); } catch { Console.WriteLine ("Problem with {0}", t.FullName); } } } return 0; } }
using System; using ChainUtils.BouncyCastle.Math.EC.Endo; using ChainUtils.BouncyCastle.Math.EC.Multiplier; using ChainUtils.BouncyCastle.Math.Field; namespace ChainUtils.BouncyCastle.Math.EC { public class ECAlgorithms { public static bool IsF2mCurve(ECCurve c) { var field = c.Field; return field.Dimension > 1 && field.Characteristic.Equals(BigInteger.Two) && field is IPolynomialExtensionField; } public static bool IsFpCurve(ECCurve c) { return c.Field.Dimension == 1; } public static ECPoint SumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { if (ps == null || ks == null || ps.Length != ks.Length || ps.Length < 1) throw new ArgumentException("point and scalar arrays should be non-null, and of equal, non-zero, length"); var count = ps.Length; switch (count) { case 1: return ps[0].Multiply(ks[0]); case 2: return SumOfTwoMultiplies(ps[0], ks[0], ps[1], ks[1]); default: break; } var p = ps[0]; var c = p.Curve; var imported = new ECPoint[count]; imported[0] = p; for (var i = 1; i < count; ++i) { imported[i] = ImportPoint(c, ps[i]); } var glvEndomorphism = c.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint(ImplSumOfMultipliesGlv(imported, ks, glvEndomorphism)); } return ValidatePoint(ImplSumOfMultiplies(imported, ks)); } public static ECPoint SumOfTwoMultiplies(ECPoint P, BigInteger a, ECPoint Q, BigInteger b) { var cp = P.Curve; Q = ImportPoint(cp, Q); // Point multiplication for Koblitz curves (using WTNAF) beats Shamir's trick if (cp is F2mCurve) { var f2mCurve = (F2mCurve) cp; if (f2mCurve.IsKoblitz) { return ValidatePoint(P.Multiply(a).Add(Q.Multiply(b))); } } var glvEndomorphism = cp.GetEndomorphism() as GlvEndomorphism; if (glvEndomorphism != null) { return ValidatePoint( ImplSumOfMultipliesGlv(new ECPoint[] { P, Q }, new BigInteger[] { a, b }, glvEndomorphism)); } return ValidatePoint(ImplShamirsTrickWNaf(P, a, Q, b)); } /* * "Shamir's Trick", originally due to E. G. Straus * (Addition chains of vectors. American Mathematical Monthly, * 71(7):806-808, Aug./Sept. 1964) * * Input: The points P, Q, scalar k = (km?, ... , k1, k0) * and scalar l = (lm?, ... , l1, l0). * Output: R = k * P + l * Q. * 1: Z <- P + Q * 2: R <- O * 3: for i from m-1 down to 0 do * 4: R <- R + R {point doubling} * 5: if (ki = 1) and (li = 0) then R <- R + P end if * 6: if (ki = 0) and (li = 1) then R <- R + Q end if * 7: if (ki = 1) and (li = 1) then R <- R + Z end if * 8: end for * 9: return R */ public static ECPoint ShamirsTrick(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { var cp = P.Curve; Q = ImportPoint(cp, Q); return ValidatePoint(ImplShamirsTrickJsf(P, k, Q, l)); } public static ECPoint ImportPoint(ECCurve c, ECPoint p) { var cp = p.Curve; if (!c.Equals(cp)) throw new ArgumentException("Point must be on the same curve"); return c.ImportPoint(p); } public static void MontgomeryTrick(ECFieldElement[] zs, int off, int len) { /* * Uses the "Montgomery Trick" to invert many field elements, with only a single actual * field inversion. See e.g. the paper: * "Fast Multi-scalar Multiplication Methods on Elliptic Curves with Precomputation Strategy Using Montgomery Trick" * by Katsuyuki Okeya, Kouichi Sakurai. */ var c = new ECFieldElement[len]; c[0] = zs[off]; var i = 0; while (++i < len) { c[i] = c[i - 1].Multiply(zs[off + i]); } var u = c[--i].Invert(); while (i > 0) { var j = off + i--; var tmp = zs[j]; zs[j] = c[i].Multiply(u); u = u.Multiply(tmp); } zs[off] = u; } /** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations, and for very small scalars. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k) { var x = k.Abs(); var q = p.Curve.Infinity; var t = x.BitLength; if (t > 0) { if (x.TestBit(0)) { q = p; } for (var i = 1; i < t; i++) { p = p.Twice(); if (x.TestBit(i)) { q = q.Add(p); } } } return k.SignValue < 0 ? q.Negate() : q; } public static ECPoint ValidatePoint(ECPoint p) { if (!p.IsValid()) throw new ArgumentException("Invalid point", "p"); return p; } internal static ECPoint ImplShamirsTrickJsf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { var curve = P.Curve; var infinity = curve.Infinity; // TODO conjugate co-Z addition (ZADDC) can return both of these var PaddQ = P.Add(Q); var PsubQ = P.Subtract(Q); var points = new ECPoint[] { Q, PsubQ, P, PaddQ }; curve.NormalizeAll(points); var table = new ECPoint[] { points[3].Negate(), points[2].Negate(), points[1].Negate(), points[0].Negate(), infinity, points[0], points[1], points[2], points[3] }; var jsf = WNafUtilities.GenerateJsf(k, l); var R = infinity; var i = jsf.Length; while (--i >= 0) { int jsfi = jsf[i]; // NOTE: The shifting ensures the sign is extended correctly int kDigit = ((jsfi << 24) >> 28), lDigit = ((jsfi << 28) >> 28); var index = 4 + (kDigit * 3) + lDigit; R = R.TwicePlus(table[index]); } return R; } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPoint Q, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); var widthP = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(k.BitLength))); var widthQ = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(l.BitLength))); var infoP = WNafUtilities.Precompute(P, widthP, true); var infoQ = WNafUtilities.Precompute(Q, widthQ, true); var preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; var preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; var preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; var preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; var wnafP = WNafUtilities.GenerateWindowNaf(widthP, k); var wnafQ = WNafUtilities.GenerateWindowNaf(widthQ, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); var width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength)))); var Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ); var infoP = WNafUtilities.GetWNafPreCompInfo(P); var infoQ = WNafUtilities.GetWNafPreCompInfo(Q); var preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; var preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; var preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; var preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; var wnafP = WNafUtilities.GenerateWindowNaf(width, k); var wnafQ = WNafUtilities.GenerateWindowNaf(width, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); } private static ECPoint ImplShamirsTrickWNaf(ECPoint[] preCompP, ECPoint[] preCompNegP, byte[] wnafP, ECPoint[] preCompQ, ECPoint[] preCompNegQ, byte[] wnafQ) { var len = System.Math.Max(wnafP.Length, wnafQ.Length); var curve = preCompP[0].Curve; var infinity = curve.Infinity; var R = infinity; var zeroes = 0; for (var i = len - 1; i >= 0; --i) { var wiP = i < wnafP.Length ? (int)(sbyte)wnafP[i] : 0; var wiQ = i < wnafQ.Length ? (int)(sbyte)wnafQ[i] : 0; if ((wiP | wiQ) == 0) { ++zeroes; continue; } var r = infinity; if (wiP != 0) { var nP = System.Math.Abs(wiP); var tableP = wiP < 0 ? preCompNegP : preCompP; r = r.Add(tableP[nP >> 1]); } if (wiQ != 0) { var nQ = System.Math.Abs(wiQ); var tableQ = wiQ < 0 ? preCompNegQ : preCompQ; r = r.Add(tableQ[nQ >> 1]); } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, BigInteger[] ks) { var count = ps.Length; var negs = new bool[count]; var infos = new WNafPreCompInfo[count]; var wnafs = new byte[count][]; for (var i = 0; i < count; ++i) { var ki = ks[i]; negs[i] = ki.SignValue < 0; ki = ki.Abs(); var width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(ki.BitLength))); infos[i] = WNafUtilities.Precompute(ps[i], width, true); wnafs[i] = WNafUtilities.GenerateWindowNaf(width, ki); } return ImplSumOfMultiplies(negs, infos, wnafs); } internal static ECPoint ImplSumOfMultipliesGlv(ECPoint[] ps, BigInteger[] ks, GlvEndomorphism glvEndomorphism) { var n = ps[0].Curve.Order; var len = ps.Length; var abs = new BigInteger[len << 1]; for (int i = 0, j = 0; i < len; ++i) { var ab = glvEndomorphism.DecomposeScalar(ks[i].Mod(n)); abs[j++] = ab[0]; abs[j++] = ab[1]; } var pointMap = glvEndomorphism.PointMap; if (glvEndomorphism.HasEfficientPointMap) { return ImplSumOfMultiplies(ps, pointMap, abs); } var pqs = new ECPoint[len << 1]; for (int i = 0, j = 0; i < len; ++i) { ECPoint p = ps[i], q = pointMap.Map(p); pqs[j++] = p; pqs[j++] = q; } return ImplSumOfMultiplies(pqs, abs); } internal static ECPoint ImplSumOfMultiplies(ECPoint[] ps, ECPointMap pointMap, BigInteger[] ks) { int halfCount = ps.Length, fullCount = halfCount << 1; var negs = new bool[fullCount]; var infos = new WNafPreCompInfo[fullCount]; var wnafs = new byte[fullCount][]; for (var i = 0; i < halfCount; ++i) { int j0 = i << 1, j1 = j0 + 1; var kj0 = ks[j0]; negs[j0] = kj0.SignValue < 0; kj0 = kj0.Abs(); var kj1 = ks[j1]; negs[j1] = kj1.SignValue < 0; kj1 = kj1.Abs(); var width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(kj0.BitLength, kj1.BitLength)))); ECPoint P = ps[i], Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMap); infos[j0] = WNafUtilities.GetWNafPreCompInfo(P); infos[j1] = WNafUtilities.GetWNafPreCompInfo(Q); wnafs[j0] = WNafUtilities.GenerateWindowNaf(width, kj0); wnafs[j1] = WNafUtilities.GenerateWindowNaf(width, kj1); } return ImplSumOfMultiplies(negs, infos, wnafs); } private static ECPoint ImplSumOfMultiplies(bool[] negs, WNafPreCompInfo[] infos, byte[][] wnafs) { int len = 0, count = wnafs.Length; for (var i = 0; i < count; ++i) { len = System.Math.Max(len, wnafs[i].Length); } var curve = infos[0].PreComp[0].Curve; var infinity = curve.Infinity; var R = infinity; var zeroes = 0; for (var i = len - 1; i >= 0; --i) { var r = infinity; for (var j = 0; j < count; ++j) { var wnaf = wnafs[j]; var wi = i < wnaf.Length ? (int)(sbyte)wnaf[i] : 0; if (wi != 0) { var n = System.Math.Abs(wi); var info = infos[j]; var table = (wi < 0 == negs[j]) ? info.PreComp : info.PreCompNeg; r = r.Add(table[n >> 1]); } } if (r == infinity) { ++zeroes; continue; } if (zeroes > 0) { R = R.TimesPow2(zeroes); zeroes = 0; } R = R.TwicePlus(r); } if (zeroes > 0) { R = R.TimesPow2(zeroes); } return R; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is used internally to create best fit behavior as per the original windows best fit behavior. // using System.Diagnostics; using System.Threading; namespace System.Text { internal sealed class InternalDecoderBestFitFallback : DecoderFallback { // Our variables internal Encoding _encoding = null; internal char[] _arrayBestFit = null; internal char _cReplacement = '?'; internal InternalDecoderBestFitFallback(Encoding encoding) { // Need to load our replacement characters table. _encoding = encoding; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new InternalDecoderBestFitFallbackBuffer(this); } // Maximum number of characters that this instance of this fallback could return public override int MaxCharCount { get { return 1; } } public override bool Equals(Object value) { InternalDecoderBestFitFallback that = value as InternalDecoderBestFitFallback; if (that != null) { return (_encoding.CodePage == that._encoding.CodePage); } return (false); } public override int GetHashCode() { return _encoding.CodePage; } } internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer { // Our variables private char _cBestFit = '\0'; private int _iCount = -1; private int _iSize; private InternalDecoderBestFitFallback _oFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Constructor public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback) { _oFallback = fallback; if (_oFallback._arrayBestFit == null) { // Lock so we don't confuse ourselves. lock (InternalSyncObject) { // Double check before we do it again. if (_oFallback._arrayBestFit == null) _oFallback._arrayBestFit = fallback._encoding.GetBestFitBytesToUnicodeData(); } } } // Fallback methods public override bool Fallback(byte[] bytesUnknown, int index) { // We expect no previous fallback in our buffer Debug.Assert(_iCount < 1, "[DecoderReplacementFallbackBuffer.Fallback] Calling fallback without a previously empty buffer"); _cBestFit = TryBestFit(bytesUnknown); if (_cBestFit == '\0') _cBestFit = _oFallback._cReplacement; _iCount = _iSize = 1; return true; } // Default version is overridden in DecoderReplacementFallback.cs public override char GetNextChar() { // We want it to get < 0 because == 0 means that the current/last character is a fallback // and we need to detect recursion. We could have a flag but we already have this counter. _iCount--; // Do we have anything left? 0 is now last fallback char, negative is nothing left if (_iCount < 0) return '\0'; // Need to get it out of the buffer. // Make sure it didn't wrap from the fast count-- path if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } // Return the best fit character return _cBestFit; } public override bool MovePrevious() { // Exception fallback doesn't have anywhere to back up to. if (_iCount >= 0) _iCount++; // Return true if we could do it. return (_iCount >= 0 && _iCount <= _iSize); } // How many characters left to output? public override int Remaining { get { return (_iCount > 0) ? _iCount : 0; } } // Clear the buffer public override unsafe void Reset() { _iCount = -1; byteStart = null; } // This version just counts the fallback and doesn't actually copy anything. internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) // Right now this has both bytes and bytes[], since we might have extra bytes, hence the // array, and we might need the index, hence the byte* { // return our replacement string Length (always 1 for InternalDecoderBestFitFallback, either // a best fit char or ? return 1; } // private helper methods private char TryBestFit(byte[] bytesCheck) { // Need to figure out our best fit character, low is beginning of array, high is 1 AFTER end of array int lowBound = 0; int highBound = _oFallback._arrayBestFit.Length; int index; char cCheck; // Check trivial case first (no best fit) if (highBound == 0) return '\0'; // If our array is too small or too big we can't check if (bytesCheck.Length == 0 || bytesCheck.Length > 2) return '\0'; if (bytesCheck.Length == 1) cCheck = unchecked((char)bytesCheck[0]); else cCheck = unchecked((char)((bytesCheck[0] << 8) + bytesCheck[1])); // Check trivial out of range case if (cCheck < _oFallback._arrayBestFit[0] || cCheck > _oFallback._arrayBestFit[highBound - 2]) return '\0'; // Binary search the array int iDiff; while ((iDiff = (highBound - lowBound)) > 6) { // Look in the middle, which is complicated by the fact that we have 2 #s for each pair, // so we don't want index to be odd because it must be word aligned. // Also note that index can never == highBound (because diff is rounded down) index = ((iDiff / 2) + lowBound) & 0xFFFE; char cTest = _oFallback._arrayBestFit[index]; if (cTest == cCheck) { // We found it Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback._arrayBestFit[index + 1]; } else if (cTest < cCheck) { // We weren't high enough lowBound = index; } else { // We weren't low enough highBound = index; } } for (index = lowBound; index < highBound; index += 2) { if (_oFallback._arrayBestFit[index] == cCheck) { // We found it Debug.Assert(index + 1 < _oFallback._arrayBestFit.Length, "[InternalDecoderBestFitFallbackBuffer.TryBestFit]Expected replacement character at end of array"); return _oFallback._arrayBestFit[index + 1]; } } // Char wasn't in our table return '\0'; } } }
// // mTouch-PDFReader library // SettingsTableVC.cs // // Copyright (c) 2012-2014 AlexanderMac(amatsibarov@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // 'Software'), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using CoreGraphics; using Foundation; using UIKit; using mTouchPDFReader.Library.Managers; using mTouchPDFReader.Library.Data.Objects; using mTouchPDFReader.Library.Data.Enums; namespace mTouchPDFReader.Library.Views.Management { public class SettingsTableVC : UITableViewController { #region Constants & Fields private const int DefaultLabelLeft = 15; private const int DefaultLabelWidth = 200; private UITableViewCell _pageTransitionStyleCell; private UITableViewCell _pageNavigationOrientationCell; private UITableViewCell _autoScaleMode; private UITableViewCell _topToolbarVisibilityCell; private UITableViewCell _bottomToolbarVisibilityCell; private UITableViewCell _zoomScaleLevelsCell; private UITableViewCell _zoomByDoubleTouchCell; private UITableViewCell _libraryReleaseDateCell; private UITableViewCell _libraryVersionCell; #endregion #region Constructors public SettingsTableVC() : base(null, null) { } #endregion #region UIViewController members public override void ViewDidLoad() { base.ViewDidLoad(); View.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; _pageTransitionStyleCell = createPageTransitionStyleCell(); _pageNavigationOrientationCell = createPageNavigationOrientationCell(); _autoScaleMode = createAutoScaleModeCell(); _topToolbarVisibilityCell = createTopToolbarVisibilityCell(); _bottomToolbarVisibilityCell = createBottomBarVisibilityCell(); _zoomScaleLevelsCell = createZoomScaleLevelsCell(); _zoomByDoubleTouchCell = createmZoomByDoubleTouchCell(); _libraryReleaseDateCell = createLibraryReleaseDateCell(); _libraryVersionCell = createLibraryVersionCell(); TableView = new UITableView(View.Bounds, UITableViewStyle.Grouped) { BackgroundView = null, AutoresizingMask = UIViewAutoresizing.All, Source = new DataSource(this) }; } #endregion #region Create controls helpers private UITableViewCell createCell(string id) { var cell = new UITableViewCell(UITableViewCellStyle.Default, id) { AutoresizingMask = UIViewAutoresizing.All, BackgroundColor = UIColor.White, SelectionStyle = UITableViewCellSelectionStyle.None }; return cell; } private UILabel createTitleLabelControl(string title) { var label = new UILabel(new CGRect(DefaultLabelLeft, 15, DefaultLabelWidth, 20)) { AutoresizingMask = UIViewAutoresizing.All, BackgroundColor = UIColor.Clear, Text = title }; return label; } private UILabel createValueLabelControl(CGRect cellRect, string title) { const int width = 150; var label = new UILabel(new CGRect(cellRect.Width - DefaultLabelLeft - width, 15, width, 20)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin, BackgroundColor = UIColor.Clear, TextAlignment = UITextAlignment.Right, Text = title }; return label; } private UISegmentedControl createSegmentControl(CGRect cellRect, string[] values, int width) { var seg = new UISegmentedControl(new CGRect(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin }; for (int i = 0; i < values.Length; i++) { seg.InsertSegment(values [i], i, false); } return seg; } private UISwitch createSwitchControl(CGRect cellRect, string[] values) { const int width = 50; var ctrl = new UISwitch(new CGRect(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin }; return ctrl; } private UISlider createSliderControl(CGRect cellRect, int minValue, int maxValue) { const int width = 100; var slider = new UISlider(new CGRect(cellRect.Width - DefaultLabelLeft - width, 5, width, 30)) { AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin, MinValue = minValue, MaxValue = maxValue }; return slider; } #endregion #region Create cells private UITableViewCell createPageTransitionStyleCell() { var cell = createCell("PageTransitionStyleCell"); var label = createTitleLabelControl("Transition style".t()); var seg = createSegmentControl(cell.Frame, new[] { "Curl".t(), "Scroll".t() }, 100); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.PageTransitionStyle; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.PageTransitionStyle = (UIPageViewControllerTransitionStyle)(long)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createPageNavigationOrientationCell() { var cell = createCell("PageNavigationOrientationCell"); var label = createTitleLabelControl("Navigation orientation".t()); var seg = createSegmentControl(cell.Frame, new[] { "Horizontal".t(), "Vertical".t() }, 100); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.PageTransitionStyle; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.PageNavigationOrientation = (UIPageViewControllerNavigationOrientation)(long)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createTopToolbarVisibilityCell() { var cell = createCell("TopToolbarVisibilityCell"); var label = createTitleLabelControl("Top Toolbar".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.TopToolbarVisible, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.TopToolbarVisible = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createBottomBarVisibilityCell() { var cell = createCell("BottomToolbarVisibilityCell"); var label = createTitleLabelControl("Bottom Toolbar".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.BottomToolbarVisible, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.BottomToolbarVisible = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createAutoScaleModeCell() { var cell = createCell("AutoScaleModelCell"); var label = createTitleLabelControl("Auto scale mode".t()); var seg = createSegmentControl(cell.Frame, new[] { "Auto width".t(), "Auto height".t() }, 150); seg.SelectedSegment = (int)MgrAccessor.SettingsMgr.Settings.AutoScaleMode; seg.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.AutoScaleMode = (AutoScaleModes)(long)seg.SelectedSegment; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(seg); return cell; } private UITableViewCell createZoomScaleLevelsCell() { var cell = createCell("ZoomScaleLevelsCell"); var label = createTitleLabelControl("Zoom scale levels".t()); var slider = createSliderControl(cell.Frame, Settings.MinZoomScaleLevels, Settings.MaxZoomScaleLevels); slider.SetValue(MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels, false); slider.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.ZoomScaleLevels = (int)slider.Value; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(slider); return cell; } private UITableViewCell createmZoomByDoubleTouchCell() { var cell = createCell("ZoomByDoubleTouchCell"); var label = createTitleLabelControl("Scale by double click".t()); var switchCtrl = createSwitchControl(cell.Frame, new[] { "Yes".t(), "No".t() }); switchCtrl.SetState(MgrAccessor.SettingsMgr.Settings.AllowZoomByDoubleTouch, false); switchCtrl.ValueChanged += delegate { MgrAccessor.SettingsMgr.Settings.AllowZoomByDoubleTouch = switchCtrl.On; MgrAccessor.SettingsMgr.Save(); }; cell.AddSubview(label); cell.AddSubview(switchCtrl); return cell; } private UITableViewCell createLibraryReleaseDateCell() { var cell = createCell("LibraryReleaseDateCell"); var label = createTitleLabelControl("Release date".t()); var labelInfo = createValueLabelControl(cell.Frame, MgrAccessor.SettingsMgr.Settings.LibraryReleaseDate.ToShortDateString()); cell.AddSubview(label); cell.AddSubview(labelInfo); return cell; } private UITableViewCell createLibraryVersionCell() { var cell = createCell("LibraryVersionCell"); var label = createTitleLabelControl("Version".t()); var labelInfo = createValueLabelControl(cell.Frame, MgrAccessor.SettingsMgr.Settings.LibraryVersion); cell.AddSubview(label); cell.AddSubview(labelInfo); return cell; } #endregion #region Table DataSource protected class DataSource : UITableViewSource { private const int SectionsCount = 4; private readonly int[] RowsInSections = new[] { 2, 2, 3, 2 }; private readonly string[] SectionTitles = new[] { "Transition style".t(), "Visibility".t(), "Scale".t(), "Library information".t() }; private readonly SettingsTableVC _vc; public DataSource(SettingsTableVC vc) { _vc = vc; } public override nint NumberOfSections(UITableView tableView) { return SectionsCount; } public override nint RowsInSection(UITableView tableview, nint section) { return RowsInSections[section]; } public override string TitleForHeader(UITableView tableView, nint section) { return SectionTitles[section]; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { switch (indexPath.Section) { case 0: switch (indexPath.Row) { case 0: return _vc._pageTransitionStyleCell; case 1: return _vc._pageNavigationOrientationCell; } break; case 1: switch (indexPath.Row) { case 0: return _vc._topToolbarVisibilityCell; case 1: return _vc._bottomToolbarVisibilityCell; } break; case 2: switch (indexPath.Row) { case 0: return _vc._autoScaleMode; case 1: return _vc._zoomScaleLevelsCell; case 2: return _vc._zoomByDoubleTouchCell; } break; case 3: switch (indexPath.Row) { case 0: return _vc._libraryReleaseDateCell; case 1: return _vc._libraryVersionCell; } break; } return null; } } #endregion } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class RadioGroup : android.widget.LinearLayout { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static RadioGroup() { InitJNI(); } protected RadioGroup(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class LayoutParams : android.widget.LinearLayout.LayoutParams { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static LayoutParams() { InitJNI(); } protected LayoutParams(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _setBaseAttributes11717; protected override void setBaseAttributes(android.content.res.TypedArray arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.LayoutParams._setBaseAttributes11717, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._setBaseAttributes11717, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _LayoutParams11718; public LayoutParams(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._LayoutParams11718, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11719; public LayoutParams(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._LayoutParams11719, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11720; public LayoutParams(int arg0, int arg1, float arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._LayoutParams11720, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11721; public LayoutParams(android.view.ViewGroup.LayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._LayoutParams11721, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _LayoutParams11722; public LayoutParams(android.view.ViewGroup.MarginLayoutParams arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.LayoutParams.staticClass, global::android.widget.RadioGroup.LayoutParams._LayoutParams11722, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.LayoutParams.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup$LayoutParams")); global::android.widget.RadioGroup.LayoutParams._setBaseAttributes11717 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "setBaseAttributes", "(Landroid/content/res/TypedArray;II)V"); global::android.widget.RadioGroup.LayoutParams._LayoutParams11718 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.RadioGroup.LayoutParams._LayoutParams11719 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(II)V"); global::android.widget.RadioGroup.LayoutParams._LayoutParams11720 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(IIF)V"); global::android.widget.RadioGroup.LayoutParams._LayoutParams11721 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.RadioGroup.LayoutParams._LayoutParams11722 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.LayoutParams.staticClass, "<init>", "(Landroid/view/ViewGroup$MarginLayoutParams;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.widget.RadioGroup.OnCheckedChangeListener_))] public interface OnCheckedChangeListener : global::MonoJavaBridge.IJavaObject { void onCheckedChanged(android.widget.RadioGroup arg0, int arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.widget.RadioGroup.OnCheckedChangeListener))] public sealed partial class OnCheckedChangeListener_ : java.lang.Object, OnCheckedChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static OnCheckedChangeListener_() { InitJNI(); } internal OnCheckedChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _onCheckedChanged11723; void android.widget.RadioGroup.OnCheckedChangeListener.onCheckedChanged(android.widget.RadioGroup arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.OnCheckedChangeListener_._onCheckedChanged11723, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.OnCheckedChangeListener_.staticClass, global::android.widget.RadioGroup.OnCheckedChangeListener_._onCheckedChanged11723, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.OnCheckedChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup$OnCheckedChangeListener")); global::android.widget.RadioGroup.OnCheckedChangeListener_._onCheckedChanged11723 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.OnCheckedChangeListener_.staticClass, "onCheckedChanged", "(Landroid/widget/RadioGroup;I)V"); } } internal static global::MonoJavaBridge.MethodId _check11724; public virtual void check(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._check11724, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._check11724, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _addView11725; public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._addView11725, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._addView11725, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _onFinishInflate11726; protected override void onFinishInflate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._onFinishInflate11726); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._onFinishInflate11726); } internal static global::MonoJavaBridge.MethodId _checkLayoutParams11727; protected override bool checkLayoutParams(android.view.ViewGroup.LayoutParams arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.RadioGroup._checkLayoutParams11727, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._checkLayoutParams11727, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnHierarchyChangeListener11728; public override void setOnHierarchyChangeListener(android.view.ViewGroup.OnHierarchyChangeListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._setOnHierarchyChangeListener11728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._setOnHierarchyChangeListener11728, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _generateLayoutParams11729; public virtual new global::android.widget.RadioGroup.LayoutParams generateLayoutParams(android.util.AttributeSet arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RadioGroup._generateLayoutParams11729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.RadioGroup.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._generateLayoutParams11729, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.widget.RadioGroup.LayoutParams; } internal static global::MonoJavaBridge.MethodId _generateDefaultLayoutParams11730; protected override global::android.widget.LinearLayout.LayoutParams generateDefaultLayoutParams() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.widget.RadioGroup._generateDefaultLayoutParams11730)) as android.widget.LinearLayout.LayoutParams; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._generateDefaultLayoutParams11730)) as android.widget.LinearLayout.LayoutParams; } internal static global::MonoJavaBridge.MethodId _setOnCheckedChangeListener11731; public virtual void setOnCheckedChangeListener(android.widget.RadioGroup.OnCheckedChangeListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._setOnCheckedChangeListener11731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._setOnCheckedChangeListener11731, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCheckedRadioButtonId11732; public virtual int getCheckedRadioButtonId() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.RadioGroup._getCheckedRadioButtonId11732); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._getCheckedRadioButtonId11732); } internal static global::MonoJavaBridge.MethodId _clearCheck11733; public virtual void clearCheck() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.RadioGroup._clearCheck11733); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._clearCheck11733); } internal static global::MonoJavaBridge.MethodId _RadioGroup11734; public RadioGroup(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._RadioGroup11734, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _RadioGroup11735; public RadioGroup(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.RadioGroup.staticClass, global::android.widget.RadioGroup._RadioGroup11735, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.RadioGroup.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/RadioGroup")); global::android.widget.RadioGroup._check11724 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "check", "(I)V"); global::android.widget.RadioGroup._addView11725 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V"); global::android.widget.RadioGroup._onFinishInflate11726 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "onFinishInflate", "()V"); global::android.widget.RadioGroup._checkLayoutParams11727 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "checkLayoutParams", "(Landroid/view/ViewGroup$LayoutParams;)Z"); global::android.widget.RadioGroup._setOnHierarchyChangeListener11728 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "setOnHierarchyChangeListener", "(Landroid/view/ViewGroup$OnHierarchyChangeListener;)V"); global::android.widget.RadioGroup._generateLayoutParams11729 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "generateLayoutParams", "(Landroid/util/AttributeSet;)Landroid/widget/RadioGroup$LayoutParams;"); global::android.widget.RadioGroup._generateDefaultLayoutParams11730 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "generateDefaultLayoutParams", "()Landroid/widget/LinearLayout$LayoutParams;"); global::android.widget.RadioGroup._setOnCheckedChangeListener11731 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "setOnCheckedChangeListener", "(Landroid/widget/RadioGroup$OnCheckedChangeListener;)V"); global::android.widget.RadioGroup._getCheckedRadioButtonId11732 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "getCheckedRadioButtonId", "()I"); global::android.widget.RadioGroup._clearCheck11733 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "clearCheck", "()V"); global::android.widget.RadioGroup._RadioGroup11734 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.RadioGroup._RadioGroup11735 = @__env.GetMethodIDNoThrow(global::android.widget.RadioGroup.staticClass, "<init>", "(Landroid/content/Context;)V"); } } }
#region PDFsharp Charting - A .NET charting library based on PDFsharp // // Authors: // Niklas Schneider // // 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 PdfSharp.Drawing; namespace PdfSharp.Charting.Renderers { /// <summary> /// Represents a Y axis renderer used for charts of type Column2D or Line. /// </summary> internal class VerticalYAxisRenderer : YAxisRenderer { /// <summary> /// Initializes a new instance of the VerticalYAxisRenderer class with the /// specified renderer parameters. /// </summary> internal VerticalYAxisRenderer(RendererParameters parms) : base(parms) { } /// <summary> /// Returns a initialized rendererInfo based on the Y axis. /// </summary> internal override RendererInfo Init() { Chart chart = (Chart)_rendererParms.DrawingItem; XGraphics gfx = _rendererParms.Graphics; AxisRendererInfo yari = new AxisRendererInfo(); yari._axis = chart._yAxis; InitScale(yari); if (yari._axis != null) { ChartRendererInfo cri = (ChartRendererInfo)_rendererParms.RendererInfo; InitTickLabels(yari, cri.DefaultFont); InitAxisTitle(yari, cri.DefaultFont); InitAxisLineFormat(yari); InitGridlines(yari); } return yari; } /// <summary> /// Calculates the space used for the Y axis. /// </summary> internal override void Format() { AxisRendererInfo yari = ((ChartRendererInfo)_rendererParms.RendererInfo).yAxisRendererInfo; if (yari._axis != null) { XGraphics gfx = _rendererParms.Graphics; XSize size = new XSize(0, 0); // height of all ticklabels double yMin = yari.MinimumScale; double yMax = yari.MaximumScale; double yMajorTick = yari.MajorTick; double lineHeight = Double.MinValue; XSize labelSize = new XSize(0, 0); for (double y = yMin; y <= yMax; y += yMajorTick) { string str = y.ToString(yari.TickLabelsFormat); labelSize = gfx.MeasureString(str, yari.TickLabelsFont); size.Height += labelSize.Height; size.Width = Math.Max(size.Width, labelSize.Width); lineHeight = Math.Max(lineHeight, labelSize.Height); } // add space for tickmarks size.Width += yari.MajorTickMarkWidth * 1.5; // Measure axis title XSize titleSize = new XSize(0, 0); if (yari._axisTitleRendererInfo != null) { RendererParameters parms = new RendererParameters(); parms.Graphics = gfx; parms.RendererInfo = yari; AxisTitleRenderer atr = new AxisTitleRenderer(parms); atr.Format(); titleSize.Height = yari._axisTitleRendererInfo.Height; titleSize.Width = yari._axisTitleRendererInfo.Width; } yari.Height = Math.Max(size.Height, titleSize.Height); yari.Width = size.Width + titleSize.Width; yari.InnerRect = yari.Rect; yari.InnerRect.Y += yari.TickLabelsFont.Height / 2; yari.LabelSize = labelSize; } } /// <summary> /// Draws the vertical Y axis. /// </summary> internal override void Draw() { AxisRendererInfo yari = ((ChartRendererInfo)_rendererParms.RendererInfo).yAxisRendererInfo; double yMin = yari.MinimumScale; double yMax = yari.MaximumScale; double yMajorTick = yari.MajorTick; double yMinorTick = yari.MinorTick; XMatrix matrix = new XMatrix(); matrix.TranslatePrepend(-yari.InnerRect.X, yMax); matrix.Scale(1, yari.InnerRect.Height / (yMax - yMin), XMatrixOrder.Append); matrix.ScalePrepend(1, -1); // mirror horizontal matrix.Translate(yari.InnerRect.X, yari.InnerRect.Y, XMatrixOrder.Append); // Draw axis. // First draw tick marks, second draw axis. double majorTickMarkStart = 0, majorTickMarkEnd = 0, minorTickMarkStart = 0, minorTickMarkEnd = 0; GetTickMarkPos(yari, ref majorTickMarkStart, ref majorTickMarkEnd, ref minorTickMarkStart, ref minorTickMarkEnd); XGraphics gfx = _rendererParms.Graphics; LineFormatRenderer lineFormatRenderer = new LineFormatRenderer(gfx, yari.LineFormat); LineFormatRenderer minorTickMarkLineFormat = new LineFormatRenderer(gfx, yari.MinorTickMarkLineFormat); LineFormatRenderer majorTickMarkLineFormat = new LineFormatRenderer(gfx, yari.MajorTickMarkLineFormat); XPoint[] points = new XPoint[2]; // Draw minor tick marks. if (yari.MinorTickMark != TickMarkType.None) { for (double y = yMin + yMinorTick; y < yMax; y += yMinorTick) { points[0].X = minorTickMarkStart; points[0].Y = y; points[1].X = minorTickMarkEnd; points[1].Y = y; matrix.TransformPoints(points); minorTickMarkLineFormat.DrawLine(points[0], points[1]); } } double lineSpace = yari.TickLabelsFont.GetHeight(); // old: yari.TickLabelsFont.GetHeight(gfx); int cellSpace = yari.TickLabelsFont.FontFamily.GetLineSpacing(yari.TickLabelsFont.Style); double xHeight = yari.TickLabelsFont.Metrics.XHeight; XSize labelSize = new XSize(0, 0); labelSize.Height = lineSpace * xHeight / cellSpace; int countTickLabels = (int)((yMax - yMin) / yMajorTick) + 1; for (int i = 0; i < countTickLabels; ++i) { double y = yMin + yMajorTick * i; string str = y.ToString(yari.TickLabelsFormat); labelSize.Width = gfx.MeasureString(str, yari.TickLabelsFont).Width; // Draw major tick marks. if (yari.MajorTickMark != TickMarkType.None) { labelSize.Width += yari.MajorTickMarkWidth * 1.5; points[0].X = majorTickMarkStart; points[0].Y = y; points[1].X = majorTickMarkEnd; points[1].Y = y; matrix.TransformPoints(points); majorTickMarkLineFormat.DrawLine(points[0], points[1]); } else labelSize.Width += SpaceBetweenLabelAndTickmark; // Draw label text. XPoint[] layoutText = new XPoint[1]; layoutText[0].X = yari.InnerRect.X + yari.InnerRect.Width - labelSize.Width; layoutText[0].Y = y; matrix.TransformPoints(layoutText); layoutText[0].Y += labelSize.Height / 2; // Center text vertically. gfx.DrawString(str, yari.TickLabelsFont, yari.TickLabelsBrush, layoutText[0]); } // Draw axis. if (yari.LineFormat != null && yari.LineFormat.Width > 0) { points[0].X = yari.InnerRect.X + yari.InnerRect.Width; points[0].Y = yMin; points[1].X = yari.InnerRect.X + yari.InnerRect.Width; points[1].Y = yMax; matrix.TransformPoints(points); if (yari.MajorTickMark != TickMarkType.None) { // yMax is at the upper side of the axis points[1].Y -= yari.LineFormat.Width / 2; points[0].Y += yari.LineFormat.Width / 2; } lineFormatRenderer.DrawLine(points[0], points[1]); } // Draw axis title if (yari._axisTitleRendererInfo != null && yari._axisTitleRendererInfo.AxisTitleText != "") { RendererParameters parms = new RendererParameters(); parms.Graphics = gfx; parms.RendererInfo = yari; double width = yari._axisTitleRendererInfo.Width; yari._axisTitleRendererInfo.Rect = yari.InnerRect; yari._axisTitleRendererInfo.Width = width; AxisTitleRenderer atr = new AxisTitleRenderer(parms); atr.Draw(); } } /// <summary> /// Calculates all values necessary for scaling the axis like minimum/maximum scale or /// minor/major tick. /// </summary> private void InitScale(AxisRendererInfo rendererInfo) { double yMin, yMax; CalcYAxis(out yMin, out yMax); FineTuneYAxis(rendererInfo, yMin, yMax); rendererInfo.MajorTickMarkWidth = DefaultMajorTickMarkWidth; rendererInfo.MinorTickMarkWidth = DefaultMinorTickMarkWidth; } /// <summary> /// Gets the top and bottom position of the major and minor tick marks depending on the /// tick mark type. /// </summary> private void GetTickMarkPos(AxisRendererInfo rendererInfo, ref double majorTickMarkStart, ref double majorTickMarkEnd, ref double minorTickMarkStart, ref double minorTickMarkEnd) { double majorTickMarkWidth = rendererInfo.MajorTickMarkWidth; double minorTickMarkWidth = rendererInfo.MinorTickMarkWidth; XRect rect = rendererInfo.Rect; switch (rendererInfo.MajorTickMark) { case TickMarkType.Inside: majorTickMarkStart = rect.X + rect.Width; majorTickMarkEnd = rect.X + rect.Width + majorTickMarkWidth; break; case TickMarkType.Outside: majorTickMarkStart = rect.X + rect.Width; majorTickMarkEnd = rect.X + rect.Width - majorTickMarkWidth; break; case TickMarkType.Cross: majorTickMarkStart = rect.X + rect.Width - majorTickMarkWidth; majorTickMarkEnd = rect.X + rect.Width + majorTickMarkWidth; break; //TickMarkType.None: default: majorTickMarkStart = 0; majorTickMarkEnd = 0; break; } switch (rendererInfo.MinorTickMark) { case TickMarkType.Inside: minorTickMarkStart = rect.X + rect.Width; minorTickMarkEnd = rect.X + rect.Width + minorTickMarkWidth; break; case TickMarkType.Outside: minorTickMarkStart = rect.X + rect.Width; minorTickMarkEnd = rect.X + rect.Width - minorTickMarkWidth; break; case TickMarkType.Cross: minorTickMarkStart = rect.X + rect.Width - minorTickMarkWidth; minorTickMarkEnd = rect.X + rect.Width + minorTickMarkWidth; break; //TickMarkType.None: default: minorTickMarkStart = 0; minorTickMarkEnd = 0; break; } } /// <summary> /// Determines the smallest and the largest number from all series of the chart. /// </summary> protected virtual void CalcYAxis(out double yMin, out double yMax) { yMin = double.MaxValue; yMax = double.MinValue; foreach (Series series in ((Chart)_rendererParms.DrawingItem).SeriesCollection) { foreach (Point point in series.Elements) { if (!double.IsNaN(point._value)) { yMin = Math.Min(yMin, point.Value); yMax = Math.Max(yMax, point.Value); } } } } } }
// Windows.cs (c) 2003 Kari Laitinen // 24.05.2003 File created. // 11.12.2003 Last modification. // NOTE: As this is an educational program, the classes defined // here are not safe for all kinds of uses. If you try to define // very large or very small windows, or put long texts inside // the windows, the classes may not work properly. using System ; class Window { protected const int MAXIMUM_WINDOW_WIDTH = 78 ; protected const int MAXIMUM_WINDOW_HEIGHT = 22 ; protected char[,] window_contents ; protected int window_width = MAXIMUM_WINDOW_WIDTH ; protected int window_height = MAXIMUM_WINDOW_HEIGHT ; protected char background_character = ' ' ; public Window() { // Data members are initialized with the above values // before this default constructor is executed. window_contents = new char [ window_width, window_height ] ; fill_with_character( background_character ) ; } public Window( int desired_window_width, int desired_window_height, char given_background_character ) { window_width = desired_window_width ; window_height = desired_window_height ; background_character = given_background_character ; window_contents = new char [ window_width, window_height ] ; fill_with_character( background_character ) ; } public void fill_with_character( char filling_character ) { for ( int row_index = 0 ; row_index < window_height ; row_index ++ ) { for ( int column_index = 0 ; column_index < window_width ; column_index ++ ) { window_contents[ column_index, row_index ] = filling_character ; } } } public void print() { Console.Write( "\n" ) ; for ( int row_index = 0 ; row_index < window_height ; row_index ++ ) { for ( int column_index = 0 ; column_index < window_width ; column_index ++ ) { Console.Write( window_contents[ column_index, row_index ] ) ; } Console.Write( "\n" ) ; } } public void move( int destination_x_index, int destination_y_index, Window another_window ) { int source_y_index = 0 ; while ( source_y_index < another_window.window_height ) { if ( destination_y_index >= 0 && destination_y_index < window_height ) { int source_x_index = 0 ; int saved_destination_x_index = destination_x_index ; while ( source_x_index < another_window.window_width ) { if ( destination_x_index >= 0 && destination_x_index < window_width ) { window_contents [ destination_x_index, destination_y_index ] = another_window.window_contents[ source_x_index, source_y_index ] ; } source_x_index ++ ; destination_x_index ++ ; } destination_x_index = saved_destination_x_index ; } source_y_index ++ ; destination_y_index ++ ; } } } class FrameWindow : Window { public FrameWindow() : this( 40, 10 ) // Calling the other constructor below. { } public FrameWindow( int desired_window_width, int desired_window_height ) : base( desired_window_width, desired_window_height, '|' ) { Window horizontal_frames = new Window( window_width - 2, window_height, '-' ) ; Window spaces_inside_window = new Window( window_width - 2, window_height - 2, ' '); move( 1, 0, horizontal_frames ) ; move( 1, 1, spaces_inside_window ) ; } } class TextWindow : FrameWindow { protected string text_inside_window ; protected void embed_text_in_window() { int text_length = text_inside_window.Length ; int text_row = window_height / 2 ; int text_start_column = (window_width - text_length) / 2 ; for ( int character_index = 0 ; character_index < text_length ; character_index ++ ) { window_contents [ text_start_column + character_index, text_row ] = text_inside_window[ character_index ] ; } } public TextWindow( int desired_window_width, int desired_window_height, string given_line_of_text ) : base( desired_window_width, desired_window_height ) { text_inside_window = given_line_of_text ; embed_text_in_window() ; } public void change_text( string new_line_of_text ) { text_inside_window = new_line_of_text ; embed_text_in_window() ; } } class DecoratedTextWindow : TextWindow { public DecoratedTextWindow( int desired_window_width, int desired_window_height, string given_line_of_text ) : base( desired_window_width, desired_window_height, given_line_of_text ) { Window decoration_frame = new Window( desired_window_width, desired_window_height, '*' ) ; TextWindow window_inside_window = new TextWindow( desired_window_width - 2, desired_window_height - 2, given_line_of_text ) ; decoration_frame.move( 1, 1, window_inside_window ) ; move( 0, 0, decoration_frame ) ; } } class Windows { static void Main() { Window background_window = new Window( 76, 22, '/' ) ; FrameWindow empty_window = new FrameWindow( 24, 7 ) ; TextWindow greeting_window = new TextWindow( 30, 8, "Hello, world." ) ; DecoratedTextWindow smiling_window = new DecoratedTextWindow( 28, 11, "Smile!" ) ; background_window.move( 6, 2, empty_window ) ; background_window.move( 4, 12, greeting_window ) ; greeting_window.change_text( "HELLO, UNIVERSE!" ) ; background_window.move( 43, 11, greeting_window ) ; background_window.move( 40, 3, smiling_window ) ; background_window.print() ; } }
using System; using System.Runtime; namespace System.Management { public class RelationshipQuery : WqlObjectQuery { private readonly static string tokenReferences; private readonly static string tokenOf; private readonly static string tokenWhere; private readonly static string tokenResultClass; private readonly static string tokenRole; private readonly static string tokenRequiredQualifier; private readonly static string tokenClassDefsOnly; private readonly static string tokenSchemaOnly; private string sourceObject; private string relationshipClass; private string relationshipQualifier; private string thisRole; private bool classDefinitionsOnly; private bool isSchemaQuery; public bool ClassDefinitionsOnly { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.classDefinitionsOnly; } set { this.classDefinitionsOnly = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public bool IsSchemaQuery { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.isSchemaQuery; } set { this.isSchemaQuery = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelationshipClass { get { if (this.relationshipClass != null) { return this.relationshipClass; } else { return string.Empty; } } set { this.relationshipClass = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string RelationshipQualifier { get { if (this.relationshipQualifier != null) { return this.relationshipQualifier; } else { return string.Empty; } } set { this.relationshipQualifier = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string SourceObject { get { if (this.sourceObject != null) { return this.sourceObject; } else { return string.Empty; } } set { this.sourceObject = value; this.BuildQuery(); base.FireIdentifierChanged(); } } public string ThisRole { get { if (this.thisRole != null) { return this.thisRole; } else { return string.Empty; } } set { this.thisRole = value; this.BuildQuery(); base.FireIdentifierChanged(); } } static RelationshipQuery() { RelationshipQuery.tokenReferences = "references"; RelationshipQuery.tokenOf = "of"; RelationshipQuery.tokenWhere = "where"; RelationshipQuery.tokenResultClass = "resultclass"; RelationshipQuery.tokenRole = "role"; RelationshipQuery.tokenRequiredQualifier = "requiredqualifier"; RelationshipQuery.tokenClassDefsOnly = "classdefsonly"; RelationshipQuery.tokenSchemaOnly = "schemaonly"; } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public RelationshipQuery() : this(null) { } public RelationshipQuery(string queryOrSourceObject) { if (queryOrSourceObject == null) { return; } else { if (!queryOrSourceObject.TrimStart(new char[0]).StartsWith(RelationshipQuery.tokenReferences, StringComparison.OrdinalIgnoreCase)) { ManagementPath managementPath = new ManagementPath(queryOrSourceObject); if ((managementPath.IsClass || managementPath.IsInstance) && managementPath.NamespacePath.Length == 0) { this.SourceObject = queryOrSourceObject; this.isSchemaQuery = false; return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "queryOrSourceObject"); } } else { this.QueryString = queryOrSourceObject; return; } } } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public RelationshipQuery(string sourceObject, string relationshipClass) : this(sourceObject, relationshipClass, null, null, false) { } public RelationshipQuery(string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole, bool classDefinitionsOnly) { this.isSchemaQuery = false; this.sourceObject = sourceObject; this.relationshipClass = relationshipClass; this.relationshipQualifier = relationshipQualifier; this.thisRole = thisRole; this.classDefinitionsOnly = classDefinitionsOnly; this.BuildQuery(); } public RelationshipQuery(bool isSchemaQuery, string sourceObject, string relationshipClass, string relationshipQualifier, string thisRole) { if (isSchemaQuery) { this.isSchemaQuery = true; this.sourceObject = sourceObject; this.relationshipClass = relationshipClass; this.relationshipQualifier = relationshipQualifier; this.thisRole = thisRole; this.classDefinitionsOnly = false; this.BuildQuery(); return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "isSchemaQuery"); } } protected internal void BuildQuery() { if (this.sourceObject == null) { base.SetQueryString(string.Empty); } if (this.sourceObject == null || this.sourceObject.Length == 0) { return; } else { string[] strArrays = new string[6]; strArrays[0] = RelationshipQuery.tokenReferences; strArrays[1] = " "; strArrays[2] = RelationshipQuery.tokenOf; strArrays[3] = " {"; strArrays[4] = this.sourceObject; strArrays[5] = "}"; string str = string.Concat(strArrays); if (this.RelationshipClass.Length != 0 || this.RelationshipQualifier.Length != 0 || this.ThisRole.Length != 0 || this.classDefinitionsOnly || this.isSchemaQuery) { str = string.Concat(str, " ", RelationshipQuery.tokenWhere); if (this.RelationshipClass.Length != 0) { string[] strArrays1 = new string[5]; strArrays1[0] = str; strArrays1[1] = " "; strArrays1[2] = RelationshipQuery.tokenResultClass; strArrays1[3] = " = "; strArrays1[4] = this.relationshipClass; str = string.Concat(strArrays1); } if (this.ThisRole.Length != 0) { string[] strArrays2 = new string[5]; strArrays2[0] = str; strArrays2[1] = " "; strArrays2[2] = RelationshipQuery.tokenRole; strArrays2[3] = " = "; strArrays2[4] = this.thisRole; str = string.Concat(strArrays2); } if (this.RelationshipQualifier.Length != 0) { string[] strArrays3 = new string[5]; strArrays3[0] = str; strArrays3[1] = " "; strArrays3[2] = RelationshipQuery.tokenRequiredQualifier; strArrays3[3] = " = "; strArrays3[4] = this.relationshipQualifier; str = string.Concat(strArrays3); } if (this.isSchemaQuery) { str = string.Concat(str, " ", RelationshipQuery.tokenSchemaOnly); } else { if (this.classDefinitionsOnly) { str = string.Concat(str, " ", RelationshipQuery.tokenClassDefsOnly); } } } base.SetQueryString(str); return; } } public override object Clone() { if (this.isSchemaQuery) { return new RelationshipQuery(true, this.sourceObject, this.relationshipClass, this.relationshipQualifier, this.thisRole); } else { return new RelationshipQuery(this.sourceObject, this.relationshipClass, this.relationshipQualifier, this.thisRole, this.classDefinitionsOnly); } } protected internal override void ParseQuery(string query) { string str = null; string str1 = null; string str2 = null; bool flag = false; bool flag1 = false; string str3 = query.Trim(); if (string.Compare(str3, 0, RelationshipQuery.tokenReferences, 0, RelationshipQuery.tokenReferences.Length, StringComparison.OrdinalIgnoreCase) == 0) { str3 = str3.Remove(0, RelationshipQuery.tokenReferences.Length); if (str3.Length == 0 || !char.IsWhiteSpace(str3[0])) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } else { str3 = str3.TrimStart(null); if (string.Compare(str3, 0, RelationshipQuery.tokenOf, 0, RelationshipQuery.tokenOf.Length, StringComparison.OrdinalIgnoreCase) == 0) { str3 = str3.Remove(0, RelationshipQuery.tokenOf.Length).TrimStart(null); if (str3.IndexOf('{') == 0) { str3 = str3.Remove(0, 1).TrimStart(null); int num = str3.IndexOf('}'); int num1 = num; if (-1 != num) { string str4 = str3.Substring(0, num1).TrimEnd(null); str3 = str3.Remove(0, num1 + 1).TrimStart(null); if (0 < str3.Length) { if (string.Compare(str3, 0, RelationshipQuery.tokenWhere, 0, RelationshipQuery.tokenWhere.Length, StringComparison.OrdinalIgnoreCase) == 0) { str3 = str3.Remove(0, RelationshipQuery.tokenWhere.Length); if (str3.Length == 0 || !char.IsWhiteSpace(str3[0])) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } else { str3 = str3.TrimStart(null); bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; bool flag6 = false; while (true) { if (str3.Length < RelationshipQuery.tokenResultClass.Length || string.Compare(str3, 0, RelationshipQuery.tokenResultClass, 0, RelationshipQuery.tokenResultClass.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str3.Length < RelationshipQuery.tokenRole.Length || string.Compare(str3, 0, RelationshipQuery.tokenRole, 0, RelationshipQuery.tokenRole.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str3.Length < RelationshipQuery.tokenRequiredQualifier.Length || string.Compare(str3, 0, RelationshipQuery.tokenRequiredQualifier, 0, RelationshipQuery.tokenRequiredQualifier.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str3.Length < RelationshipQuery.tokenClassDefsOnly.Length || string.Compare(str3, 0, RelationshipQuery.tokenClassDefsOnly, 0, RelationshipQuery.tokenClassDefsOnly.Length, StringComparison.OrdinalIgnoreCase) != 0) { if (str3.Length < RelationshipQuery.tokenSchemaOnly.Length || string.Compare(str3, 0, RelationshipQuery.tokenSchemaOnly, 0, RelationshipQuery.tokenSchemaOnly.Length, StringComparison.OrdinalIgnoreCase) != 0) { break; } ManagementQuery.ParseToken(ref str3, RelationshipQuery.tokenSchemaOnly, ref flag6); flag1 = true; } else { ManagementQuery.ParseToken(ref str3, RelationshipQuery.tokenClassDefsOnly, ref flag5); flag = true; } } else { ManagementQuery.ParseToken(ref str3, RelationshipQuery.tokenRequiredQualifier, "=", ref flag4, ref str2); } } else { ManagementQuery.ParseToken(ref str3, RelationshipQuery.tokenRole, "=", ref flag3, ref str1); } } else { ManagementQuery.ParseToken(ref str3, RelationshipQuery.tokenResultClass, "=", ref flag2, ref str); } } if (str3.Length == 0) { if (flag && flag1) { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "where"); } } this.sourceObject = str4; this.relationshipClass = str; this.thisRole = str1; this.relationshipQualifier = str2; this.classDefinitionsOnly = flag; this.isSchemaQuery = flag1; return; } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY")); } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "of"); } } } else { throw new ArgumentException(RC.GetString("INVALID_QUERY"), "references"); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Xml; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml.Internals; namespace Xamarin.Forms.Xaml { internal class CreateValuesVisitor : IXamlNodeVisitor { public CreateValuesVisitor(HydratationContext context) { Context = context; } Dictionary<INode, object> Values { get { return Context.Values; } } HydratationContext Context { get; } public bool VisitChildrenFirst { get { return true; } } public bool StopOnDataTemplate { get { return true; } } public bool StopOnResourceDictionary { get { return false; } } public void Visit(ValueNode node, INode parentNode) { Values[node] = node.Value; } public void Visit(MarkupNode node, INode parentNode) { } public void Visit(ElementNode node, INode parentNode) { object value = null; XamlParseException xpe; var type = XamlParser.GetElementType(node.XmlType, node, Context.RootElement?.GetType().GetTypeInfo().Assembly, out xpe); if (xpe != null) throw xpe; Context.Types[node] = type; string ctorargname; if (IsXaml2009LanguagePrimitive(node)) value = CreateLanguagePrimitive(type, node); else if (node.Properties.ContainsKey(XmlName.xArguments) || node.Properties.ContainsKey(XmlName.xFactoryMethod)) value = CreateFromFactory(type, node); else if ( type.GetTypeInfo() .DeclaredConstructors.Any( ci => ci.IsPublic && ci.GetParameters().Length != 0 && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))) && ValidateCtorArguments(type, node, out ctorargname)) value = CreateFromParameterizedConstructor(type, node); else if (!type.GetTypeInfo().DeclaredConstructors.Any(ci => ci.IsPublic && ci.GetParameters().Length == 0) && !ValidateCtorArguments(type, node, out ctorargname)) { throw new XamlParseException($"The Property {ctorargname} is required to create a {type.FullName} object.", node); } else { //this is a trick as the DataTemplate parameterless ctor is internal, and we can't CreateInstance(..., false) on WP7 try { if (type == typeof (DataTemplate)) value = new DataTemplate(); if (type == typeof (ControlTemplate)) value = new ControlTemplate(); if (value == null && node.CollectionItems.Any() && node.CollectionItems.First() is ValueNode) { var serviceProvider = new XamlServiceProvider(node, Context); var converted = ((ValueNode)node.CollectionItems.First()).Value.ConvertTo(type, () => type.GetTypeInfo(), serviceProvider); if (converted != null && converted.GetType() == type) value = converted; } if (value == null) value = Activator.CreateInstance(type); } catch (TargetInvocationException e) { if (e.InnerException is XamlParseException || e.InnerException is XmlException) throw e.InnerException; throw; } } Values[node] = value; var markup = value as IMarkupExtension; if (markup != null && (value is TypeExtension || value is StaticExtension || value is ArrayExtension)) { var serviceProvider = new XamlServiceProvider(node, Context); var visitor = new ApplyPropertiesVisitor(Context); foreach (var cnode in node.Properties.Values.ToList()) cnode.Accept(visitor, node); foreach (var cnode in node.CollectionItems) cnode.Accept(visitor, node); value = markup.ProvideValue(serviceProvider); INode xKey; if (!node.Properties.TryGetValue(XmlName.xKey, out xKey)) xKey = null; node.Properties.Clear(); node.CollectionItems.Clear(); if (xKey != null) node.Properties.Add(XmlName.xKey, xKey); Values[node] = value; } if (value is BindableObject) NameScope.SetNameScope(value as BindableObject, node.Namescope); } public void Visit(RootNode node, INode parentNode) { var rnode = (XamlLoader.RuntimeRootNode)node; Values[node] = rnode.Root; Context.Types[node] = rnode.Root.GetType(); var bindableRoot = rnode.Root as BindableObject; if (bindableRoot != null) NameScope.SetNameScope(bindableRoot, node.Namescope); } public void Visit(ListNode node, INode parentNode) { //this is a gross hack to keep ListNode alive. ListNode must go in favor of Properties XmlName name; if (ApplyPropertiesVisitor.TryGetPropertyName(node, parentNode, out name)) node.XmlName = name; } bool ValidateCtorArguments(Type nodeType, IElementNode node, out string missingArgName) { missingArgName = null; var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))); if (ctorInfo == null) return true; foreach (var parameter in ctorInfo.GetParameters()) { var propname = parameter.CustomAttributes.First(ca => ca.AttributeType.FullName == "Xamarin.Forms.ParameterAttribute") .ConstructorArguments.First() .Value as string; if (!node.Properties.ContainsKey(new XmlName("", propname))) { missingArgName = propname; return false; } } return true; } public object CreateFromParameterizedConstructor(Type nodeType, IElementNode node) { var ctorInfo = nodeType.GetTypeInfo() .DeclaredConstructors.FirstOrDefault( ci => ci.GetParameters().Length != 0 && ci.IsPublic && ci.GetParameters().All(pi => pi.CustomAttributes.Any(attr => attr.AttributeType == typeof (ParameterAttribute)))); object[] arguments = CreateArgumentsArray(node, ctorInfo); return ctorInfo.Invoke(arguments); } public object CreateFromFactory(Type nodeType, IElementNode node) { object[] arguments = CreateArgumentsArray(node); if (!node.Properties.ContainsKey(XmlName.xFactoryMethod)) { //non-default ctor return Activator.CreateInstance(nodeType, arguments); } var factoryMethod = ((string)((ValueNode)node.Properties[XmlName.xFactoryMethod]).Value); Type[] types = arguments == null ? new Type[0] : arguments.Select(a => a.GetType()).ToArray(); Func<MethodInfo, bool> isMatch = m => { if (m.Name != factoryMethod) return false; var p = m.GetParameters(); if (p.Length != types.Length) return false; if (!m.IsStatic) return false; for (var i = 0; i < p.Length; i++) { if ((p [i].ParameterType.IsAssignableFrom(types [i]))) continue; var op_impl = p [i].ParameterType.GetRuntimeMethod("op_Implicit", new [] { types [i]}); if (op_impl == null) return false; arguments [i] = op_impl.Invoke(null, new [] { arguments [i]}); } return true; }; var mi = nodeType.GetRuntimeMethods().FirstOrDefault(isMatch); if (mi == null) throw new MissingMemberException($"No static method found for {nodeType.FullName}::{factoryMethod} ({string.Join(", ", types.Select(t => t.FullName))})"); return mi.Invoke(null, arguments); } public object[] CreateArgumentsArray(IElementNode enode) { if (!enode.Properties.ContainsKey(XmlName.xArguments)) return null; var node = enode.Properties[XmlName.xArguments]; var elementNode = node as ElementNode; if (elementNode != null) { var array = new object[1]; array[0] = Values[elementNode]; return array; } var listnode = node as ListNode; if (listnode != null) { var array = new object[listnode.CollectionItems.Count]; for (var i = 0; i < listnode.CollectionItems.Count; i++) array[i] = Values[(ElementNode)listnode.CollectionItems[i]]; return array; } return null; } public object[] CreateArgumentsArray(IElementNode enode, ConstructorInfo ctorInfo) { var n = ctorInfo.GetParameters().Length; var array = new object[n]; for (var i = 0; i < n; i++) { var parameter = ctorInfo.GetParameters()[i]; var propname = parameter.CustomAttributes.First(attr => attr.AttributeType == typeof (ParameterAttribute)) .ConstructorArguments.First() .Value as string; var name = new XmlName("", propname); INode node; if (!enode.Properties.TryGetValue(name, out node)) { throw new XamlParseException( String.Format("The Property {0} is required to create a {1} object.", propname, ctorInfo.DeclaringType.FullName), enode as IXmlLineInfo); } if (!enode.SkipProperties.Contains(name)) enode.SkipProperties.Add(name); var value = Context.Values[node]; var serviceProvider = new XamlServiceProvider(enode, Context); var convertedValue = value.ConvertTo(parameter.ParameterType, () => parameter, serviceProvider); array[i] = convertedValue; } return array; } static bool IsXaml2009LanguagePrimitive(IElementNode node) { return node.NamespaceURI == "http://schemas.microsoft.com/winfx/2009/xaml"; } static object CreateLanguagePrimitive(Type nodeType, IElementNode node) { object value = null; if (nodeType == typeof (string)) value = String.Empty; else if (nodeType == typeof (Uri)) value = null; else value = Activator.CreateInstance(nodeType); if (node.CollectionItems.Count == 1 && node.CollectionItems[0] is ValueNode && ((ValueNode)node.CollectionItems[0]).Value is string) { var valuestring = ((ValueNode)node.CollectionItems[0]).Value as string; if (nodeType == typeof(SByte)) { sbyte retval; if (sbyte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Int16)) { short retval; if (short.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Int32)) { int retval; if (int.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Int64)) { long retval; if (long.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Byte)) { byte retval; if (byte.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(UInt16)) { ushort retval; if (ushort.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(UInt32)) { uint retval; if (uint.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(UInt64)) { ulong retval; if (ulong.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Single)) { float retval; if (float.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof(Double)) { double retval; if (double.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof (Boolean)) { bool outbool; if (bool.TryParse(valuestring, out outbool)) return outbool; } if (nodeType == typeof(TimeSpan)) { TimeSpan retval; if (TimeSpan.TryParse(valuestring, CultureInfo.InvariantCulture, out retval)) return retval; } if (nodeType == typeof (char)) { char retval; if (char.TryParse(valuestring, out retval)) return retval; } if (nodeType == typeof (string)) return valuestring; if (nodeType == typeof (decimal)) { decimal retval; if (decimal.TryParse(valuestring, NumberStyles.Number, CultureInfo.InvariantCulture, out retval)) return retval; } else if (nodeType == typeof (Uri)) { Uri retval; if (Uri.TryCreate(valuestring, UriKind.RelativeOrAbsolute, out retval)) return retval; } } return value; } } }
using IntuiLab.Leap.DataStructures; using IntuiLab.Leap.Utils; using Leap; using System; using System.Collections.Generic; namespace IntuiLab.Leap.Recognition.Gestures { /// <summary> /// This class contains the algoritms of gestures recognition /// </summary> internal class GestureRecognizer { // The recognition of a gesture is here based on the comparison between the direction vectors of the movement from on frame to another. // Those vectors are calculate from the points of the discretized movement. // We compare the angle between the direction vector of a frame and the one of the previous frame. For exemple, if the angle is close to 0, // the movement is linear. We also consider the movement speed, the minimum number of frames it appears, etc. #region Fields private bool m_VerboseMode; #endregion #region Properties /// <summary> /// Contains the timestamp of the last event raised for a gesture /// </summary> private Tuple<GestureType, long> m_lastGestureTimestamp; public Tuple<GestureType, long> LastGestureTimestamp { get { return m_lastGestureTimestamp; } } #endregion #region Events /*********************************** Events for gestures in progress*****************************************************/ public event GestureDetectedEventHandler NoGestureDetected_GestureRecognizer; public event GestureDetectedEventHandler SwipeLeftGestureDetected_GestureRecognizer; public event GestureDetectedEventHandler SwipeRightGestureDetected_GestureRecognizer; public event GestureDetectedEventHandler TapGestureDetected_GestureRecognizer; public event GestureDetectedEventHandler PushGestureDetected_GestureRecognizer; private void RaiseNoGestureDetectedEvent(float speed, Vector direction, long timestamp) { if (NoGestureDetected_GestureRecognizer != null) NoGestureDetected_GestureRecognizer(this, new GestureDetectedEventArgs(GestureType.None, speed, direction, timestamp)); } private void RaiseSwipeLeftGestureEvent(float speed, Vector direction, long timestamp) { if (SwipeLeftGestureDetected_GestureRecognizer != null) { SwipeLeftGestureDetected_GestureRecognizer(this, new GestureDetectedEventArgs(GestureType.SwipeLeft, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.SwipeLeft, timestamp); } } private void RaiseSwipeRightGestureEvent(float speed, Vector direction, long timestamp) { if (SwipeRightGestureDetected_GestureRecognizer != null) { SwipeRightGestureDetected_GestureRecognizer(this, new GestureDetectedEventArgs(GestureType.SwipeRight, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.SwipeRight, timestamp); } } private void RaiseTapGestureEvent(float speed, Vector direction, long timestamp) { if (TapGestureDetected_GestureRecognizer != null) { TapGestureDetected_GestureRecognizer(this, new GestureDetectedEventArgs(GestureType.Tap, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.Tap, timestamp); } } private void RaisePushGestureEvent(float speed, Vector direction, long timestamp) { if (PushGestureDetected_GestureRecognizer != null) { PushGestureDetected_GestureRecognizer(this, new GestureDetectedEventArgs(GestureType.Push, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.Push, timestamp); } } /***********************************************************************************************************************/ /*********************** Events for gestures start *********************************************************************/ public event GestureDetectedEventHandler SwipeLeftGestureBegin; public event GestureDetectedEventHandler SwipeRightGestureBegin; public event GestureDetectedEventHandler TapGestureBegin; public event GestureDetectedEventHandler PushGestureBegin; private void RaiseSwipeLeftGestureBegin(float speed, Vector direction, long timestamp) { if (SwipeLeftGestureBegin != null) { SwipeLeftGestureBegin(this, new GestureDetectedEventArgs(GestureType.SwipeLeft, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.SwipeLeft, timestamp); } } private void RaiseSwipeRightGestureBegin(float speed, Vector direction, long timestamp) { if (SwipeRightGestureBegin != null) { SwipeRightGestureBegin(this, new GestureDetectedEventArgs(GestureType.SwipeRight, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.SwipeRight, timestamp); } } private void RaiseTapGestureBegin(float speed, Vector direction, long timestamp) { if (TapGestureBegin != null) { TapGestureBegin(this, new GestureDetectedEventArgs(GestureType.Tap, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.Tap, timestamp); } } private void RaisePushGestureBegin(float speed, Vector direction, long timestamp) { if (PushGestureBegin != null) { PushGestureBegin(this, new GestureDetectedEventArgs(GestureType.Push, speed, direction, timestamp)); this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.Push, timestamp); } } /***********************************************************************************************************************/ /*********************** Events for gestures end ***********************************************************************/ public event GestureDetectedEventHandler SwipeLeftGestureEnd; public event GestureDetectedEventHandler SwipeRightGestureEnd; public event GestureDetectedEventHandler TapGestureEnd; public event GestureDetectedEventHandler PushGestureEnd; private void RaiseSwipeLeftGestureEnd(float speed, Vector direction, long timestamp) { if (SwipeLeftGestureEnd != null) { SwipeLeftGestureEnd(this, new GestureDetectedEventArgs(GestureType.SwipeLeft, speed, direction, timestamp)); } } private void RaiseSwipeRightGestureEnd(float speed, Vector direction, long timestamp) { if (SwipeRightGestureEnd != null) { SwipeRightGestureEnd(this, new GestureDetectedEventArgs(GestureType.SwipeRight, speed, direction, timestamp)); } } private void RaiseTapGestureEnd(float speed, Vector direction, long timestamp) { if (TapGestureEnd != null) { TapGestureEnd(this, new GestureDetectedEventArgs(GestureType.Tap, speed, direction, timestamp)); } } private void RaisePushGestureEnd(float speed, Vector direction, long timestamp) { if (PushGestureEnd != null) { PushGestureEnd(this, new GestureDetectedEventArgs(GestureType.Push, speed, direction, timestamp)); } } /***********************************************************************************************************************/ #endregion #region Constructor public GestureRecognizer(bool verboseMode) { this.m_VerboseMode = verboseMode; this.m_lastGestureTimestamp = new Tuple<GestureType, long>(GestureType.None, 0L); } #endregion /// <summary> /// Detects if a gesture is beginning or in progress. /// </summary> /// <param name="frames">The list of last frames.</param> /// <param name="fingerId">The id of the finger to check</param> public void Process(List<IFrame> frames, int fingerId) { List<Vector> directions = new List<Vector>(); for (int i = 1; i < ParametersGesture.Instance.NbMinFrames; i++) { // we store all the direction vector of the movement between one frame and the previous directions.Add(LeapMath.Direction(fingerId, frames[i - 1], frames[i])); } IFrame actualFrame = frames[0]; IFrame oldFrame = frames[ParametersGesture.Instance.NbMinFrames - 1]; // we check if the movement is linear. If it is, we go on if (!LeapMath.IsLinearDirection(directions, m_VerboseMode)) return; // we calculate the global speed of the movement float globalSpeed = LeapMath.Speed(fingerId, oldFrame, actualFrame); // mm/s // we calculate the global direction of the movement Vector globalDirection = LeapMath.Direction(fingerId, oldFrame, actualFrame); if (m_VerboseMode) { Console.WriteLine("global speed={0} mm/s", globalSpeed); Console.WriteLine("global direction=" + globalDirection); Console.WriteLine("position=" + actualFrame.Finger(fingerId).TipPosition); Console.WriteLine("duration={0} us", (actualFrame.Timestamp - oldFrame.Timestamp)); Console.WriteLine("oldFrame id={0}, actualFrame id={1}", oldFrame.Id, actualFrame.Id); Console.WriteLine("timestamp=" + actualFrame.Timestamp); } // we check if the conditions (speed, displacement, etc) for gestures are valid // to have a priority on gesture, we call the condition checker of the priority gesture first if (TapConditionIsValid(globalSpeed, globalDirection)) { if (this.m_lastGestureTimestamp.Item1 != GestureType.Tap || Math.Abs(actualFrame.Timestamp - this.m_lastGestureTimestamp.Item2) > ParametersGesture.Instance.MaxTimeBetweenTwoFrames) RaiseTapGestureBegin(globalSpeed, globalDirection, actualFrame.Timestamp); else RaiseTapGestureEvent(globalSpeed, globalDirection, actualFrame.Timestamp); } else if (PushConditionIsValid(globalSpeed, globalDirection, actualFrame.Finger(fingerId).TipPosition)) { if (this.m_lastGestureTimestamp.Item1 != GestureType.Push || Math.Abs(actualFrame.Timestamp - this.m_lastGestureTimestamp.Item2) > ParametersGesture.Instance.MaxTimeBetweenTwoFrames) RaisePushGestureBegin(globalSpeed, globalDirection, actualFrame.Timestamp); else RaisePushGestureEvent(globalSpeed, globalDirection, actualFrame.Timestamp); } else if (SwipeRightConditionIsValid(globalSpeed, globalDirection)) { if (this.m_lastGestureTimestamp.Item1 != GestureType.SwipeRight || Math.Abs(actualFrame.Timestamp - this.m_lastGestureTimestamp.Item2) > ParametersGesture.Instance.MaxTimeBetweenTwoFrames) RaiseSwipeRightGestureBegin(globalSpeed, globalDirection, actualFrame.Timestamp); else RaiseSwipeRightGestureEvent(globalSpeed, globalDirection, actualFrame.Timestamp); } else if (SwipeLeftConditionIsValid(globalSpeed, globalDirection)) { if (this.m_lastGestureTimestamp.Item1 != GestureType.SwipeLeft || Math.Abs(actualFrame.Timestamp - this.m_lastGestureTimestamp.Item2) > ParametersGesture.Instance.MaxTimeBetweenTwoFrames) RaiseSwipeLeftGestureBegin(globalSpeed, globalDirection, actualFrame.Timestamp); else RaiseSwipeLeftGestureEvent(globalSpeed, globalDirection, actualFrame.Timestamp); } else { RaiseNoGestureDetectedEvent(globalSpeed, globalDirection, actualFrame.Timestamp); } } #region Stop Checker /// <summary> /// Checks if the gesture is ending. /// </summary> /// <param name="frames">The list of the two last frames.</param> /// <param name="fingerId">The id of the finger in movement.</param> public void CheckGestureEnd(List<IFrame> frames, int fingerId) { IFrame actualFrame = frames[0]; IFrame previousFrame = frames[1]; // we calculate the instant speed of the finger float instantSpeed = (actualFrame.Finger(fingerId).IsValid) ? LeapMath.Speed(fingerId, previousFrame, actualFrame) : 0; // mm/s if (m_VerboseMode) { Console.WriteLine("instant speed=" + instantSpeed); } // if the instant speed is too small, we consider that the gesture is finished if (instantSpeed < ParametersGesture.Instance.StopSpeed) { switch (m_lastGestureTimestamp.Item1) { case GestureType.Tap: { RaiseSwipeLeftGestureEnd(instantSpeed, null, actualFrame.Timestamp); } break; case GestureType.Push: { RaisePushGestureEnd(instantSpeed, null, actualFrame.Timestamp); } break; case GestureType.SwipeRight: { RaiseSwipeRightGestureEnd(instantSpeed, null, actualFrame.Timestamp); } break; case GestureType.SwipeLeft: { RaiseSwipeLeftGestureEnd(instantSpeed, null, actualFrame.Timestamp); } break; default: break; } } } #endregion #region Conditions Checkers // A tap gesture has to have a linear trajectory, its speed must be in a specific interval, the displacement along the x axis must be small and the one along the y axis big. // The movement has to be directed downward (dy < 0) /// <summary> /// Checks if the conditions for a Tap gesture are valid /// </summary> private bool TapConditionIsValid(float speed, Vector globalDirection) { if (speed > ParametersGesture.Instance.Tap_minSpeed && speed < ParametersGesture.Instance.Tap_maxSpeed) { if (globalDirection.x > -ParametersGesture.Instance.Tap_maxDx && globalDirection.x < ParametersGesture.Instance.Tap_maxDx && globalDirection.y < ParametersGesture.Instance.Tap_minDy) return true; } return false; } // A swipe must have a linear direction, and its speed must be in a specific interval. /// <summary> /// Check is the conditions for a Swipe Right gesture are valid /// </summary> private bool SwipeRightConditionIsValid(float speed, Vector globalDirection) { if (speed > ParametersGesture.Instance.Swipe_minSpeed && speed < ParametersGesture.Instance.Swipe_maxSpeed) { if (globalDirection.x >= 0) return true; } return false; } /// <summary> /// Check if the conditions for a Swipe Left gesture are valid /// </summary> private bool SwipeLeftConditionIsValid(float speed, Vector globalDirection) { if (speed > ParametersGesture.Instance.Swipe_minSpeed && speed < ParametersGesture.Instance.Swipe_maxSpeed) { if (globalDirection.x < 0) return true; } return false; } /// <summary> /// Checks if the conditions for a Push gesture is valid /// </summary> public bool PushConditionIsValid(float speed, Vector globalDirection, Vector lastPosition) { if (speed > ParametersGesture.Instance.Push_minSpeed && speed < ParametersGesture.Instance.Push_maxSpeed) { if (globalDirection.x > -ParametersGesture.Instance.Push_maxDx && globalDirection.x < ParametersGesture.Instance.Push_maxDx && globalDirection.z < ParametersGesture.Instance.Push_minDz && globalDirection.y > ParametersGesture.Instance.Push_minDy && lastPosition.z < ParametersGesture.Instance.Push_maxZ) // The last condition is that the finger must pass a certain limit for the push to be recognized, but it greatly reduces the success rate. return true; // Comment it if you want the push to be detected without having to pass the limit, or set the parameter higher. } return false; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Xml; namespace System.Runtime.Serialization.Xml.Canonicalization.Tests { internal interface IPrefixGenerator { string GetPrefix(string namespaceUri, int depth, bool isForAttribute); } internal enum XmlDocumentPosition { BeforeRootElement, InRootElement, AfterRootElement } internal sealed class CanonicalWriter : XmlDictionaryWriter { private const int InitialElementStackSize = 10; private readonly CanonicalAttributeManager _attributesToRender; private CanonicalEncoder _encoder; private bool _includeComments; private string[] _inclusivePrefixes; private IPrefixGenerator _prefixGenerator; private ExclusiveCanonicalNamespaceManager _manager; private int _startingDepthForAttributePrefixGeneration; private WriteState _state; private XmlDocumentPosition _docPos; private ElementEntry[] _elements; private int _elementCount; private int _depth; private int _attributePrefixGenerationIndex; private bool _bufferOnlyRootElementContents; private string _currentAttributeName; private string _currentAttributePrefix; private string _currentAttributeNamespace; private string _currentAttributeValue; private XmlAttributeHolder[] _rootElementAttributes; private string _rootElementPrefix; private string _pendingBaseDeclarationPrefix; private string _pendingBaseDeclarationNamespace; private byte[] _base64Remainder; private int _base64RemainderSize; private char[] _conversionBuffer; private const int ConversionBufferSize = 4 * 128; private const int Base64ByteBufferSize = 3 * 128; private XmlDictionaryWriter _bufferingWriter; private char[] _auxBuffer; private ICanonicalWriterEndRootElementCallback _endOfRootElementCallback; private IAncestralNamespaceContextProvider _contextProvider; public CanonicalWriter(CanonicalEncoder encoder) : this(encoder, null, false, null, 0) { } public CanonicalWriter(CanonicalEncoder encoder, string[] inclusivePrefixes, bool includeComments, IPrefixGenerator prefixGenerator, int startingDepthForAttributePrefixGeneration) { _attributesToRender = new CanonicalAttributeManager(); _encoder = encoder; _includeComments = includeComments; _prefixGenerator = prefixGenerator; _startingDepthForAttributePrefixGeneration = startingDepthForAttributePrefixGeneration; _manager = new ExclusiveCanonicalNamespaceManager(); _elements = new ElementEntry[InitialElementStackSize]; _inclusivePrefixes = inclusivePrefixes; Reset(); } public XmlDictionaryWriter BufferingWriter { get { return _bufferingWriter; } set { ThrowIfNotInStartState(); _bufferingWriter = value; // allow null } } public bool BufferOnlyRootElementContents { get { return _bufferOnlyRootElementContents; } set { ThrowIfNotInStartState(); _bufferOnlyRootElementContents = value; } } public IAncestralNamespaceContextProvider ContextProvider { get { return _contextProvider; } set { ThrowIfNotInStartState(); _contextProvider = value; } } public CanonicalEncoder Encoder { get { return _encoder; } set { ThrowIfNotInStartState(); if (value == null) { throw new ArgumentNullException("value"); } _encoder = value; } } internal ICanonicalWriterEndRootElementCallback EndRootElementCallback { get { return _endOfRootElementCallback; } set { ThrowIfNotInStartState(); _endOfRootElementCallback = value; // allow null } } public bool IncludeComments { get { return _includeComments; } set { ThrowIfNotInStartState(); _includeComments = value; } } public IPrefixGenerator PrefixGenerator { get { return _prefixGenerator; } set { ThrowIfNotInStartState(); _prefixGenerator = value; } } internal XmlAttributeHolder[] RootElementAttributes { get { return _rootElementAttributes; } } public string RootElementPrefix { get { return _rootElementPrefix; } } private bool ShouldDelegate { get { return _bufferingWriter != null && (!_bufferOnlyRootElementContents || _depth > 0); } } public int StartingDepthForAttributePrefixGeneration { get { return _startingDepthForAttributePrefixGeneration; } set { ThrowIfNotInStartState(); if (value < 0) { throw new ArgumentOutOfRangeException("value", "Value must be non-negative."); } _startingDepthForAttributePrefixGeneration = value; } } public override WriteState WriteState { get { return _state; } } private string AutoGeneratePrefix(string ns, bool isForAttribute) { string prefix = null; if (_prefixGenerator != null) { prefix = _prefixGenerator.GetPrefix(ns, _depth + _startingDepthForAttributePrefixGeneration, isForAttribute); } if (prefix != null && LookupNamespace(prefix) == null) { return prefix; } if (!isForAttribute) { return string.Empty; } do { prefix = "d" + (_depth + _startingDepthForAttributePrefixGeneration) + "p" + ++_attributePrefixGenerationIndex; } while (LookupNamespace(prefix) != null); return prefix; } public override void Close() { if (ShouldDelegate) { _bufferingWriter.Close(); } } public override void Flush() { if (ShouldDelegate) { _bufferingWriter.Flush(); } } public void FlushWriterAndEncoder() { Flush(); _encoder.Flush(); } public string[] GetInclusivePrefixes() { return _inclusivePrefixes; } private string LookupNamespace(string prefix) { if (prefix == null) { prefix = string.Empty; } string ns = _manager.LookupNamespace(prefix); if (ns == null && prefix.Length == 0) { ns = string.Empty; } return ns; } public override string LookupPrefix(string ns) { return _manager.LookupPrefix(ns, false); } private void OnEndElement() { if (_state != WriteState.Content && _state != WriteState.Element) { ThrowBadStateException("EndElement"); } OnPossibleEndOfStartTag(WriteState.Content); _encoder.EncodeEndElement(_elements[_elementCount - 1].prefix, _elements[_elementCount - 1].localName); PopElement(); _manager.ExitElementContext(); _depth--; if (_depth == 0) { _docPos = XmlDocumentPosition.AfterRootElement; if (EndRootElementCallback != null) { EndRootElementCallback.OnEndOfRootElement(this); } } } private void OnPossibleEndOfBase64Content() { if (_base64RemainderSize > 0) { WriteBase64Core(_base64Remainder, 0, _base64RemainderSize); _base64RemainderSize = 0; } } private void OnPossibleEndOfStartTag(WriteState newState) { if (_state == WriteState.Element) { OnEndStartElement(); _depth++; } _state = newState; } private void OnEndStartElement() { if (_inclusivePrefixes != null) { for (int i = 0; i < _inclusivePrefixes.Length; i++) { _manager.MarkToRenderForInclusivePrefix(_inclusivePrefixes[i], _depth == 0, _contextProvider); } } _attributesToRender.Sort(); _encoder.EncodeStartElementOpen(_elements[_elementCount - 1].prefix, _elements[_elementCount - 1].localName); _manager.Render(_encoder); _attributesToRender.Encode(_encoder); _encoder.EncodeStartElementClose(); if (BufferOnlyRootElementContents && _elementCount == 1) { _rootElementAttributes = _attributesToRender.Copy(); _rootElementPrefix = _elements[0].prefix; } _attributesToRender.Clear(); } private void PopElement() { _elements[--_elementCount].Clear(); } private void PushElement(string prefix, string localName) { if (_elementCount == _elements.Length) { ElementEntry[] newElements = new ElementEntry[_elements.Length * 2]; Array.Copy(_elements, 0, newElements, 0, _elementCount); _elements = newElements; } _elements[_elementCount++].Set(prefix, localName); } public void Reset() { _state = WriteState.Start; _attributesToRender.Clear(); if (_encoder != null) { _encoder.Reset(); } _manager.Reset(); for (int i = _elementCount - 1; i >= 0; i--) { _elements[i].Clear(); } _elementCount = 0; _depth = 0; _docPos = XmlDocumentPosition.BeforeRootElement; _attributePrefixGenerationIndex = 0; _rootElementAttributes = null; _rootElementPrefix = null; _base64RemainderSize = 0; _pendingBaseDeclarationPrefix = null; _pendingBaseDeclarationNamespace = null; } public void RestoreDefaultSettings() { BufferingWriter = null; BufferOnlyRootElementContents = false; ContextProvider = null; PrefixGenerator = null; StartingDepthForAttributePrefixGeneration = 0; } public void SetInclusivePrefixes(string[] inclusivePrefixes) { ThrowIfNotInStartState(); _inclusivePrefixes = inclusivePrefixes; } private void ThrowBadStateException(string call) { throw new InvalidOperationException(String.Format("Invalid Operation for writer state: {0}, {1}", call, _state)); } private void ThrowIfNotInStartState() { if (_state != WriteState.Start) { throw new InvalidOperationException("Setting may be modified only when the writer is in Start State."); } } public override void WriteBase64(byte[] buffer, int offset, int count) { CanonicalEncoder.ValidateBufferBounds(buffer, offset, count); int originalOffset = offset; int originalCount = count; if (_state == WriteState.Element) { OnPossibleEndOfStartTag(WriteState.Content); } // complete previous left overs if (_base64RemainderSize > 0) { int nBytes = Math.Min(3 - _base64RemainderSize, count); Buffer.BlockCopy(buffer, offset, _base64Remainder, _base64RemainderSize, nBytes); _base64RemainderSize += nBytes; offset += nBytes; count -= nBytes; if (_base64RemainderSize == 3) { WriteBase64Core(_base64Remainder, 0, 3); _base64RemainderSize = 0; } } if (count > 0) { // save new left over _base64RemainderSize = count % 3; if (_base64RemainderSize > 0) { if (_base64Remainder == null) { _base64Remainder = new byte[3]; } Buffer.BlockCopy(buffer, offset + count - _base64RemainderSize, _base64Remainder, 0, _base64RemainderSize); count -= _base64RemainderSize; } // write the middle WriteBase64Core(buffer, offset, count); } if (ShouldDelegate) { _bufferingWriter.WriteBase64(buffer, originalOffset, originalCount); } } private void WriteBase64Core(byte[] buffer, int offset, int count) { if (_conversionBuffer == null) { _conversionBuffer = new char[ConversionBufferSize]; } while (count > 0) { int nBytes = Math.Min(count, Base64ByteBufferSize); int nChars = Convert.ToBase64CharArray(buffer, offset, nBytes, _conversionBuffer, 0); WriteStringCore(_conversionBuffer, 0, nChars, true, true); offset += nBytes; count -= nBytes; } } public override void WriteCData(string s) { if (s == null) { throw new ArgumentNullException("s"); } OnPossibleEndOfBase64Content(); if (_state == WriteState.Element) { OnPossibleEndOfStartTag(WriteState.Content); } else if (_state != WriteState.Content) { ThrowBadStateException("WriteCData"); } _encoder.EncodeWithTranslation(s, CanonicalEncoder.XmlStringType.CDataContent); if (ShouldDelegate) { _bufferingWriter.WriteCData(s); } } public override void WriteCharEntity(char ch) { switch (ch) { case '<': WriteRaw("&lt;"); break; case '>': WriteRaw("&gt;"); break; case '&': WriteRaw("&amp;"); break; default: if (_auxBuffer == null) { _auxBuffer = new char[1]; } _auxBuffer[0] = ch; WriteStringCore(_auxBuffer, 0, 1, false, false); if (ShouldDelegate) { _bufferingWriter.WriteCharEntity(ch); } break; } } public override void WriteChars(char[] buffer, int index, int count) { WriteStringCore(buffer, index, count, false, false); if (ShouldDelegate) { CanonicalEncoder.WriteEscapedChars(_bufferingWriter, buffer, index, count); } } public override void WriteComment(string text) { if (text == null) { throw new ArgumentNullException("text"); } if (_state == WriteState.Element) { OnPossibleEndOfStartTag(WriteState.Content); } else if (_state == WriteState.Attribute) { ThrowBadStateException("WriteComment"); } if (_includeComments) { _encoder.EncodeComment(text, _docPos); } if (ShouldDelegate) { _bufferingWriter.WriteComment(text); } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (ShouldDelegate) { _bufferingWriter.WriteDocType(name, pubid, sysid, subset); } } public override void WriteEndAttribute() { if (_state != WriteState.Attribute) { ThrowBadStateException("WriteEndAttribute"); } OnPossibleEndOfBase64Content(); if (_currentAttributePrefix == "xmlns") { _manager.AddLocalNamespaceIfNotRedundant(_currentAttributeName, _currentAttributeValue); } else { _attributesToRender.Add(_currentAttributePrefix, _currentAttributeName, _currentAttributeNamespace, _currentAttributeValue); if (_currentAttributePrefix.Length > 0) { _manager.AddLocalNamespaceIfNotRedundant(_currentAttributePrefix, _currentAttributeNamespace); _manager.MarkToRenderForVisiblyUsedPrefix(_currentAttributePrefix, true, _contextProvider); } } _currentAttributeName = null; _currentAttributePrefix = null; _currentAttributeNamespace = null; _currentAttributeValue = null; _state = WriteState.Element; if (ShouldDelegate) { _bufferingWriter.WriteEndAttribute(); if (_pendingBaseDeclarationNamespace != null) { _bufferingWriter.WriteStartAttribute("xmlns", _pendingBaseDeclarationPrefix, null); _bufferingWriter.WriteString(_pendingBaseDeclarationNamespace); _bufferingWriter.WriteEndAttribute(); _pendingBaseDeclarationNamespace = null; _pendingBaseDeclarationPrefix = null; } } } public override void WriteEndDocument() { if (ShouldDelegate) { _bufferingWriter.WriteEndDocument(); } } public override void WriteEndElement() { OnPossibleEndOfBase64Content(); OnEndElement(); if (ShouldDelegate) { _bufferingWriter.WriteEndElement(); } } public override void WriteEntityRef(string name) { throw new NotSupportedException(); } public override void WriteFullEndElement() { OnPossibleEndOfBase64Content(); OnEndElement(); if (ShouldDelegate) { _bufferingWriter.WriteFullEndElement(); } } public override void WriteProcessingInstruction(string name, string text) { if (name == null) { throw new ArgumentNullException("name"); } if (_state == WriteState.Attribute) { ThrowBadStateException("WriteProcessingInstruction"); } OnPossibleEndOfBase64Content(); OnPossibleEndOfStartTag(WriteState.Content); if (ShouldDelegate) { _bufferingWriter.WriteProcessingInstruction(name, text); } } public override void WriteQualifiedName(string localName, string ns) { if (localName == null || localName.Length == 0) { throw new ArgumentNullException("localName"); } if (ns == null) { ns = string.Empty; } string prefix = _manager.LookupPrefix(ns, false); if (ns.Length == 0) { if (prefix == null) { prefix = string.Empty; } else if (prefix.Length > 0) { if (_state != WriteState.Attribute || LookupNamespace(string.Empty) != null) { throw new InvalidOperationException(String.Format("Prefix not defined for namespace {0}", ns)); } prefix = string.Empty; _pendingBaseDeclarationNamespace = ns; _pendingBaseDeclarationPrefix = prefix; } } else if (prefix == null) { if (_state != WriteState.Attribute) { throw new InvalidOperationException(String.Format("Prefix not defined for namespace: {0}", ns)); } if (BufferingWriter != null) { prefix = BufferingWriter.LookupPrefix(ns); } if (prefix == null) { prefix = AutoGeneratePrefix(ns, true); _pendingBaseDeclarationNamespace = ns; _pendingBaseDeclarationPrefix = prefix; } } _manager.AddLocalNamespaceIfNotRedundant(prefix, ns); // not visibly utilized; so don't force rendering if (prefix.Length != 0) { WriteStringCore(prefix); WriteStringCore(":"); } WriteStringCore(localName); if (ShouldDelegate) { if (prefix.Length != 0) { _bufferingWriter.WriteString(prefix); _bufferingWriter.WriteString(":"); } _bufferingWriter.WriteString(localName); } } public override void WriteRaw(char[] buffer, int index, int count) { WriteStringCore(buffer, index, count, true, false); if (ShouldDelegate) { _bufferingWriter.WriteRaw(buffer, index, count); } } public override void WriteRaw(string data) { WriteStringCore(data, true); if (ShouldDelegate) { _bufferingWriter.WriteRaw(data); } } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString ns) { WriteStartAttributeCore(ref prefix, localName == null ? null : localName.Value, ns == null ? null : ns.Value); if (ShouldDelegate) { _bufferingWriter.WriteStartAttribute(prefix, localName, ns); } } public override void WriteStartAttribute(string prefix, string localName, string ns) { WriteStartAttributeCore(ref prefix, localName, ns); if (ShouldDelegate) { _bufferingWriter.WriteStartAttribute(prefix, localName, ns); } } private void WriteStartAttributeCore(ref string prefix, string localName, string ns) { if (_state != WriteState.Element) { ThrowBadStateException("WriteStartAttribute"); } if (localName == null) { throw new ArgumentNullException("localName"); } if (prefix == null) { prefix = string.Empty; } if (prefix.Length == 0 && localName == "xmlns") { _currentAttributePrefix = "xmlns"; _currentAttributeName = string.Empty; _currentAttributeValue = string.Empty; } else if (prefix == "xmlns") { _currentAttributePrefix = "xmlns"; _currentAttributeName = localName; _currentAttributeValue = string.Empty; } else { if (localName.Length == 0) { throw new ArgumentOutOfRangeException("localName", "Length must be greater than zero."); } // non-namespace declaration attribute if (ns == null) { if (prefix.Length == 0) { ns = string.Empty; } else { ns = LookupNamespace(prefix); if (ns == null) { throw new InvalidOperationException(String.Format("Undefined use of prefix at attribute: {0}, {1}", prefix, localName)); } } } else if (ns.Length == 0) { if (prefix.Length != 0) { throw new InvalidOperationException("Invalid Namespaceffor empty Prefix."); } } else if (prefix.Length == 0) { prefix = _manager.LookupPrefix(ns, true); if (prefix == null) { prefix = AutoGeneratePrefix(ns, true); } } _currentAttributePrefix = prefix; _currentAttributeNamespace = ns; _currentAttributeName = localName; _currentAttributeValue = string.Empty; } _state = WriteState.Attribute; } public override void WriteStartDocument() { if (ShouldDelegate) { _bufferingWriter.WriteStartDocument(); } } public override void WriteStartDocument(bool standalone) { if (ShouldDelegate) { _bufferingWriter.WriteStartDocument(standalone); } } public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString ns) { WriteStartElementCore(ref prefix, localName == null ? null : localName.Value, ns == null ? null : ns.Value); if (ShouldDelegate) { _bufferingWriter.WriteStartElement(prefix, localName, ns); } } public override void WriteStartElement(string prefix, string localName, string ns) { WriteStartElementCore(ref prefix, localName, ns); if (ShouldDelegate) { _bufferingWriter.WriteStartElement(prefix, localName, ns); } } private void WriteStartElementCore(ref string prefix, string localName, string ns) { if (_state == WriteState.Attribute) { ThrowBadStateException("WriteStartElement"); } if (localName == null || localName.Length == 0) { throw new ArgumentNullException("localName"); } OnPossibleEndOfBase64Content(); OnPossibleEndOfStartTag(WriteState.Element); if (_docPos == XmlDocumentPosition.BeforeRootElement) { _docPos = XmlDocumentPosition.InRootElement; } _manager.EnterElementContext(); if (ns == null) { if (prefix == null) { prefix = string.Empty; } ns = LookupNamespace(prefix); if (ns == null) { throw new InvalidOperationException(String.Format("Undefined use of prefix at Element: {0}, {1}", prefix, localName)); } } else if (prefix == null) { prefix = LookupPrefix(ns); if (prefix == null) { prefix = AutoGeneratePrefix(ns, false); } } _manager.AddLocalNamespaceIfNotRedundant(prefix, ns); _manager.MarkToRenderForVisiblyUsedPrefix(prefix, true, _contextProvider); PushElement(prefix, localName); _attributePrefixGenerationIndex = 0; } public override void WriteString(string s) { if (s == null) { throw new ArgumentNullException("s"); } WriteStringCore(s); if (ShouldDelegate) { CanonicalEncoder.WriteEscapedString(_bufferingWriter, s); } } public override void WriteString(XmlDictionaryString s) { if (s == null) { throw new ArgumentNullException("s"); } WriteStringCore(s.Value); if (ShouldDelegate) { _bufferingWriter.WriteString(s); } } private void WriteStringCore(string s) { WriteStringCore(s, false); } private void WriteStringCore(string s, bool isRaw) { OnPossibleEndOfBase64Content(); if (_state == WriteState.Attribute) { if (_currentAttributeValue.Length == 0) { _currentAttributeValue = s; } else { // attribute value concatenation path unlikely to be hit in most scenarios _currentAttributeValue += s; } } else { if (_state == WriteState.Element) { OnPossibleEndOfStartTag(WriteState.Content); } else if (_state != WriteState.Content) { ThrowBadStateException("WriteString"); } if (isRaw) { _encoder.Encode(s); } else { _encoder.EncodeWithTranslation(s, CanonicalEncoder.XmlStringType.TextContent); } } } private void WriteStringCore(char[] buffer, int offset, int count, bool isRaw, bool isBase64Generated) { if (!isBase64Generated) { OnPossibleEndOfBase64Content(); } if (_state == WriteState.Attribute) { if (_currentAttributeValue.Length == 0) { _currentAttributeValue = new string(buffer, offset, count); } else { // attribute value concatenation path unlikely to be hit in most scenarios _currentAttributeValue += new string(buffer, offset, count); } } else { if (_state == WriteState.Element) { OnPossibleEndOfStartTag(WriteState.Content); } else if (_state != WriteState.Content) { ThrowBadStateException("WriteString"); } if (isRaw || isBase64Generated) { _encoder.Encode(buffer, offset, count); } else { _encoder.EncodeWithTranslation(buffer, offset, count, CanonicalEncoder.XmlStringType.TextContent); } } } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { throw new NotSupportedException(); } public override void WriteValue(string value) { WriteStringCore(value); if (ShouldDelegate) { _bufferingWriter.WriteValue(value); } } public override void WriteWhitespace(string ws) { WriteStringCore(ws); if (ShouldDelegate) { _bufferingWriter.WriteWhitespace(ws); } } private struct ElementEntry { internal string prefix; internal string localName; public void Clear() { prefix = null; localName = null; } public void Set(string prefix, string localName) { this.prefix = prefix; this.localName = localName; } } } internal interface ICanonicalWriterEndRootElementCallback { void OnEndOfRootElement(CanonicalWriter writer); } // accumulates attributes of one element internal sealed class CanonicalAttributeManager { private const int InitialListSize = 8; private const int MaxPoolSize = 16; private AttributeEntry[] _list = new AttributeEntry[InitialListSize]; private int _count; private readonly Pool<AttributeEntry> _pool = new Pool<AttributeEntry>(MaxPoolSize); public CanonicalAttributeManager() { Clear(); } public void Add(string prefix, string localName, string namespaceUri, string value) { AttributeEntry entry = _pool.Take(); if (entry == null) { entry = new AttributeEntry(); } entry.Init(prefix, localName, namespaceUri, value); if (_count == _list.Length) { AttributeEntry[] newList = new AttributeEntry[_list.Length * 2]; Array.Copy(_list, 0, newList, 0, _count); _list = newList; } _list[_count++] = entry; } public void Clear() { for (int i = 0; i < _count; i++) { AttributeEntry entry = _list[i]; _list[i] = null; entry.Clear(); _pool.Return(entry); } _count = 0; } public XmlAttributeHolder[] Copy() { XmlAttributeHolder[] holder = new XmlAttributeHolder[_count]; for (int i = 0; i < _count; i++) { AttributeEntry a = _list[i]; holder[i] = new XmlAttributeHolder(a.prefix, a.localName, a.namespaceUri, a.value); } return holder; } public void Encode(CanonicalEncoder encoder) { for (int i = 0; i < _count; i++) { _list[i].Encode(encoder); } } public void Sort() { Array.Sort(_list, 0, _count, AttributeEntrySortOrder.Instance); } private sealed class AttributeEntry { internal string prefix; internal string localName; internal string namespaceUri; internal string value; public void Init(string prefix, string localName, string namespaceUri, string value) { this.prefix = prefix; this.localName = localName; this.namespaceUri = namespaceUri; this.value = value; } public void Clear() { prefix = null; localName = null; namespaceUri = null; value = null; } public void Encode(CanonicalEncoder encoder) { encoder.EncodeAttribute(prefix, localName, value); } public void WriteTo(XmlDictionaryWriter writer) { writer.WriteAttributeString(prefix, localName, namespaceUri, value); } } private sealed class AttributeEntrySortOrder : IComparer<AttributeEntry> { private static AttributeEntrySortOrder s_instance = new AttributeEntrySortOrder(); private AttributeEntrySortOrder() { } public static AttributeEntrySortOrder Instance { get { return s_instance; } } public int Compare(AttributeEntry x, AttributeEntry y) { int namespaceCompareResult = String.Compare(x.namespaceUri, y.namespaceUri, StringComparison.Ordinal); if (namespaceCompareResult != 0) { return namespaceCompareResult; } return String.Compare(x.localName, y.localName, StringComparison.Ordinal); } } } internal struct XmlAttributeHolder { private string _prefix; private string _ns; private string _localName; private string _value; public static XmlAttributeHolder[] emptyArray = new XmlAttributeHolder[0]; public XmlAttributeHolder(string prefix, string localName, string ns, string value) { _prefix = prefix; _localName = localName; _ns = ns; _value = value; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Registrasi_LABAddRI : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiLAB"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListJenisPenjamin(); GetListHubungan(); GetListStatus(); GetListPangkat(); GetListAgama(); GetListPendidikan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); GetNomorRegistrasi(); GetNomorTunggu(); GetListKelompokPemeriksaan(); GetListSatuanKerjaPenjamin(); } } //========= public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPenjamin.Items.Clear(); int i = 0; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkat() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); DataTable dt = myObj.GetList(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgamaPenjamin.Items.Clear(); int i = 0; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgamaPenjamin.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikanPenjamin.Items.Clear(); int i = 0; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikanPenjamin.SelectedIndex = i; i++; } } //========== public void GetNomorTunggu() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 42;//LAB myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); myObj.PoliklinikId = 42;//LAB myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); lblNoRegistrasi.Text = txtNoRegistrasi.Text; } public void GetListKelompokPemeriksaan() { SIMRS.DataAccess.RS_KelompokPemeriksaan myObj = new SIMRS.DataAccess.RS_KelompokPemeriksaan(); myObj.JenisPemeriksaanId = 1;//Laboratorium DataTable dt = myObj.GetListByJenisPemeriksaanId(); cmbKelompokPemeriksaan.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbKelompokPemeriksaan.Items.Add(""); cmbKelompokPemeriksaan.Items[i].Text = dr["Nama"].ToString(); cmbKelompokPemeriksaan.Items[i].Value = dr["Id"].ToString(); i++; } cmbKelompokPemeriksaan.SelectedIndex = 0; GetListPemeriksaan(); } public DataSet GetDataPemeriksaan() { DataSet ds = new DataSet(); if (Session["dsLayananLAB"] != null) ds = (DataSet)Session["dsLayananLAB"]; else { SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); myObj.PoliklinikId = 42;//Polklinik LAB DataTable myData = myObj.SelectAllWPoliklinikIdLogic(); ds.Tables.Add(myData); Session.Add("dsLayananLAB", ds); } return ds; } public void GetListPemeriksaan() { DataSet ds = new DataSet(); ds = GetDataPemeriksaan(); lstRefPemeriksaan.DataTextField = "Nama"; lstRefPemeriksaan.DataValueField = "Id"; DataView dv = ds.Tables[0].DefaultView; dv.RowFilter = " KelompokPemeriksaanId = " + cmbKelompokPemeriksaan.SelectedItem.Value; lstRefPemeriksaan.DataSource = dv; lstRefPemeriksaan.DataBind(); } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } if (txtPasienId.Text == "") { lblError.Text = "Data Pasien Belum dipilih !"; return; } int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbStatusPenjamin.SelectedIndex > 0) myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = Int64.Parse(txtPasienId.Text); GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; myRJ.AsalPasienId = Int64.Parse(txtRegistrasiId.Text); myRJ.PoliklinikId = 42;//LAB myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "") myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.Keterangan = txtKeterangan.Text; myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); ////Input Data Layanan SIMRS.DataAccess.RS_RJLayanan myLayanan = new SIMRS.DataAccess.RS_RJLayanan(); SIMRS.DataAccess.RS_Layanan myTarif = new SIMRS.DataAccess.RS_Layanan(); if (lstPemeriksaan.Items.Count > 0) { string[] kellay; string[] Namakellay; DataTable dt; for (int i = 0; i < lstPemeriksaan.Items.Count; i++) { myLayanan.RJLayananId = 0; myLayanan.RawatJalanId = myRJ.RawatJalanId; myLayanan.JenisLayananId = 3; kellay = lstPemeriksaan.Items[i].Value.Split('|'); Namakellay = lstPemeriksaan.Items[i].Text.Split(':'); myLayanan.KelompokLayananId = 2; myLayanan.LayananId = int.Parse(kellay[1]); myLayanan.NamaLayanan = Namakellay[1]; myTarif.Id = int.Parse(kellay[1]); dt = myTarif.GetTarifRIByLayananId(int.Parse(txtKelasId.Text)); if (dt.Rows.Count > 0) myLayanan.Tarif = dt.Rows[0]["Tarif"].ToString() != "" ? (Decimal)dt.Rows[0]["Tarif"] : 0; else myLayanan.Tarif = 0; myLayanan.JumlahSatuan = double.Parse("1"); myLayanan.Discount = 0; myLayanan.BiayaTambahan = 0; myLayanan.JumlahTagihan = myLayanan.Tarif; myLayanan.Keterangan = ""; myLayanan.CreatedBy = UserId; myLayanan.CreatedDate = DateTime.Now; myLayanan.Insert(); } } //================= string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("LABView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("LABList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPenjamin.Text = row["Nama"].ToString(); cmbHubungan.SelectedValue = row["HubunganId"].ToString(); txtUmurPenjamin.Text = row["Umur"].ToString(); txtAlamatPenjamin.Text = row["Alamat"].ToString(); txtTeleponPenjamin.Text = row["Telepon"].ToString(); cmbAgamaPenjamin.SelectedValue = row["AgamaId"].ToString(); cmbPendidikanPenjamin.SelectedValue = row["PendidikanId"].ToString(); cmbStatusPenjamin.SelectedValue = row["StatusId"].ToString(); cmbPangkatPenjamin.SelectedValue = row["PangkatId"].ToString(); txtNoKTPPenjamin.Text = row["NoKTP"].ToString(); txtGolDarahPenjamin.Text = row["GolDarah"].ToString(); txtNRPPenjamin.Text = row["NRP"].ToString(); //cmbSatuanKerjaPenjamin.Text = row["Kesatuan"].ToString(); txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString(); txtKeteranganPenjamin.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPerusahaan.Text = row["Nama"].ToString(); txtNamaKontak.Text = row["NamaKontak"].ToString(); txtAlamatPerusahaan.Text = row["Alamat"].ToString(); txtTeleponPerusahaan.Text = row["Telepon"].ToString(); txtFAXPerusahaan.Text = row["Fax"].ToString(); txtKeteranganPerusahaan.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { GetNomorTunggu(); GetNomorRegistrasi(); } protected void btnSearch_Click(object sender, EventArgs e) { GetListPasien(); EmptyFormPasien(); } public DataView GetResultSearch() { DataSet ds = new DataSet(); DataTable myData = new DataTable(); SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap(); if (txtNoRMSearch.Text != "") myObj.NoRM = txtNoRMSearch.Text; if (txtNamaSearch.Text != "") myObj.Nama = txtNamaSearch.Text; if (txtNRPSearch.Text != "") myObj.NRP = txtNRPSearch.Text; myData = myObj.SelectAllFilterLast(0,0,""); DataView dv = myData.DefaultView; return dv; } public void GetListPasien() { GridViewPasien.SelectedIndex = -1; // Re-binds the grid GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); } protected void GridViewPasien_SelectedIndexChanged(object sender, EventArgs e) { Int64 PaseinId = (Int64)GridViewPasien.SelectedValue; UpdateFormPasien(PaseinId); EmptyFormPejamin(); } public void UpdateFormPasien(Int64 RawatInapId) { SIMRS.DataAccess.RS_RawatInap myObj = new SIMRS.DataAccess.RS_RawatInap(); myObj.RawatInapId = RawatInapId; DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtPasienId.Text = row["PasienId"].ToString(); txtRawatInapId.Text = row["RawatInapId"].ToString(); txtRegistrasiId.Text = row["RegistrasiId"].ToString(); lblNoRMHeader.Text = row["NoRM"].ToString(); lblNoRM.Text = row["NoRM"].ToString(); lblNamaPasienHeader.Text = row["Nama"].ToString(); lblNamaPasien.Text = row["Nama"].ToString(); lblStatus.Text = row["StatusNama"].ToString(); lblPangkat.Text = row["PangkatNama"].ToString(); lblNoAskes.Text = row["NoAskes"].ToString(); lblNoKTP.Text = row["NoKTP"].ToString(); lblGolDarah.Text = row["GolDarah"].ToString(); lblNRP.Text = row["NRP"].ToString(); lblKesatuan.Text = row["Kesatuan"].ToString(); lblTempatLahir.Text = row["TempatLahir"].ToString() == "" ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : row["TempatLahir"].ToString(); lblTanggalLahir.Text = row["TanggalLahir"].ToString() != "" ? ((DateTime)row["TanggalLahir"]).ToString("dd MMMM yyyy"):""; lblAlamat.Text = row["Alamat"].ToString(); lblTelepon.Text = row["Telepon"].ToString(); lblJenisKelamin.Text = row["JenisKelamin"].ToString(); lblStatusPerkawinan.Text = row["StatusPerkawinanNama"].ToString(); lblAgama.Text = row["AgamaNama"].ToString(); lblPendidikan.Text = row["PendidikanNama"].ToString(); lblPekerjaan.Text = row["Pekerjaan"].ToString(); lblAlamatKantor.Text = row["AlamatKantor"].ToString(); lblTeleponKantor.Text = row["TeleponKantor"].ToString(); //lblKeterangan.Text = row["Keterangan"].ToString(); if (row["KelasNama"].ToString() != "") txtKeterangan.Text = "Pasien Rawa Inap Kelas: " + row["KelasNama"].ToString(); if (row["RuangNama"].ToString() != "") txtKeterangan.Text += " Ruangan: " + row["RuangNama"].ToString(); if (row["NomorRuang"].ToString() != "") txtKeterangan.Text += " Nomor Kamar: " + row["NomorRuang"].ToString(); if (row["KelasId"].ToString() != "") txtKelasId.Text = row["KelasId"].ToString(); else txtKelasId.Text = "0"; } else { EmptyFormPasien(); } SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.PasienId = Int64.Parse(txtPasienId.Text); DataTable dTbl = myReg.SelectOne_ByPasienId(); if (dTbl.Rows.Count > 0) { DataRow rs = dTbl.Rows[0]; txtPenjaminId.Text = rs["PenjaminId"].ToString(); } } public void EmptyFormPasien() { txtPasienId.Text = ""; txtRawatInapId.Text = ""; txtRegistrasiId.Text = ""; lblNoRMHeader.Text = ""; lblNoRM.Text = ""; lblNamaPasien.Text = ""; lblNamaPasienHeader.Text = ""; lblStatus.Text = ""; lblPangkat.Text = ""; lblNoAskes.Text = ""; lblNoKTP.Text = ""; lblGolDarah.Text = ""; lblNRP.Text = ""; lblKesatuan.Text = ""; lblTempatLahir.Text = ""; lblTanggalLahir.Text = ""; lblAlamat.Text = ""; lblTelepon.Text = ""; lblJenisKelamin.Text = ""; lblStatusPerkawinan.Text = ""; lblAgama.Text = ""; lblPendidikan.Text = ""; lblPekerjaan.Text = ""; lblAlamatKantor.Text = ""; lblTeleponKantor.Text = ""; lblKeterangan.Text = ""; txtKeterangan.Text = ""; txtKelasId.Text = "0"; } protected void GridViewPasien_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridViewPasien.SelectedIndex = -1; GridViewPasien.PageIndex = e.NewPageIndex; GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); EmptyFormPasien(); } protected void cmbKelompokPemeriksaan_SelectedIndexChanged(object sender, EventArgs e) { GetListPemeriksaan(); } protected void btnAddPemeriksaan_Click(object sender, EventArgs e) { if (lstRefPemeriksaan.SelectedIndex != -1) { int i = lstPemeriksaan.Items.Count; bool exist = false; string selectValue = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; for (int j = 0; j < i; j++) { if (lstPemeriksaan.Items[j].Value == selectValue) { exist = true; break; } } if (!exist) { ListItem newItem = new ListItem(); newItem.Text = cmbKelompokPemeriksaan.SelectedItem.Text + ": " + lstRefPemeriksaan.SelectedItem.Text; newItem.Value = cmbKelompokPemeriksaan.SelectedItem.Value + "|" + lstRefPemeriksaan.SelectedItem.Value; lstPemeriksaan.Items.Add(newItem); } } } protected void btnRemovePemeriksaan_Click(object sender, EventArgs e) { if (lstPemeriksaan.SelectedIndex != -1) { lstPemeriksaan.Items.RemoveAt(lstPemeriksaan.SelectedIndex); } } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) { cmbSatuanKerjaPenjamin.SelectedIndex = i; } i++; } } public void EmptyFormPejamin() { txtNamaPenjamin.Text = ""; cmbHubungan.SelectedValue = ""; txtUmurPenjamin.Text = ""; txtAlamatPenjamin.Text = ""; txtTeleponPenjamin.Text = ""; cmbAgamaPenjamin.SelectedIndex = 0; cmbPendidikanPenjamin.SelectedIndex = 0; cmbStatusPenjamin.SelectedIndex = 0; //cmbPangkatPenjamin.SelectedIndex = 0; txtNoKTPPenjamin.Text = ""; txtGolDarahPenjamin.Text = ""; txtNRPPenjamin.Text = ""; cmbSatuanKerjaPenjamin.SelectedIndex = 0; txtAlamatKesatuanPenjamin.Text = ""; txtKeteranganPenjamin.Text = ""; txtNamaPerusahaan.Text = ""; txtNamaKontak.Text = ""; txtAlamatPerusahaan.Text = ""; txtTeleponPerusahaan.Text = ""; txtFAXPerusahaan.Text = ""; txtKeteranganPerusahaan.Text = ""; } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using FluentAssertions; using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.InternalAbstractions; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Test.Utilities; using NuGet.Frameworks; using Xunit; namespace Microsoft.DotNet.Cli.Utils.Tests { public class GivenAProjectDependenciesCommandResolver : TestBase { private const string TestProjectName = "AppWithDirectDep"; [Fact] public void It_returns_null_when_CommandName_is_null() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] { "" }, ProjectDirectory = "/some/directory", Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_ProjectDirectory_is_null() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = null, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_Framework_is_null() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = null }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_Configuration_is_null() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] { "" }, ProjectDirectory = testInstance.Path, Configuration = null, Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_CommandName_does_not_exist_in_ProjectDependencies() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_a_CommandSpec_with_Dotnet_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectDependencies() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithBuildArtifacts() .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-hello", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void It_escapes_CommandArguments_when_returning_a_CommandSpec() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithBuildArtifacts() .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-hello", CommandArguments = new[] { "arg with space" }, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void It_passes_depsfile_arg_to_host_when_returning_a_CommandSpec() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithBuildArtifacts() .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-hello", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("--depsfile"); } [Fact] public void It_sets_depsfile_in_output_path_in_commandspec() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var outputDir = Path.Combine(testInstance.Path, "outdir"); var commandResolverArguments = new CommandResolverArguments { CommandName = "dotnet-hello", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10, OutputPath = outputDir }; var buildCommand = new BuildCommand( Path.Combine(testInstance.Path, "project.json"), output: outputDir, framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString()) .Execute().Should().Pass(); var projectContext = ProjectContext.Create( testInstance.Path, FrameworkConstants.CommonFrameworks.NetCoreApp10, DotnetRuntimeIdentifiers.InferCurrentRuntimeIdentifiers(DotnetFiles.VersionFileObject)); var depsFilePath = projectContext.GetOutputPaths("Debug", outputPath: outputDir).RuntimeFiles.DepsJson; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain($"--depsfile {depsFilePath}"); } [Fact] public void It_sets_depsfile_in_build_base_path_in_commandspec() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithLockFiles(); var buildBasePath = Path.Combine(testInstance.Path, "basedir"); var commandResolverArguments = new CommandResolverArguments { CommandName = "dotnet-hello", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10, BuildBasePath = buildBasePath }; var buildCommand = new BuildCommand( Path.Combine(testInstance.Path, "project.json"), buildBasePath: buildBasePath, framework: FrameworkConstants.CommonFrameworks.NetCoreApp10.ToString()) .Execute().Should().Pass(); var projectContext = ProjectContext.Create( testInstance.Path, FrameworkConstants.CommonFrameworks.NetCoreApp10, DotnetRuntimeIdentifiers.InferCurrentRuntimeIdentifiers(DotnetFiles.VersionFileObject)); var depsFilePath = projectContext.GetOutputPaths("Debug", buildBasePath).RuntimeFiles.DepsJson; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain($"--depsfile {depsFilePath}"); } [Fact] public void It_returns_a_CommandSpec_with_CommandName_in_Args_when_returning_a_CommandSpec_and_CommandArguments_are_null() { var projectDependenciesCommandResolver = SetupProjectDependenciesCommandResolver(); var testInstance = TestAssetsManager.CreateTestInstance(TestProjectName) .WithBuildArtifacts() .WithLockFiles(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-hello", CommandArguments = null, ProjectDirectory = testInstance.Path, Configuration = "Debug", Framework = FrameworkConstants.CommonFrameworks.NetCoreApp10 }; var result = projectDependenciesCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("dotnet-hello"); } private ProjectDependenciesCommandResolver SetupProjectDependenciesCommandResolver( IEnvironmentProvider environment = null, IPackagedCommandSpecFactory packagedCommandSpecFactory = null) { environment = environment ?? new EnvironmentProvider(); packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory(); var projectDependenciesCommandResolver = new ProjectDependenciesCommandResolver(environment, packagedCommandSpecFactory); return projectDependenciesCommandResolver; } } }
// 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: Some floating-point math operations ** ** ===========================================================*/ //This class contains only static members and doesn't require serialization. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { public static partial class Math { public const double E = 2.7182818284590452354; public const double PI = 3.14159265358979323846; private const int maxRoundingDigits = 15; private const double doubleRoundLimit = 1e16d; // This table is required for the Round function which can specify the number of digits to round to private static double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Abs(short value) { if (value < 0) { value = (short)-value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Abs(int value) { if (value < 0) { value = -value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Abs(long value) { if (value < 0) { value = -value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if (value < 0) { value = (sbyte)-value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Abs(decimal value) { return decimal.Abs(value); } [StackTraceHidden] private static void ThrowAbsOverflow() { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } public static long BigMul(int a, int b) { return ((long)a) * b; } public static double BitDecrement(double x) { var bits = BitConverter.DoubleToInt64Bits(x); if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000) { // NaN returns NaN // -Infinity returns -Infinity // +Infinity returns double.MaxValue return (bits == 0x7FF00000_00000000) ? double.MaxValue : x; } if (bits == 0x00000000_00000000) { // +0.0 returns -double.Epsilon return -double.Epsilon; } // Negative values need to be incremented // Positive values need to be decremented bits += ((bits < 0) ? +1 : -1); return BitConverter.Int64BitsToDouble(bits); } public static double BitIncrement(double x) { var bits = BitConverter.DoubleToInt64Bits(x); if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000) { // NaN returns NaN // -Infinity returns double.MinValue // +Infinity returns +Infinity return (bits == unchecked((long)(0xFFF00000_00000000))) ? double.MinValue : x; } if (bits == unchecked((long)(0x80000000_00000000))) { // -0.0 returns double.Epsilon return double.Epsilon; } // Negative values need to be decremented // Positive values need to be incremented bits += ((bits < 0) ? -1 : +1); return BitConverter.Int64BitsToDouble(bits); } public static unsafe double CopySign(double x, double y) { // This method is required to work for all inputs, // including NaN, so we operate on the raw bits. var xbits = BitConverter.DoubleToInt64Bits(x); var ybits = BitConverter.DoubleToInt64Bits(y); // If the sign bits of x and y are not the same, // flip the sign bit of x and return the new value; // otherwise, just return x if ((xbits ^ ybits) < 0) { return BitConverter.Int64BitsToDouble(xbits ^ long.MinValue); } return x; } public static int DivRem(int a, int b, out int result) { // TODO https://github.com/dotnet/coreclr/issues/3439: // Restore to using % and / when the JIT is able to eliminate one of the idivs. // In the meantime, a * and - is measurably faster than an extra /. int div = a / b; result = a - (div * b); return div; } public static long DivRem(long a, long b, out long result) { long div = a / b; result = a - (div * b); return div; } internal static uint DivRem(uint a, uint b, out uint result) { uint div = a / b; result = a - (div * b); return div; } internal static ulong DivRem(ulong a, ulong b, out ulong result) { ulong div = a / b; result = a - (div * b); return div; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Ceiling(decimal d) { return decimal.Ceiling(d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Clamp(byte value, byte min, byte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Clamp(decimal value, decimal min, decimal max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Clamp(double value, double min, double max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Clamp(short value, short min, short max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Clamp(int value, int min, int max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Clamp(long value, long min, long max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte Clamp(sbyte value, sbyte min, sbyte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp(float value, float min, float max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort Clamp(ushort value, ushort min, ushort max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Clamp(uint value, uint min, uint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Clamp(ulong value, ulong min, ulong max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } else if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Floor(decimal d) { return decimal.Floor(d); } public static double IEEERemainder(double x, double y) { if (double.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (double.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } var regularMod = x % y; if (double.IsNaN(regularMod)) { return double.NaN; } if ((regularMod == 0) && double.IsNegative(x)) { return double.NegativeZero; } var alternativeResult = (regularMod - (Abs(y) * Sign(x))); if (Abs(alternativeResult) == Abs(regularMod)) { var divisionResult = x / y; var roundedResult = Round(divisionResult); if (Abs(roundedResult) > Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Abs(alternativeResult) < Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } public static double Log(double a, double newBase) { if (double.IsNaN(a)) { return a; // IEEE 754-2008: NaN payload must be preserved } if (double.IsNaN(newBase)) { return newBase; // IEEE 754-2008: NaN payload must be preserved } if (newBase == 1) { return double.NaN; } if ((a != 1) && ((newBase == 0) || double.IsPositiveInfinity(newBase))) { return double.NaN; } return (Log(a) / Log(newBase)); } [NonVersionable] public static byte Max(byte val1, byte val2) { return (val1 >= val2) ? val1 : val2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Max(decimal val1, decimal val2) { return decimal.Max(val1, val2); } public static double Max(double val1, double val2) { // When val1 and val2 are both finite or infinite, return the larger // * We count +0.0 as larger than -0.0 to match MSVC // When val1 or val2, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (double.IsNaN(val1)) { return val2; } if (double.IsNaN(val2)) { return val1; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT // which would then return an incorrect value if (val1 == val2) { return double.IsNegative(val1) ? val2 : val1; } return (val1 < val2) ? val2 : val1; } [NonVersionable] public static short Max(short val1, short val2) { return (val1 >= val2) ? val1 : val2; } [NonVersionable] public static int Max(int val1, int val2) { return (val1 >= val2) ? val1 : val2; } [NonVersionable] public static long Max(long val1, long val2) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static sbyte Max(sbyte val1, sbyte val2) { return (val1 >= val2) ? val1 : val2; } public static float Max(float val1, float val2) { // When val1 and val2 are both finite or infinite, return the larger // * We count +0.0 as larger than -0.0 to match MSVC // When val1 or val2, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (float.IsNaN(val1)) { return val2; } if (float.IsNaN(val2)) { return val1; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT // which would then return an incorrect value if (val1 == val2) { return float.IsNegative(val1) ? val2 : val1; } return (val1 < val2) ? val2 : val1; } [CLSCompliant(false)] [NonVersionable] public static ushort Max(ushort val1, ushort val2) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static uint Max(uint val1, uint val2) { return (val1 >= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static ulong Max(ulong val1, ulong val2) { return (val1 >= val2) ? val1 : val2; } public static double MaxMagnitude(double x, double y) { // When x and y are both finite or infinite, return the larger magnitude // * We count +0.0 as larger than -0.0 to match MSVC // When x or y, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (double.IsNaN(x)) { return y; } if (double.IsNaN(y)) { return x; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would // then return an incorrect value double ax = Abs(x); double ay = Abs(y); if (ax == ay) { return double.IsNegative(x) ? y : x; } return (ax < ay) ? y : x; } [NonVersionable] public static byte Min(byte val1, byte val2) { return (val1 <= val2) ? val1 : val2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Min(decimal val1, decimal val2) { return decimal.Min(val1, val2); } public static double Min(double val1, double val2) { // When val1 and val2 are both finite or infinite, return the smaller // * We count -0.0 as smaller than -0.0 to match MSVC // When val1 or val2, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (double.IsNaN(val1)) { return val2; } if (double.IsNaN(val2)) { return val1; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT // which would then return an incorrect value if (val1 == val2) { return double.IsNegative(val1) ? val1 : val2; } return (val1 < val2) ? val1 : val2; } [NonVersionable] public static short Min(short val1, short val2) { return (val1 <= val2) ? val1 : val2; } [NonVersionable] public static int Min(int val1, int val2) { return (val1 <= val2) ? val1 : val2; } [NonVersionable] public static long Min(long val1, long val2) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static sbyte Min(sbyte val1, sbyte val2) { return (val1 <= val2) ? val1 : val2; } public static float Min(float val1, float val2) { // When val1 and val2 are both finite or infinite, return the smaller // * We count -0.0 as smaller than -0.0 to match MSVC // When val1 or val2, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (float.IsNaN(val1)) { return val2; } if (float.IsNaN(val2)) { return val1; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (val1 < val2) first could get transformed into (val2 >= val1) by the JIT // which would then return an incorrect value if (val1 == val2) { return float.IsNegative(val1) ? val1 : val2; } return (val1 < val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static ushort Min(ushort val1, ushort val2) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static uint Min(uint val1, uint val2) { return (val1 <= val2) ? val1 : val2; } [CLSCompliant(false)] [NonVersionable] public static ulong Min(ulong val1, ulong val2) { return (val1 <= val2) ? val1 : val2; } public static double MinMagnitude(double x, double y) { // When x and y are both finite or infinite, return the smaller magnitude // * We count -0.0 as smaller than -0.0 to match MSVC // When x or y, but not both, are NaN return the opposite // * We return the opposite if either is NaN to match MSVC if (double.IsNaN(x)) { return y; } if (double.IsNaN(y)) { return x; } // We do this comparison first and separately to handle the -0.0 to +0.0 comparision // * Doing (ax < ay) first could get transformed into (ay >= ax) by the JIT which would // then return an incorrect value double ax = Abs(x); double ay = Abs(y); if (ax == ay) { return double.IsNegative(x) ? x : y; } return (ax < ay) ? x : y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d) { return decimal.Round(d, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, int decimals) { return decimal.Round(d, decimals); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, MidpointRounding mode) { return decimal.Round(d, 0, mode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, int decimals, MidpointRounding mode) { return decimal.Round(d, decimals, mode); } [Intrinsic] public static double Round(double a) { // ************************************************************************************ // IMPORTANT: Do not change this implementation without also updating Math.Round(double), // FloatingPointUtils::round(double), and FloatingPointUtils::round(float) // ************************************************************************************ // If the number has no fractional part do nothing // This shortcut is necessary to workaround precision loss in borderline cases on some platforms if (a == (double)((long)a)) { return a; } // We had a number that was equally close to 2 integers. // We need to return the even one. double flrTempVal = Floor(a + 0.5); if ((a == (Floor(a) + 0.5)) && (FMod(flrTempVal, 2.0) != 0)) { flrTempVal -= 1.0; } return CopySign(flrTempVal, a); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Round(double value, int digits) { return Round(value, digits, MidpointRounding.ToEven); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public static unsafe double Round(double value, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) { throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits); } if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } if (Abs(value) < doubleRoundLimit) { var power10 = roundPower10Double[digits]; value *= power10; switch (mode) { // Rounds to the nearest value; if the number falls midway, // it is rounded to the nearest value with an even least significant digit case MidpointRounding.ToEven: { value = Round(value); break; } // Rounds to the nearest value; if the number falls midway, // it is rounded to the nearest value above (for positive numbers) or below (for negative numbers) case MidpointRounding.AwayFromZero: { double fraction = ModF(value, &value); if (Abs(fraction) >= 0.5) { value += Sign(fraction); } break; } // Directed rounding: Round to the nearest value, toward to zero case MidpointRounding.ToZero: { value = Truncate(value); break; } // Directed Rounding: Round down to the next value, toward negative infinity case MidpointRounding.ToNegativeInfinity: { value = Floor(value); break; } // Directed rounding: Round up to the next value, toward positive infinity case MidpointRounding.ToPositiveInfinity: { value = Ceiling(value); break; } default: { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } } value /= power10; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(decimal value) { return decimal.Sign(value); } public static int Sign(double value) { if (value < 0) { return -1; } else if (value > 0) { return 1; } else if (value == 0) { return 0; } throw new ArithmeticException(SR.Arithmetic_NaN); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(short value) { return Sign((int)value); } public static int Sign(int value) { return unchecked(value >> 31 | (int)((uint)-value >> 31)); } public static int Sign(long value) { return unchecked((int)(value >> 63 | (long)((ulong)-value >> 63))); } [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(sbyte value) { return Sign((int)value); } public static int Sign(float value) { if (value < 0) { return -1; } else if (value > 0) { return 1; } else if (value == 0) { return 0; } throw new ArithmeticException(SR.Arithmetic_NaN); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Truncate(decimal d) { return decimal.Truncate(d); } public static unsafe double Truncate(double d) { ModF(d, &d); return d; } private static void ThrowMinMaxException<T>(T min, T max) { throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max)); } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Provides access to all native methods provided by <c>NativeExtension</c>. /// An extra level of indirection is added to P/Invoke calls to allow intelligent loading /// of the right configuration of the native extension based on current platform, architecture etc. /// </summary> internal class NativeMethods { #region Native methods public readonly Delegates.grpcsharp_init_delegate grpcsharp_init; public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown; public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string; public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create; public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata; public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length; public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details; public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata; public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled; public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy; public readonly Delegates.grpcsharp_request_call_context_create_delegate grpcsharp_request_call_context_create; public readonly Delegates.grpcsharp_request_call_context_call_delegate grpcsharp_request_call_context_call; public readonly Delegates.grpcsharp_request_call_context_method_delegate grpcsharp_request_call_context_method; public readonly Delegates.grpcsharp_request_call_context_host_delegate grpcsharp_request_call_context_host; public readonly Delegates.grpcsharp_request_call_context_deadline_delegate grpcsharp_request_call_context_deadline; public readonly Delegates.grpcsharp_request_call_context_request_metadata_delegate grpcsharp_request_call_context_request_metadata; public readonly Delegates.grpcsharp_request_call_context_destroy_delegate grpcsharp_request_call_context_destroy; public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create; public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release; public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel; public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status; public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary; public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming; public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming; public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming; public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message; public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client; public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server; public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message; public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata; public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside; public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata; public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials; public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer; public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy; public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create; public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string; public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer; public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy; public readonly Delegates.grpcsharp_override_default_ssl_roots grpcsharp_override_default_ssl_roots; public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create; public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create; public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release; public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create; public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create; public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call; public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state; public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state; public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target; public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy; public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event; public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create; public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown; public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next; public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck; public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy; public readonly Delegates.gprsharp_free_delegate gprsharp_free; public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create; public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add; public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count; public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key; public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value; public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full; public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log; public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin; public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin; public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create; public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release; public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create; public readonly Delegates.grpcsharp_server_register_completion_queue_delegate grpcsharp_server_register_completion_queue; public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port; public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port; public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start; public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call; public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls; public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback; public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy; public readonly Delegates.gprsharp_now_delegate gprsharp_now; public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future; public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past; public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type; public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec; public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback; public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop; #endregion public NativeMethods(UnmanagedLibrary library) { this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library); this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library); this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library); this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library); this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library); this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library); this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library); this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library); this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library); this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library); this.grpcsharp_request_call_context_create = GetMethodDelegate<Delegates.grpcsharp_request_call_context_create_delegate>(library); this.grpcsharp_request_call_context_call = GetMethodDelegate<Delegates.grpcsharp_request_call_context_call_delegate>(library); this.grpcsharp_request_call_context_method = GetMethodDelegate<Delegates.grpcsharp_request_call_context_method_delegate>(library); this.grpcsharp_request_call_context_host = GetMethodDelegate<Delegates.grpcsharp_request_call_context_host_delegate>(library); this.grpcsharp_request_call_context_deadline = GetMethodDelegate<Delegates.grpcsharp_request_call_context_deadline_delegate>(library); this.grpcsharp_request_call_context_request_metadata = GetMethodDelegate<Delegates.grpcsharp_request_call_context_request_metadata_delegate>(library); this.grpcsharp_request_call_context_destroy = GetMethodDelegate<Delegates.grpcsharp_request_call_context_destroy_delegate>(library); this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library); this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library); this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library); this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library); this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library); this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library); this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library); this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library); this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library); this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library); this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library); this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library); this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library); this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library); this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library); this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library); this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library); this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library); this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library); this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library); this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library); this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library); this.grpcsharp_override_default_ssl_roots = GetMethodDelegate<Delegates.grpcsharp_override_default_ssl_roots>(library); this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library); this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library); this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library); this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library); this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library); this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library); this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library); this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library); this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library); this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library); this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library); this.grpcsharp_completion_queue_create = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_delegate>(library); this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library); this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library); this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library); this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library); this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library); this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library); this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library); this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library); this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library); this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library); this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library); this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library); this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library); this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library); this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library); this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library); this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library); this.grpcsharp_server_register_completion_queue = GetMethodDelegate<Delegates.grpcsharp_server_register_completion_queue_delegate>(library); this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library); this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library); this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library); this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library); this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library); this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library); this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library); this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library); this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library); this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library); this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library); this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library); this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library); this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library); } /// <summary> /// Gets singleton instance of this class. /// </summary> public static NativeMethods Get() { return NativeExtension.Get().NativeMethods; } static T GetMethodDelegate<T>(UnmanagedLibrary library) where T : class { var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate"); return library.GetNativeMethodDelegate<T>(methodName); } static string RemoveStringSuffix(string str, string toRemove) { if (!str.EndsWith(toRemove)) { return str; } return str.Substring(0, str.Length - toRemove.Length); } /// <summary> /// Delegate types for all published native methods. Declared under inner class to prevent scope pollution. /// </summary> public class Delegates { public delegate void grpcsharp_init_delegate(); public delegate void grpcsharp_shutdown_delegate(); public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char* public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate(); public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen); public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx, out UIntPtr detailsLength); public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx); public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx); public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx); public delegate RequestCallContextSafeHandle grpcsharp_request_call_context_create_delegate(); public delegate CallSafeHandle grpcsharp_request_call_context_call_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_method_delegate(RequestCallContextSafeHandle ctx, out UIntPtr methodLength); public delegate IntPtr grpcsharp_request_call_context_host_delegate(RequestCallContextSafeHandle ctx, out UIntPtr hostLength); public delegate Timespec grpcsharp_request_call_context_deadline_delegate(RequestCallContextSafeHandle ctx); public delegate IntPtr grpcsharp_request_call_context_request_metadata_delegate(RequestCallContextSafeHandle ctx); public delegate void grpcsharp_request_call_context_destroy_delegate(IntPtr ctx); public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2); public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials); public delegate CallError grpcsharp_call_cancel_delegate(CallSafeHandle call); public delegate CallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description); public delegate CallError grpcsharp_call_start_unary_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags); public delegate CallError grpcsharp_call_send_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, bool sendEmptyInitialMetadata); public delegate CallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, byte[] statusMessage, UIntPtr statusMessageLen, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, byte[] optionalSendBuffer, UIntPtr optionalSendBufferLen, WriteFlags writeFlags); public delegate CallError grpcsharp_call_recv_message_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call, BatchContextSafeHandle ctx); public delegate CallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); public delegate CallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials); public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call); public delegate void grpcsharp_call_destroy_delegate(IntPtr call); public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs); public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value); public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value); public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args); public delegate void grpcsharp_override_default_ssl_roots(string pemRootCerts); public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey); public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds); public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials); public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs); public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs); public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline); public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect); public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState, Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call); public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel); public delegate int grpcsharp_sizeof_grpc_event_delegate(); public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_delegate(); public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq); public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag); public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq); public delegate void gprsharp_free_delegate(IntPtr ptr); public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity); public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength); public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray); public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr keyLength); public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index, out UIntPtr valueLength); public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array); public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback); public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor); public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails); public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth); public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials); public delegate ServerSafeHandle grpcsharp_server_create_delegate(ChannelArgsSafeHandle args); public delegate void grpcsharp_server_register_completion_queue_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq); public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr); public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds); public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server); public delegate CallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, RequestCallContextSafeHandle ctx); public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server); public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx); public delegate void grpcsharp_server_destroy_delegate(IntPtr server); public delegate Timespec gprsharp_now_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_future_delegate(ClockType clockType); public delegate Timespec gprsharp_inf_past_delegate(ClockType clockType); public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, ClockType targetClock); public delegate int gprsharp_sizeof_timespec_delegate(); public delegate CallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback); public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr); } } }
/* * 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; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Linq.Expressions; using System.Reflection; using NUnit.Framework; using NUnit.Framework.Constraints; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.Tests { public static class Constraints { //This is here because C# has a gap in the language, you can't infer type from a constructor public static PropertyCompareConstraint<T> PropertyCompareConstraint<T>(T expected) { return new PropertyCompareConstraint<T>(expected); } } public class PropertyCompareConstraint<T> : NUnit.Framework.Constraints.Constraint { private readonly object _expected; //the reason everywhere uses propertyNames.Reverse().ToArray() is because the stack is backwards of the order we want to display the properties in. private string failingPropertyName = string.Empty; private object failingExpected; private object failingActual; public PropertyCompareConstraint(T expected) { _expected = expected; } public override bool Matches(object actual) { return ObjectCompare(_expected, actual, new Stack<string>()); } private bool ObjectCompare(object expected, object actual, Stack<string> propertyNames) { //If they are both null, they are equal if (actual == null && expected == null) return true; //If only one is null, then they aren't if (actual == null || expected == null) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } //prevent loops... if (propertyNames.Count > 50) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } if (actual.GetType() != expected.GetType()) { propertyNames.Push("GetType()"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actual.GetType(); failingExpected = expected.GetType(); return false; } if (actual.GetType() == typeof(Color)) { Color actualColor = (Color) actual; Color expectedColor = (Color) expected; if (actualColor.R != expectedColor.R) { propertyNames.Push("R"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.R; failingExpected = expectedColor.R; return false; } if (actualColor.G != expectedColor.G) { propertyNames.Push("G"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.G; failingExpected = expectedColor.G; return false; } if (actualColor.B != expectedColor.B) { propertyNames.Push("B"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.B; failingExpected = expectedColor.B; return false; } if (actualColor.A != expectedColor.A) { propertyNames.Push("A"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); propertyNames.Pop(); failingActual = actualColor.A; failingExpected = expectedColor.A; return false; } return true; } IComparable comp = actual as IComparable; if (comp != null) { if (comp.CompareTo(expected) != 0) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } return true; } //Now try the much more annoying IComparable<T> Type icomparableInterface = actual.GetType().GetInterface("IComparable`1"); if (icomparableInterface != null) { int result = (int)icomparableInterface.GetMethod("CompareTo").Invoke(actual, new[] { expected }); if (result != 0) { failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actual; failingExpected = expected; return false; } return true; } IEnumerable arr = actual as IEnumerable; if (arr != null) { List<object> actualList = arr.Cast<object>().ToList(); List<object> expectedList = ((IEnumerable)expected).Cast<object>().ToList(); if (actualList.Count != expectedList.Count) { propertyNames.Push("Count"); failingPropertyName = string.Join(".", propertyNames.Reverse().ToArray()); failingActual = actualList.Count; failingExpected = expectedList.Count; propertyNames.Pop(); return false; } //actualList and expectedList should be the same size. for (int i = 0; i < actualList.Count; i++) { propertyNames.Push("[" + i + "]"); if (!ObjectCompare(expectedList[i], actualList[i], propertyNames)) return false; propertyNames.Pop(); } //Everything seems okay... return true; } //Skip static properties. I had a nasty problem comparing colors because of all of the public static colors. PropertyInfo[] properties = expected.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (ignores.Contains(property.Name)) continue; object actualValue = property.GetValue(actual, null); object expectedValue = property.GetValue(expected, null); propertyNames.Push(property.Name); if (!ObjectCompare(expectedValue, actualValue, propertyNames)) return false; propertyNames.Pop(); } return true; } public override void WriteDescriptionTo(MessageWriter writer) { writer.WriteExpectedValue(failingExpected); } public override void WriteActualValueTo(MessageWriter writer) { writer.WriteActualValue(failingActual); writer.WriteLine(); writer.Write(" On Property: " + failingPropertyName); } //These notes assume the lambda: (x=>x.Parent.Value) //ignores should really contain like a fully dotted version of the property name, but I'm starting with small steps readonly List<string> ignores = new List<string>(); public PropertyCompareConstraint<T> IgnoreProperty(Expression<Func<T, object>> func) { Expression express = func.Body; PullApartExpression(express); return this; } private void PullApartExpression(Expression express) { //This deals with any casts... like implicit casts to object. Not all UnaryExpression are casts, but this is a first attempt. if (express is UnaryExpression) PullApartExpression(((UnaryExpression)express).Operand); if (express is MemberExpression) { //If the inside of the lambda is the access to x, we've hit the end of the chain. // We should track by the fully scoped parameter name, but this is the first rev of doing this. ignores.Add(((MemberExpression)express).Member.Name); } } } [TestFixture] public class PropertyCompareConstraintTest { public class HasInt { public int TheValue { get; set; } } [Test] public void IntShouldMatch() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 5 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void IntShouldNotMatch() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 4 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void IntShouldIgnore() { HasInt actual = new HasInt { TheValue = 5 }; HasInt expected = new HasInt { TheValue = 4 }; var constraint = Constraints.PropertyCompareConstraint(expected).IgnoreProperty(x => x.TheValue); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void AssetShouldMatch() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture); AssetBase expected = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void AssetShouldNotMatch() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture); AssetBase expected = new AssetBase(UUID.Random(), "asset one", (sbyte)AssetType.Texture); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void AssetShouldNotMatch2() { UUID uuid1 = UUID.Random(); AssetBase actual = new AssetBase(uuid1, "asset one", (sbyte)AssetType.Texture); AssetBase expected = new AssetBase(uuid1, "asset two", (sbyte)AssetType.Texture); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void UUIDShouldMatch() { UUID uuid1 = UUID.Random(); UUID uuid2 = UUID.Parse(uuid1.ToString()); var constraint = Constraints.PropertyCompareConstraint(uuid1); Assert.That(constraint.Matches(uuid2), Is.True); } [Test] public void UUIDShouldNotMatch() { UUID uuid1 = UUID.Random(); UUID uuid2 = UUID.Random(); var constraint = Constraints.PropertyCompareConstraint(uuid1); Assert.That(constraint.Matches(uuid2), Is.False); } [Test] public void TestColors() { Color actual = Color.Red; Color expected = Color.FromArgb(actual.A, actual.R, actual.G, actual.B); var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void ShouldCompareLists() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2, 3 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.True); } [Test] public void ShouldFailToCompareListsThatAreDifferent() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2, 4 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } [Test] public void ShouldFailToCompareListsThatAreDifferentLengths() { List<int> expected = new List<int> { 1, 2, 3 }; List<int> actual = new List<int> { 1, 2 }; var constraint = Constraints.PropertyCompareConstraint(expected); Assert.That(constraint.Matches(actual), Is.False); } public class Recursive { public Recursive Other { get; set; } } [Test] public void ErrorsOutOnRecursive() { Recursive parent = new Recursive(); Recursive child = new Recursive(); parent.Other = child; child.Other = parent; var constraint = Constraints.PropertyCompareConstraint(child); Assert.That(constraint.Matches(child), Is.False); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Equivalency; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.TestKit { public abstract class TransactionalStateStorageTestRunner<TState> : TransactionTestRunnerBase where TState : class, new() { protected Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory; protected Func<int, TState> stateFactory; protected Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig; /// <summary> /// Constructor /// </summary> /// <param name="stateStorageFactory">factory to create ITransactionalStateStorage, the test runner are assuming the state /// in storage is empty when ITransactionalStateStorage was created </param> /// <param name="stateFactory">factory to create TState for test</param> /// <param name="grainFactory">grain Factory needed for test runner</param> /// <param name="testOutput">test output to helpful messages</param> /// <param name="assertConfig">A reference to the FluentAssertions.Equivalency.EquivalencyAssertionOptions`1 /// configuration object that can be used to influence the way the object graphs /// are compared</param> protected TransactionalStateStorageTestRunner(Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory, Func<int, TState> stateFactory, IGrainFactory grainFactory, Action<string> testOutput, Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig = null) :base(grainFactory, testOutput) { this.stateStorageFactory = stateStorageFactory; this.stateFactory = stateFactory; this.assertConfig = assertConfig; } public virtual async Task FirstTime_Load_ShouldReturnEmptyLoadResponse() { var stateStorage = await this.stateStorageFactory(); var response = await stateStorage.Load(); var defaultStateValue = new TState(); //Assertion response.Should().NotBeNull(); response.ETag.Should().BeNull(); response.CommittedSequenceId.Should().Be(0); AssertTState(response.CommittedState, defaultStateValue); response.PendingStates.Should().BeEmpty(); } private static List<PendingTransactionState<TState>> emptyPendingStates = new List<PendingTransactionState<TState>>(); public virtual async Task StoreWithoutChanges() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store without any changes var etag1 = await stateStorage.Store(loadresponse.ETag, loadresponse.Metadata, emptyPendingStates, null, null); // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().Be(etag1); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update metadata, then write back var now = DateTime.UtcNow; var cr = MakeCommitRecords(2, 2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(etag1, metadata, emptyPendingStates, null, null); // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } public virtual async Task WrongEtags() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store with wrong e-tag, must fail try { var etag1 = await stateStorage.Store("wrong-etag", loadresponse.Metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().BeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update timestamp in metadata, then write back with correct e-tag var now = DateTime.UtcNow; var cr = MakeCommitRecords(2,2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(null, metadata, emptyPendingStates, null, null); // update timestamp in metadata, then write back with wrong e-tag, must fail try { var now2 = DateTime.UtcNow; var metadata2 = new TransactionalStateMetaData() { TimeStamp = now2, CommitRecords = MakeCommitRecords(3,3) }; await stateStorage.Store(null, metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } private void AssertTState(TState actual, TState expected) { if(assertConfig == null) actual.ShouldBeEquivalentTo(expected); else actual.ShouldBeEquivalentTo(expected, assertConfig); } private PendingTransactionState<TState> MakePendingState(long seqno, TState val, bool tm) { var result = new PendingTransactionState<TState>() { SequenceId = seqno, TimeStamp = DateTime.UtcNow, TransactionId = Guid.NewGuid().ToString(), TransactionManager = tm ? default(ParticipantId) : MakeParticipantId(), State = new TState() }; result.State = val; return result; } private ParticipantId MakeParticipantId() { return new ParticipantId( "tm", null, // (GrainReference) grainFactory.GetGrain<ITransactionTestGrain>(Guid.NewGuid(), TransactionTestConstants.SingleStateTransactionalGrain), ParticipantId.Role.Resource | ParticipantId.Role.Manager); } private Dictionary<Guid, CommitRecord> MakeCommitRecords(int count, int size) { var result = new Dictionary<Guid, CommitRecord>(); for (int j = 0; j < size; j++) { var r = new CommitRecord() { Timestamp = DateTime.UtcNow, WriteParticipants = new List<ParticipantId>(), }; for (int i = 0; i < size; i++) { r.WriteParticipants.Add(MakeParticipantId()); } result.Add(Guid.NewGuid(), r); } return result; } private async Task PrepareOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); _ = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState); } public virtual async Task ConfirmOne(bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); } else { _ = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, 1, null); } loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState, expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate = MakePendingState(1, this.stateFactory(123), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState1 = this.stateFactory(123); var expectedState2 = this.stateFactory(456); var pendingstate1 = MakePendingState(1, expectedState1, false); var pendingstate2 = MakePendingState(1, expectedState2, false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1 }, null, null); _ = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate2 }, null, null); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate2.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate2.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate2.TransactionId); AssertTState(loadresponse.PendingStates[0].State,expectedState2); } public virtual async Task ConfirmOneAndCancelOne(bool useTwoSteps = false, bool reverseOrder = false) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate1 = MakePendingState(1, expectedState, false); var pendingstate2 = MakePendingState(2, this.stateFactory(456), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2 }, null, null); if (useTwoSteps) { if (reverseOrder) { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } else { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } } else { _ = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, 1); } loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task PrepareMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstates = new List<PendingTransactionState<TState>>(); var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } _ = await stateStorage.Store(etag, metadata, pendingstates, null, null); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i+1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State,expectedStates[i]); } } public virtual async Task ConfirmMany(int count, bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, count, null); } else { _ = await stateStorage.Store(etag, metadata, pendingstates, count, null); } loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(count); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedStates[count - 1]); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); _ = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates1 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates1.Add(this.stateFactory(i * 1000 + 1)); } var expectedStates2 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates2.Add(this.stateFactory(i * 1000)); } var pendingstates1 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates1.Add(MakePendingState(i + 1, expectedStates1[i], false)); } var pendingstates2 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates2.Add(MakePendingState(i + 1, expectedStates2[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates1, null, null); _ = await stateStorage.Store(etag, metadata, pendingstates2, null, null); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i + 1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates2[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates2[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates2[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State, expectedStates2[i]); } } public virtual async Task GrowingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate3b = MakePendingState(3, this.stateFactory(33), false); var pendingstate4b = MakePendingState(4, this.stateFactory(44), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var expectedState6 = this.stateFactory(66); var pendingstate6 = MakePendingState(6, expectedState6, false); var expectedState7 = this.stateFactory(77); var pendingstate7 = MakePendingState(7, expectedState7, false); var expectedState8 = this.stateFactory(88); var pendingstate8 = MakePendingState(8, expectedState8, false); // prepare 1,2,3a,4a etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a}, null, null); // replace 3b,4b, prepare 5, 6, 7, 8 confirm 1, 2, 3b, 4b, 5, 6 _ = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, 6, null); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(6); AssertTState(loadresponse.CommittedState, expectedState6); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(2); loadresponse.PendingStates[0].SequenceId.Should().Be(7); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate7.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate7.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate7.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState7); loadresponse.PendingStates[1].SequenceId.Should().Be(8); loadresponse.PendingStates[1].TimeStamp.Should().Be(pendingstate8.TimeStamp); loadresponse.PendingStates[1].TransactionManager.Should().Be(pendingstate8.TransactionManager); loadresponse.PendingStates[1].TransactionId.Should().Be(pendingstate8.TransactionId); AssertTState(loadresponse.PendingStates[1].State, expectedState8); } public virtual async Task ShrinkingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var pendingstate6 = MakePendingState(6, this.stateFactory(66), false); var pendingstate7 = MakePendingState(7, this.stateFactory(77), false); var pendingstate8 = MakePendingState(8, this.stateFactory(88), false); var expectedState3b = this.stateFactory(33); var pendingstate3b = MakePendingState(3, expectedState3b, false); var expectedState4b = this.stateFactory(44); var pendingstate4b = MakePendingState(4, expectedState4b, false); // prepare 1,2,3a,4a, 5, 6, 7, 8 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, null, null); // replace 3b,4b, confirm 1, 2, 3b, cancel 5, 6, 7, 8 _ = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b }, 3, 4); loadresponse = await stateStorage.Load(); _ = loadresponse.ETag; _ = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(3); AssertTState(loadresponse.CommittedState, expectedState3b); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(4); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate4b.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate4b.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate4b.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState4b); } } }
using UnityEngine; using System.Collections; [AddComponentMenu("2D Toolkit/Sprite/tk2dSlicedSprite")] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(MeshFilter))] [ExecuteInEditMode] /// <summary> /// Sprite implementation that implements 9-slice scaling. /// </summary> public class tk2dSlicedSprite : tk2dBaseSprite { Mesh mesh; Vector2[] meshUvs; Vector3[] meshVertices; Color32[] meshColors; Vector3[] meshNormals = null; Vector4[] meshTangents = null; int[] meshIndices; [SerializeField] Vector2 _dimensions = new Vector2(50.0f, 50.0f); [SerializeField] Anchor _anchor = Anchor.LowerLeft; [SerializeField] bool _borderOnly = false; [SerializeField] bool legacyMode = false; // purely for fixup in 2D Toolkit 2.0 /// <summary> /// Gets or sets border only. When true, the quad in the middle of the /// sliced sprite is omitted, thus only drawing a border and saving fillrate /// </summary> public bool BorderOnly { get { return _borderOnly; } set { if (value != _borderOnly) { _borderOnly = value; UpdateIndices(); } } } /// <summary> /// Gets or sets the dimensions. /// </summary> /// <value> /// Use this to change the dimensions of the sliced sprite in pixel units /// </value> public Vector2 dimensions { get { return _dimensions; } set { if (value != _dimensions) { _dimensions = value; UpdateVertices(); UpdateCollider(); } } } /// <summary> /// The anchor position for this sliced sprite /// </summary> public Anchor anchor { get { return _anchor; } set { if (value != _anchor) { _anchor = value; UpdateVertices(); UpdateCollider(); } } } /// <summary> /// Top border in sprite fraction (0 - Top, 1 - Bottom) /// </summary> public float borderTop = 0.2f; /// <summary> /// Bottom border in sprite fraction (0 - Bottom, 1 - Top) /// </summary> public float borderBottom = 0.2f; /// <summary> /// Left border in sprite fraction (0 - Left, 1 - Right) /// </summary> public float borderLeft = 0.2f; /// <summary> /// Right border in sprite fraction (1 - Right, 0 - Left) /// </summary> public float borderRight = 0.2f; public void SetBorder(float left, float bottom, float right, float top) { if (borderLeft != left || borderBottom != bottom || borderRight != right || borderTop != top) { borderLeft = left; borderBottom = bottom; borderRight = right; borderTop = top; UpdateVertices(); } } [SerializeField] protected bool _createBoxCollider = false; /// <summary> /// Create a trimmed box collider for this sprite /// </summary> public bool CreateBoxCollider { get { return _createBoxCollider; } set { if (_createBoxCollider != value) { _createBoxCollider = value; UpdateCollider(); } } } new void Awake() { base.Awake(); // Create mesh, independently to everything else mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; GetComponent<MeshFilter>().mesh = mesh; // Cache box collider if (boxCollider == null) { boxCollider = GetComponent<BoxCollider>(); } #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D == null) { boxCollider2D = GetComponent<BoxCollider2D>(); } #endif // This will not be set when instantiating in code // In that case, Build will need to be called if (Collection) { // reset spriteId if outside bounds // this is when the sprite collection data is corrupt if (_spriteId < 0 || _spriteId >= Collection.Count) _spriteId = 0; Build(); } } protected void OnDestroy() { if (mesh) { #if UNITY_EDITOR DestroyImmediate(mesh); #else Destroy(mesh); #endif } } new protected void SetColors(Color32[] dest) { tk2dSpriteGeomGen.SetSpriteColors (dest, 0, 16, _color, collectionInst.premultipliedAlpha); } // Calculated center and extents Vector3 boundsCenter = Vector3.zero, boundsExtents = Vector3.zero; protected void SetGeometry(Vector3[] vertices, Vector2[] uvs) { var sprite = CurrentSprite; float colliderOffsetZ = ( boxCollider != null ) ? ( boxCollider.center.z ) : 0.0f; float colliderExtentZ = ( boxCollider != null ) ? ( boxCollider.size.z * 0.5f ) : 0.5f; tk2dSpriteGeomGen.SetSlicedSpriteGeom(meshVertices, meshUvs, 0, out boundsCenter, out boundsExtents, sprite, _scale, dimensions, new Vector2(borderLeft, borderBottom), new Vector2(borderRight, borderTop), anchor, colliderOffsetZ, colliderExtentZ); if (meshNormals.Length > 0 || meshTangents.Length > 0) { tk2dSpriteGeomGen.SetSpriteVertexNormals(meshVertices, meshVertices[0], meshVertices[15], sprite.normals, sprite.tangents, meshNormals, meshTangents); } if (sprite.positions.Length != 4 || sprite.complexGeometry) { for (int i = 0; i < vertices.Length; ++i) vertices[i] = Vector3.zero; } } void SetIndices() { int n = _borderOnly ? (8 * 6) : (9 * 6); meshIndices = new int[n]; tk2dSpriteGeomGen.SetSlicedSpriteIndices(meshIndices, 0, 0, CurrentSprite, _borderOnly); } // returns true if value is close enough to compValue, by within 1% of scale bool NearEnough(float value, float compValue, float scale) { float diff = Mathf.Abs(value - compValue); return Mathf.Abs(diff / scale) < 0.01f; } void PermanentUpgradeLegacyMode() { tk2dSpriteDefinition def = CurrentSprite; // Guess anchor float x = def.untrimmedBoundsData[0].x; float y = def.untrimmedBoundsData[0].y; float w = def.untrimmedBoundsData[1].x; float h = def.untrimmedBoundsData[1].y; if (NearEnough(x, 0, w) && NearEnough(y, -h/2, h)) _anchor = tk2dBaseSprite.Anchor.UpperCenter; else if (NearEnough(x, 0, w) && NearEnough(y, 0, h)) _anchor = tk2dBaseSprite.Anchor.MiddleCenter; else if (NearEnough(x, 0, w) && NearEnough(y, h/2, h)) _anchor = tk2dBaseSprite.Anchor.LowerCenter; else if (NearEnough(x, -w/2, w) && NearEnough(y, -h/2, h)) _anchor = tk2dBaseSprite.Anchor.UpperRight; else if (NearEnough(x, -w/2, w) && NearEnough(y, 0, h)) _anchor = tk2dBaseSprite.Anchor.MiddleRight; else if (NearEnough(x, -w/2, w) && NearEnough(y, h/2, h)) _anchor = tk2dBaseSprite.Anchor.LowerRight; else if (NearEnough(x, w/2, w) && NearEnough(y, -h/2, h)) _anchor = tk2dBaseSprite.Anchor.UpperLeft; else if (NearEnough(x, w/2, w) && NearEnough(y, 0, h)) _anchor = tk2dBaseSprite.Anchor.MiddleLeft; else if (NearEnough(x, w/2, w) && NearEnough(y, h/2, h)) _anchor = tk2dBaseSprite.Anchor.LowerLeft; else { Debug.LogError("tk2dSlicedSprite (" + name + ") error - Unable to determine anchor upgrading from legacy mode. Please fix this manually."); _anchor = tk2dBaseSprite.Anchor.MiddleCenter; } // Calculate dimensions in pixel units float pixelWidth = w / def.texelSize.x; float pixelHeight = h / def.texelSize.y; _dimensions.x = _scale.x * pixelWidth; _dimensions.y = _scale.y * pixelHeight; _scale.Set( 1, 1, 1 ); legacyMode = false; } public override void Build() { // Best guess upgrade if (legacyMode == true) { PermanentUpgradeLegacyMode(); } var spriteDef = CurrentSprite; meshUvs = new Vector2[16]; meshVertices = new Vector3[16]; meshColors = new Color32[16]; meshNormals = new Vector3[0]; meshTangents = new Vector4[0]; if (spriteDef.normals != null && spriteDef.normals.Length > 0) { meshNormals = new Vector3[16]; } if (spriteDef.tangents != null && spriteDef.tangents.Length > 0) { meshTangents = new Vector4[16]; } SetIndices(); SetGeometry(meshVertices, meshUvs); SetColors(meshColors); if (mesh == null) { mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; } else { mesh.Clear(); } mesh.vertices = meshVertices; mesh.colors32 = meshColors; mesh.uv = meshUvs; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.triangles = meshIndices; mesh.RecalculateBounds(); mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer ); GetComponent<MeshFilter>().mesh = mesh; UpdateCollider(); UpdateMaterial(); } protected override void UpdateGeometry() { UpdateGeometryImpl(); } protected override void UpdateColors() { UpdateColorsImpl(); } protected override void UpdateVertices() { UpdateGeometryImpl(); } void UpdateIndices() { if (mesh != null) { SetIndices(); mesh.triangles = meshIndices; } } protected void UpdateColorsImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (meshColors == null || meshColors.Length == 0) return; #endif if (meshColors == null || meshColors.Length == 0) { Build(); } else { SetColors(meshColors); mesh.colors32 = meshColors; } } protected void UpdateGeometryImpl() { #if UNITY_EDITOR // This can happen with prefabs in the inspector if (mesh == null) return; #endif if (meshVertices == null || meshVertices.Length == 0) { Build(); } else { SetGeometry(meshVertices, meshUvs); mesh.vertices = meshVertices; mesh.uv = meshUvs; mesh.normals = meshNormals; mesh.tangents = meshTangents; mesh.RecalculateBounds(); mesh.bounds = AdjustedMeshBounds( mesh.bounds, renderLayer ); UpdateCollider(); } } #region Collider protected override void UpdateCollider() { if (CreateBoxCollider) { if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics3D) { if (boxCollider != null) { boxCollider.size = 2 * boundsExtents; boxCollider.center = boundsCenter; } } else if (CurrentSprite.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D) { #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (boxCollider2D != null) { boxCollider2D.size = 2 * boundsExtents; boxCollider2D.center = boundsCenter; } #endif } } } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif protected override void CreateCollider() { UpdateCollider(); } #if UNITY_EDITOR public override void EditMode__CreateCollider() { if (CreateBoxCollider) { base.CreateSimpleBoxCollider(); } UpdateCollider(); } #endif #endregion protected override void UpdateMaterial() { if (renderer.sharedMaterial != collectionInst.spriteDefinitions[spriteId].materialInst) renderer.material = collectionInst.spriteDefinitions[spriteId].materialInst; } protected override int GetCurrentVertexCount() { #if UNITY_EDITOR if (meshVertices == null) return 0; #endif return 16; } public override void ReshapeBounds(Vector3 dMin, Vector3 dMax) { var sprite = CurrentSprite; Vector3 oldSize = new Vector3(_dimensions.x * sprite.texelSize.x * _scale.x, _dimensions.y * sprite.texelSize.y * _scale.y); Vector3 oldMin = Vector3.zero; switch (_anchor) { case Anchor.LowerLeft: oldMin.Set(0,0,0); break; case Anchor.LowerCenter: oldMin.Set(0.5f,0,0); break; case Anchor.LowerRight: oldMin.Set(1,0,0); break; case Anchor.MiddleLeft: oldMin.Set(0,0.5f,0); break; case Anchor.MiddleCenter: oldMin.Set(0.5f,0.5f,0); break; case Anchor.MiddleRight: oldMin.Set(1,0.5f,0); break; case Anchor.UpperLeft: oldMin.Set(0,1,0); break; case Anchor.UpperCenter: oldMin.Set(0.5f,1,0); break; case Anchor.UpperRight: oldMin.Set(1,1,0); break; } oldMin = Vector3.Scale(oldMin, oldSize) * -1; Vector3 newDimensions = oldSize + dMax - dMin; newDimensions.x /= sprite.texelSize.x * _scale.x; newDimensions.y /= sprite.texelSize.y * _scale.y; Vector3 scaledMin = new Vector3(Mathf.Approximately(_dimensions.x, 0) ? 0 : (oldMin.x * newDimensions.x / _dimensions.x), Mathf.Approximately(_dimensions.y, 0) ? 0 : (oldMin.y * newDimensions.y / _dimensions.y)); Vector3 offset = oldMin + dMin - scaledMin; offset.z = 0; transform.position = transform.TransformPoint(offset); dimensions = new Vector2(newDimensions.x, newDimensions.y); } }
/* * Copyright 2018 University of Zurich * * 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.Text; using KaVE.Commons.Model.Naming.CodeElements; using KaVE.Commons.Model.Naming.Impl.v0.CodeElements; using KaVE.Commons.Utils; using NUnit.Framework; namespace KaVE.Commons.TestGeneration.Java { public class JavaMemberNamingTestGenerator { private readonly StringBuilder _sb = new StringBuilder(); [Test, Ignore("this \"test\" is only executed manually")] public void Run() { Console.WriteLine( "put result into '<cc.kave.commons>:/cc.kave.commons.generated/GeneratedCodeElementTest.java'"); _sb.OpenClass("cc.kave.commons.generated", "GeneratedCodeElementTest"); _sb.AppendCustomAssertDefinitions(); _sb.Comment("defaults"); // defaults GenerateFieldTest(0, 0, new FieldName()); GenerateEventTest(0, 0, new EventName()); GenerateMethodTest(0, 0, new MethodName()); GeneratePropertyTest(0, 0, new PropertyName()); _sb.Comment("generated names"); var counter = 1; foreach (var typeId in JavaTypeNamingTestGenerator.TypesSource()) { GenerateFieldTests(counter, typeId); GenerateEventTests(counter, typeId); GenerateMethodTests(counter, typeId); GeneratePropertyTests(counter, typeId); counter++; } var mids = new[] { "[p:void] [T,P]..ctor()", "[p:void] [T,P]..cctor()", "[p:void] [T,P]..init()", "[p:void] [T,P]..cinit()", "static [p:void] [T,P].Ext(this [p:int] i)" }; counter++; var counter2 = 0; foreach (var mid in mids) { GenerateMethodTest(counter, counter2++, new MethodName(mid)); } var pids = new[] { "get [p:void] [T,P].P()", "get [p:void] [T,P].P([p:int] i)", "get [p:void] [T,P].P([p:int] i, [p:int] j)" }; counter++; counter2 = 0; foreach (var pid in pids) { GeneratePropertyTest(counter, counter2++, new PropertyName(pid)); } _sb.CloseClass(); Console.WriteLine(_sb); } private void GenerateFieldTests(int counter, string typeId) { var counter2 = 0; foreach (var memberBase in GenerateMemberBases(typeId, "_f")) { GenerateFieldTest(counter, counter2++, new FieldName(memberBase)); } } private void GenerateFieldTest(int counter, int counter2, IFieldName sut) { OpenTestAndDeclareSut(counter, counter2, sut); _sb.CloseTest(); } private void GenerateEventTests(int counter, string typeId) { var counter2 = 0; foreach (var memberBase in GenerateMemberBases(typeId, "e")) { GenerateEventTest(counter, counter2++, new EventName(memberBase)); } } private void GenerateEventTest(int counter, int counter2, IEventName sut) { OpenTestAndDeclareSut(counter, counter2, sut); _sb.AppendAreEqual(sut.HandlerType, "sut.getHandlerType()"); _sb.CloseTest(); } private void GenerateMethodTests(int counter, string typeId) { var counter2 = 0; foreach (var memberBase in GenerateMemberBases(typeId, "M")) { foreach (var genericPart in new[] {"", "`1[[T]]", "`1[[T -> {0}]]".FormatEx(typeId), "`2[[T],[U]]"}) { GenerateMethodTest( counter, counter2++, new MethodName("{0}{1}()".FormatEx(memberBase, genericPart))); } foreach ( var paramPart in new[] { "", "out [?] p", "[{0}] p".FormatEx(typeId), "[{0}] p1, [{0}] p2".FormatEx(typeId) }) { GenerateMethodTest(counter, counter2++, new MethodName("{0}({1})".FormatEx(memberBase, paramPart))); } } } private void GenerateMethodTest(int counter, int counter2, IMethodName sut) { OpenTestAndDeclareSut(counter, counter2, sut); _sb.AppendAreEqual(sut.ReturnType, "sut.getReturnType()"); _sb.AppendAreEqual(sut.IsConstructor, "sut.isConstructor()"); _sb.AppendAreEqual(sut.IsInit, "sut.isInit()"); _sb.AppendAreEqual(sut.IsExtensionMethod, "sut.isExtensionMethod()"); _sb.AppendParameterizedNameAssert(sut); _sb.CloseTest(); } private void GeneratePropertyTests(int counter, string typeId) { var counter2 = 0; foreach (var memberBase in GenerateMemberBases(typeId, "P")) { GeneratePropertyTest(counter, counter2++, new PropertyName("get " + memberBase + "()")); } } private void GeneratePropertyTest(int counter, int counter2, IPropertyName sut) { OpenTestAndDeclareSut(counter, counter2, sut); _sb.AppendAreEqual(sut.HasGetter, "sut.hasGetter()"); _sb.AppendAreEqual(sut.HasSetter, "sut.hasSetter()"); _sb.AppendAreEqual(sut.IsIndexer, "sut.isIndexer()"); _sb.AppendParameterizedNameAssert(sut); _sb.CloseTest(); } private static IEnumerable<string> GenerateMemberBases(string typeId, string memberName) { foreach (var staticPart in new[] {"", "static "}) { yield return "{0}[T,P] [{1}].{2}".FormatEx(staticPart, typeId, memberName); yield return "{0}[{1}] [T,P].{2}".FormatEx(staticPart, typeId, memberName); } } private void OpenTestAndDeclareSut(int counter, int counter2, IMemberName sut) { var simpleName = sut.GetType().Name; _sb.OpenTest("{0}Test_{1}_{2}".FormatEx(simpleName, counter, counter2)); _sb.AppendLine("String id = \"{0}\";".FormatEx(sut.Identifier)); _sb.AppendLine("I{0} sut = new {0}({1});".FormatEx(simpleName, sut.IsUnknown ? "" : "id")); _sb.Append("assertBasicMember(sut,id,"); _sb.Append(sut.IsUnknown ? "true" : "false").Append(','); _sb.Append(sut.IsHashed ? "true" : "false").Append(','); _sb.Append(sut.IsStatic ? "true" : "false").Append(','); _sb.Append("\"" + sut.DeclaringType.Identifier + "\"").Append(','); _sb.Append("\"" + sut.ValueType.Identifier + "\"").Append(','); _sb.Append("\"" + sut.FullName + "\"").Append(','); _sb.Append("\"" + sut.Name + "\""); _sb.AppendLine(");"); } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using Encog.ML.Data.Market.Loader; using Encog.ML.Data.Temporal; using Encog.Util.Time; namespace Encog.ML.Data.Market { /// <summary> /// A data set that is designed to hold market data. This class is based on the /// TemporalNeuralDataSet. This class is designed to load financial data from /// external sources. This class is designed to track financial data across days. /// However, it should be usable with other levels of granularity as well. /// </summary> public sealed class MarketMLDataSet : TemporalMLDataSet { /// <summary> /// The loader to use to obtain the data. /// </summary> private readonly IMarketLoader _loader; /// <summary> /// A map between the data points and actual data. /// </summary> private readonly IDictionary<Int64, TemporalPoint> _pointIndex = new Dictionary<Int64, TemporalPoint>(); /// <summary> /// Construct a market data set object. /// </summary> /// <param name="loader">The loader to use to get the financial data.</param> /// <param name="inputWindowSize">The input window size, that is how many datapoints do we use to predict.</param> /// <param name="predictWindowSize">How many datapoints do we want to predict.</param> public MarketMLDataSet(IMarketLoader loader,Int64 inputWindowSize, Int64 predictWindowSize) : base((int)inputWindowSize, (int)predictWindowSize) { _loader = loader; SequenceGrandularity = TimeUnit.Days; } /// <summary> /// Initializes a new instance of the <see cref="MarketMLDataSet"/> class. /// </summary> /// <param name="loader">The loader.</param> /// <param name="inputWindowSize">Size of the input window.</param> /// <param name="predictWindowSize">Size of the predict window.</param> /// <param name="unit">The time unit to use.</param> public MarketMLDataSet(IMarketLoader loader, Int64 inputWindowSize, Int64 predictWindowSize, TimeUnit unit) : base((int)inputWindowSize, (int)predictWindowSize) { _loader = loader; SequenceGrandularity =unit; } /// <summary> /// The loader that is being used for this set. /// </summary> public IMarketLoader Loader { get { return _loader; } } /// <summary> /// Add one description of the type of market data that we are seeking at /// each datapoint. /// </summary> /// <param name="desc"></param> public override void AddDescription(TemporalDataDescription desc) { if (!(desc is MarketDataDescription)) { throw new MarketError( "Only MarketDataDescription objects may be used " + "with the MarketMLDataSet container."); } base.AddDescription(desc); } /// <summary> /// Create a datapoint at the specified date. /// </summary> /// <param name="when">The date to create the point at.</param> /// <returns>Returns the TemporalPoint created for the specified date.</returns> public override TemporalPoint CreatePoint(DateTime when) { Int64 sequence = (Int64)GetSequenceFromDate(when); TemporalPoint result; if (_pointIndex.ContainsKey(sequence)) { result = _pointIndex[sequence]; } else { result = base.CreatePoint(when); _pointIndex[(int)result.Sequence] = result; } return result; } /// <summary> /// Load data from the loader. /// </summary> /// <param name="begin">The beginning date.</param> /// <param name="end">The ending date.</param> public void Load(DateTime begin, DateTime end) { // define the starting point if it is not already defined if (StartingPoint == DateTime.MinValue) { StartingPoint = begin; } // clear out any loaded points Points.Clear(); // first obtain a collection of symbols that need to be looked up IDictionary<TickerSymbol, object> symbolSet = new Dictionary<TickerSymbol, object>(); foreach (MarketDataDescription desc in Descriptions) { if (symbolSet.Count == 0) { symbolSet[desc.Ticker] = null; } foreach (TickerSymbol ts in symbolSet.Keys) { if (!ts.Equals(desc.Ticker)) { symbolSet[desc.Ticker] = null; break; } } } // now loop over each symbol and load the data foreach (TickerSymbol symbol in symbolSet.Keys) { LoadSymbol(symbol, begin, end); } // resort the points SortPoints(); } /// <summary> /// Load one point of market data. /// </summary> /// <param name="ticker">The ticker symbol to load.</param> /// <param name="point">The point to load at.</param> /// <param name="item">The item being loaded.</param> private void LoadPointFromMarketData(TickerSymbol ticker, TemporalPoint point, LoadedMarketData item) { foreach (TemporalDataDescription desc in Descriptions) { var mdesc = (MarketDataDescription) desc; if (mdesc.Ticker.Equals(ticker)) { point.Data[mdesc.Index] = item.Data[mdesc.DataType]; } } } /// <summary> /// Load one ticker symbol. /// </summary> /// <param name="ticker">The ticker symbol to load.</param> /// <param name="from">Load data from this date.</param> /// <param name="to">Load data to this date.</param> private void LoadSymbol(TickerSymbol ticker, DateTime from, DateTime to) { IList < MarketDataType > types = new List<MarketDataType>(); foreach (MarketDataDescription desc in Descriptions) { if (desc.Ticker.Equals(ticker)) { types.Add(desc.DataType); } } ICollection<LoadedMarketData> data = Loader.Load(ticker, types, from, to); foreach (LoadedMarketData item in data) { TemporalPoint point = CreatePoint(item.When); LoadPointFromMarketData(ticker, point, item); } } } }
// // ColorSelector.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2012 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.Drawing; using Xwt.Backends; using System.Collections.Generic; using Xwt.Accessibility; namespace Xwt { [BackendType (typeof(IColorSelectorBackend))] public class ColorSelector: Widget { protected new class WidgetBackendHost: Widget.WidgetBackendHost, IColorSelectorEventSink { protected override IBackend OnCreateBackend () { var b = base.OnCreateBackend (); if (b == null) b = new DefaultColorSelectorBackend (); return b; } public void OnColorChanged () { ((ColorSelector)Parent).OnColorChanged (EventArgs.Empty); } } public ColorSelector () { } protected override Xwt.Backends.BackendHost CreateBackendHost () { return new WidgetBackendHost (); } IColorSelectorBackend Backend { get { return (IColorSelectorBackend) BackendHost.Backend; } } /// <summary> /// Gets or sets the selected color /// </summary> public Color Color { get { return Backend.Color; } set { Backend.Color = value; } } public bool SupportsAlpha { get { return Backend.SupportsAlpha; } set { Backend.SupportsAlpha = value; } } protected virtual void OnColorChanged (EventArgs args) { if (colorChanged != null) colorChanged (this, args); } EventHandler colorChanged; public event EventHandler ColorChanged { add { BackendHost.OnBeforeEventAdd (ColorSelectorEvent.ColorChanged, colorChanged); colorChanged += value; } remove { colorChanged -= value; BackendHost.OnAfterEventRemove (ColorSelectorEvent.ColorChanged, colorChanged); } } } class DefaultColorSelectorBackend: XwtWidgetBackend, IColorSelectorBackend { HueBox hsBox; LightBox lightBox; ColorSelectionBox colorBox; SpinButton hueEntry; SpinButton satEntry; SpinButton lightEntry; SpinButton redEntry; SpinButton greenEntry; SpinButton blueEntry; SpinButton alphaEntry; HSlider alphaSlider; HSeparator alphaSeparator; Color currentColor; bool loadingEntries; List<Widget> alphaControls = new List<Widget> (); bool enableColorChangedEvent; List<Label> labelWidgets = new List<Label> (); public DefaultColorSelectorBackend () { HBox box = new HBox (); Table selBox = new Table (); hsBox = new HueBox (); hsBox.Light = 0.5; lightBox = new LightBox (); hsBox.SelectionChanged += delegate { lightBox.Hue = hsBox.SelectedColor.Hue; lightBox.Saturation = hsBox.SelectedColor.Saturation; }; colorBox = new ColorSelectionBox () { MinHeight = 20 }; selBox.Add (hsBox, 0, 0); selBox.Add (lightBox, 1, 0); box.PackStart (selBox); const int entryWidth = 40; VBox entryBox = new VBox (); Table entryTable = new Table (); entryTable.Add (CreateLabel (Application.TranslationCatalog.GetString("Color:")), 0, 0); entryTable.Add (colorBox, 1, 0, colspan:4); entryTable.Add (new HSeparator (), 0, 1, colspan:5); int r = 2; var hueLabel = CreateLabel (); entryTable.Add (hueLabel, 0, r); entryTable.Add (hueEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 360, Digits = 0, IncrementValue = 1 }, 1, r++); SetupEntry (hueEntry, hueLabel, Application.TranslationCatalog.GetString ("Hue")); var satLabel = CreateLabel (); entryTable.Add (satLabel, 0, r); entryTable.Add (satEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 100, Digits = 0, IncrementValue = 1 }, 1, r++); SetupEntry (satEntry, satLabel, Application.TranslationCatalog.GetString ("Saturation")); var lightLabel = CreateLabel (); entryTable.Add (lightLabel, 0, r); entryTable.Add (lightEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 100, Digits = 0, IncrementValue = 1 }, 1, r++); SetupEntry (lightEntry, lightLabel, Application.TranslationCatalog.GetString ("Light")); r = 2; var redLabel = CreateLabel (); entryTable.Add (redLabel, 3, r); entryTable.Add (redEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++); SetupEntry (redEntry, redLabel, Application.TranslationCatalog.GetString ("Red")); var greenLabel = CreateLabel (); entryTable.Add (greenLabel, 3, r); entryTable.Add (greenEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++); SetupEntry (greenEntry, greenLabel, Application.TranslationCatalog.GetString ("Green")); var blueLabel = CreateLabel (); entryTable.Add (blueLabel, 3, r); entryTable.Add (blueEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r++); SetupEntry (blueEntry, blueLabel, Application.TranslationCatalog.GetString ("Blue")); entryTable.Add (alphaSeparator = new HSeparator (), 0, r++, colspan:5); var alphaLabel = CreateLabel (); entryTable.Add (alphaLabel, 0, r); entryTable.Add (alphaSlider = new HSlider () { MinimumValue = 0, MaximumValue = 255, }, 1, r, colspan: 3); entryTable.Add (alphaEntry = new SpinButton () { MinWidth = entryWidth, MinimumValue = 0, MaximumValue = 255, Digits = 0, IncrementValue = 1 }, 4, r); SetupEntry (alphaEntry, alphaLabel, Application.TranslationCatalog.GetString ("Opacity")); // Don't allow the slider to get keyboard focus, as it doesn't really work with the keyboard and the opacity // spin button takes its place alphaSlider.CanGetFocus = false; alphaSlider.Accessible.Label = Application.TranslationCatalog.GetString ("Opacity"); alphaControls.Add (alphaSeparator); alphaControls.Add (alphaLabel); alphaControls.Add (alphaEntry); entryBox.PackStart (entryTable); box.PackStart (entryBox); Content = box; hsBox.SelectionChanged += HandleColorBoxSelectionChanged; lightBox.SelectionChanged += HandleColorBoxSelectionChanged; hueEntry.ValueChanged += HandleHslChanged; satEntry.ValueChanged += HandleHslChanged; lightEntry.ValueChanged += HandleHslChanged; redEntry.ValueChanged += HandleRgbChanged; greenEntry.ValueChanged += HandleRgbChanged; blueEntry.ValueChanged += HandleRgbChanged; alphaEntry.ValueChanged += HandleAlphaChanged; alphaSlider.ValueChanged += HandleAlphaChanged; Color = Colors.White; } public override Color TextColor { get { return labelWidgets[0].TextColor; } set { foreach (Label labelWidget in labelWidgets) labelWidget.TextColor = value; } } static void SetupEntry (SpinButton spinButton, Label labelWidget, string labelText) { labelWidget.Text = GetLabelWithColon (labelText); spinButton.Accessible.Label = labelText; spinButton.Accessible.LabelWidget = labelWidget; } Label CreateLabel (string text = null) { Label label = text == null ? new Label () : new Label (text); labelWidgets.Add (label); return label; } static string GetLabelWithColon (string labelText) { string labelFormat = Application.TranslationCatalog.GetString ("{0}:"); return string.Format (labelFormat, labelText); } void HandleAlphaChanged (object sender, EventArgs e) { if (loadingEntries) return; if (sender == alphaSlider) alphaEntry.Value = alphaSlider.Value; if (sender == alphaEntry) alphaSlider.Value = alphaEntry.Value; int a = Convert.ToInt32 (alphaEntry.Value); currentColor = currentColor.WithAlpha ((double)a / 255d); LoadColorBoxSelection (); HandleColorChanged (); } void HandleHslChanged (object sender, EventArgs e) { if (loadingEntries) return; int h = Convert.ToInt32 (hueEntry.Value); int s = Convert.ToInt32 (satEntry.Value); int l = Convert.ToInt32 (lightEntry.Value); currentColor = Color.FromHsl ((double)h / 360d, (double)s / 100d, (double)l / 100d, currentColor.Alpha); LoadColorBoxSelection (); LoadRgbEntries (); HandleColorChanged (); } void HandleRgbChanged (object sender, EventArgs e) { if (loadingEntries) return; int r = Convert.ToInt32 (redEntry.Value); int g = Convert.ToInt32 (greenEntry.Value); int b = Convert.ToInt32 (blueEntry.Value); currentColor = new Color ((double)r / 255d, (double)g / 255d, (double)b / 255d, currentColor.Alpha); LoadColorBoxSelection (); LoadHslEntries (); HandleColorChanged (); } void HandleColorBoxSelectionChanged (object sender, EventArgs args) { currentColor = Color.FromHsl ( hsBox.SelectedColor.Hue, hsBox.SelectedColor.Saturation, lightBox.Light, currentColor.Alpha); colorBox.Color = currentColor; LoadHslEntries (); LoadRgbEntries (); HandleColorChanged (); } void LoadAlphaEntry () { alphaEntry.Value = ((int)(currentColor.Alpha * 255)); alphaSlider.Value = ((int)(currentColor.Alpha * 255)); } void LoadHslEntries () { loadingEntries = true; hueEntry.Value = ((int)(currentColor.Hue * 360)); satEntry.Value = ((int)(currentColor.Saturation * 100)); lightEntry.Value = ((int)(currentColor.Light * 100)); loadingEntries = false; } void LoadRgbEntries () { loadingEntries = true; redEntry.Value = ((int)(currentColor.Red * 255)); greenEntry.Value = ((int)(currentColor.Green * 255)); blueEntry.Value = ((int)(currentColor.Blue * 255)); loadingEntries = false; } void LoadColorBoxSelection () { hsBox.SelectedColor = currentColor; lightBox.Light = currentColor.Light; lightBox.Hue = hsBox.SelectedColor.Hue; lightBox.Saturation = hsBox.SelectedColor.Saturation; colorBox.Color = currentColor; } #region IColorSelectorBackend implementation public Color Color { get { return currentColor; } set { currentColor = value; LoadColorBoxSelection (); LoadRgbEntries (); LoadHslEntries (); LoadAlphaEntry (); } } public bool SupportsAlpha { get { return alphaControls [0].Visible; } set { foreach (var w in alphaControls) w.Visible = value; } } #endregion protected new IColorSelectorEventSink EventSink { get { return (IColorSelectorEventSink)base.EventSink; } } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is ColorSelectorEvent) { switch ((ColorSelectorEvent)eventId) { case ColorSelectorEvent.ColorChanged: enableColorChangedEvent = true; break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is ColorSelectorEvent) { switch ((ColorSelectorEvent)eventId) { case ColorSelectorEvent.ColorChanged: enableColorChangedEvent = false; break; } } } void HandleColorChanged () { if (enableColorChangedEvent) Application.Invoke (EventSink.OnColorChanged); } } class HueBox: Canvas { const int size = 150; const int padding = 3; bool buttonDown; Point selection; Image colorBox; double light; public double Light { get { return light; } set { light = value; if (colorBox != null) { colorBox.Dispose (); colorBox = null; } QueueDraw (); } } public Color SelectedColor { get { return GetColor ((int)selection.X, (int)selection.Y); } set { selection.X = (size - 1) * value.Hue; selection.Y = (size - 1) * (1 - value.Saturation); QueueDraw (); } } public HueBox () { MinWidth = size + padding * 2; MinHeight = size + padding * 2; } protected override void OnDraw (Context ctx, Rectangle dirtyRect) { if (colorBox == null) { using (var ib = new ImageBuilder (size, size)) { for (int i=0; i<size; i++) { for (int j=0; j<size; j++) { ib.Context.Rectangle (i, j, 1, 1); ib.Context.SetColor (GetColor (i,j)); ib.Context.Fill (); } } if (ParentWindow != null) colorBox = ib.ToBitmap (this); // take screen scale factor into account else colorBox = ib.ToBitmap (); } } ctx.DrawImage (colorBox, padding, padding); ctx.SetLineWidth (1); ctx.SetColor (Colors.Black); ctx.Rectangle (selection.X + padding - 2 + 0.5, selection.Y + padding - 2 + 0.5, 4, 4); ctx.Stroke (); } Color GetColor (int x, int y) { return Color.FromHsl ((double)x / (double)(size-1), (double)(size - 1 - y) / (double)(size-1), Light); } protected override void OnButtonPressed (ButtonEventArgs args) { base.OnButtonPressed (args); buttonDown = true; selection = new Point (args.X - padding, args.Y - padding); OnSelectionChanged (); QueueDraw (); } protected override void OnButtonReleased (ButtonEventArgs args) { base.OnButtonReleased (args); buttonDown = false; QueueDraw (); } protected override void OnMouseMoved (MouseMovedEventArgs args) { base.OnMouseMoved (args); if (buttonDown) { QueueDraw (); selection = new Point (args.X - padding, args.Y - padding); OnSelectionChanged (); } } void OnSelectionChanged () { if (selection.X < 0) selection.X = 0; if (selection.Y < 0) selection.Y = 0; if (selection.X >= size) selection.X = size - 1; if (selection.Y >= size) selection.Y = size - 1; if (SelectionChanged != null) SelectionChanged (this, EventArgs.Empty); } public event EventHandler SelectionChanged; } class LightBox: Canvas { const int padding = 3; double light; double saturation; double hue; bool buttonPressed; public double Hue { get { return hue; } set { hue = value; QueueDraw (); } } public double Saturation { get { return saturation; } set { saturation = value; QueueDraw (); } } public double Light { get { return light; } set { light = value; QueueDraw (); } } public LightBox () { MinWidth = 20; MinHeight = 20; } protected override void OnDraw (Context ctx, Rectangle dirtyRect) { double width = Size.Width - padding * 2; int range = (int)Size.Height - padding * 2; for (int n=0; n < range; n++) { ctx.Rectangle (padding, padding + n, width, 1); ctx.SetColor (Color.FromHsl (hue, saturation, (double)(range - n - 1) / (double)(range - 1))); ctx.Fill (); } ctx.Rectangle (0.5, padding + (int)(((double)range) * (1-light)) + 0.5 - 2, Size.Width - 1, 4); ctx.SetColor (Colors.Black); ctx.SetLineWidth (1); ctx.Stroke (); } protected override void OnButtonPressed (ButtonEventArgs args) { base.OnButtonPressed (args); buttonPressed = true; OnSelectionChanged ((int)args.Y - padding); QueueDraw (); } protected override void OnButtonReleased (ButtonEventArgs args) { base.OnButtonReleased (args); buttonPressed = false; QueueDraw (); } protected override void OnMouseMoved (MouseMovedEventArgs args) { base.OnMouseMoved (args); if (buttonPressed) { OnSelectionChanged ((int)args.Y - padding); QueueDraw (); } } void OnSelectionChanged (int y) { int range = (int)Size.Height - padding * 2; if (y < 0) y = 0; if (y >= range) y = range - 1; light = 1 - ((double) y / (double)(range - 1)); if (SelectionChanged != null) SelectionChanged (this, EventArgs.Empty); } public event EventHandler SelectionChanged; } class ColorSelectionBox: Canvas { Color color; public Color Color { get { return color; } set { color = value; QueueDraw (); } } protected override void OnDraw (Context ctx, Rectangle dirtyRect) { ctx.Rectangle (Bounds); ctx.SetColor (Colors.White); ctx.Fill (); ctx.MoveTo (0, 0); ctx.LineTo (Size.Width, 0); ctx.LineTo (0, Size.Height); ctx.LineTo (0, 0); ctx.SetColor (Colors.Black); ctx.Fill (); ctx.Rectangle (Bounds); ctx.SetColor (color); ctx.Fill (); } } }
// // FlickrExport.cs // // Author: // Lorenzo Milesi <maxxer@yetopen.it> // Stephane Delcroix <stephane@delcroix.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2008-2009 Novell, Inc. // Copyright (C) 2008-2009 Lorenzo Milesi // Copyright (C) 2008-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.IO; using System.Threading; using Mono.Unix; using FlickrNet; using FSpot.Core; using FSpot.Filters; using FSpot.Widgets; using FSpot.UI.Dialog; using Hyena; using Hyena.Widgets; namespace FSpot.Exporters.Flickr { public class FlickrExport : Extensions.IExporter { IBrowsableCollection selection; [GtkBeans.Builder.Object] Gtk.Dialog dialog; [GtkBeans.Builder.Object] Gtk.CheckButton scale_check; [GtkBeans.Builder.Object] Gtk.CheckButton tag_check; [GtkBeans.Builder.Object] Gtk.CheckButton hierarchy_check; [GtkBeans.Builder.Object] Gtk.CheckButton ignore_top_level_check; [GtkBeans.Builder.Object] Gtk.CheckButton open_check; [GtkBeans.Builder.Object] Gtk.SpinButton size_spin; [GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow; [GtkBeans.Builder.Object] Gtk.Button auth_flickr; [GtkBeans.Builder.Object] Gtk.ProgressBar used_bandwidth; [GtkBeans.Builder.Object] Gtk.Button do_export_flickr; [GtkBeans.Builder.Object] Gtk.Label auth_label; [GtkBeans.Builder.Object] Gtk.RadioButton public_radio; [GtkBeans.Builder.Object] Gtk.CheckButton family_check; [GtkBeans.Builder.Object] Gtk.CheckButton friend_check; GtkBeans.Builder builder; string dialog_name = "flickr_export_dialog"; Thread command_thread; ThreadProgressDialog progress_dialog; ProgressItem progress_item; public const string EXPORT_SERVICE = "flickr/"; public const string SCALE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "scale"; public const string SIZE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "size"; public const string BROWSER_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "browser"; public const string TAGS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "tags"; public const string PUBLIC_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "public"; public const string FAMILY_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "family"; public const string FRIENDS_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "friends"; public const string TAG_HIERARCHY_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "tag_hierarchy"; public const string IGNORE_TOP_LEVEL_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "ignore_top_level"; bool open; bool scale; bool is_public; bool is_friend; bool is_family; string token; int photo_index; int size; Auth auth; FlickrRemote fr; FlickrRemote.Service current_service; string auth_text; State state; enum State { Disconnected, Connected, InAuth, Authorized } State CurrentState { get { return state; } set { switch (value) { case State.Disconnected: auth_label.Text = auth_text; auth_flickr.Sensitive = true; do_export_flickr.Sensitive = false; auth_flickr.Label = Catalog.GetString ("Authorize"); used_bandwidth.Visible = false; break; case State.Connected: auth_flickr.Sensitive = true; do_export_flickr.Sensitive = false; auth_label.Text = string.Format (Catalog.GetString ("Return to this window after you have finished the authorization process on {0} and click the \"Complete Authorization\" button below"), current_service.Name); auth_flickr.Label = Catalog.GetString ("Complete Authorization"); used_bandwidth.Visible = false; break; case State.InAuth: auth_flickr.Sensitive = false; auth_label.Text = string.Format (Catalog.GetString ("Logging into {0}"), current_service.Name); auth_flickr.Label = Catalog.GetString ("Checking credentials..."); do_export_flickr.Sensitive = false; used_bandwidth.Visible = false; break; case State.Authorized: do_export_flickr.Sensitive = true; auth_flickr.Sensitive = true; auth_label.Text = string.Format (Catalog.GetString ("Welcome, {0}. You are connected to {1}."), auth.User.UserName, current_service.Name); auth_flickr.Label = string.Format (Catalog.GetString ("Sign in as a different user"), auth.User.UserName); used_bandwidth.Visible = !fr.Connection.PeopleGetUploadStatus().IsPro && fr.Connection.PeopleGetUploadStatus().BandwidthMax > 0; if (used_bandwidth.Visible) { used_bandwidth.Fraction = fr.Connection.PeopleGetUploadStatus().PercentageUsed; used_bandwidth.Text = string.Format (Catalog.GetString("Used {0} of your allowed {1} monthly quota"), GLib.Format.SizeForDisplay (fr.Connection.PeopleGetUploadStatus().BandwidthUsed), GLib.Format.SizeForDisplay (fr.Connection.PeopleGetUploadStatus().BandwidthMax)); } break; } state = value; } } public FlickrExport (IBrowsableCollection selection, bool display_tags) : this (SupportedService.Flickr, selection, display_tags) { } public FlickrExport (SupportedService service, IBrowsableCollection selection, bool display_tags) : this () { Run (service, selection, display_tags); } public FlickrExport () { } public virtual void Run (IBrowsableCollection selection) { Run (SupportedService.Flickr, selection, false); } public void Run (SupportedService service, IBrowsableCollection selection, bool display_tags) { this.selection = selection; current_service = FlickrRemote.Service.FromSupported (service); var view = new TrayView (selection); view.DisplayTags = display_tags; view.DisplayDates = false; builder = new GtkBeans.Builder (null, "flickr_export.ui", null); builder.Autoconnect (this); Dialog.Modal = false; Dialog.TransientFor = null; thumb_scrolledwindow.Add (view); HandleSizeActive (null, null); public_radio.Toggled += HandlePublicChanged; tag_check.Toggled += HandleTagChanged; hierarchy_check.Toggled += HandleHierarchyChanged; HandleTagChanged (null, null); HandleHierarchyChanged (null, null); Dialog.ShowAll (); Dialog.Response += HandleResponse; auth_flickr.Clicked += HandleClicked; auth_text = string.Format (auth_label.Text, current_service.Name); auth_label.Text = auth_text; used_bandwidth.Visible = false; LoadPreference (SCALE_KEY); LoadPreference (SIZE_KEY); LoadPreference (BROWSER_KEY); LoadPreference (TAGS_KEY); LoadPreference (TAG_HIERARCHY_KEY); LoadPreference (IGNORE_TOP_LEVEL_KEY); LoadPreference (PUBLIC_KEY); LoadPreference (FAMILY_KEY); LoadPreference (FRIENDS_KEY); LoadPreference (current_service.PreferencePath); do_export_flickr.Sensitive = false; fr = new FlickrRemote (token, current_service); if (!string.IsNullOrEmpty (token)) { StartAuth (); } } public bool StartAuth () { CurrentState = State.InAuth; if (command_thread == null || ! command_thread.IsAlive) { command_thread = new Thread (new ThreadStart (CheckAuthorization)); command_thread.Start (); } return true; } public void CheckAuthorization () { var args = new AuthorizationEventArgs (); try { args.Auth = fr.CheckLogin (); } catch (FlickrException e) { args.Exception = e; } catch (Exception e) { var md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on"), e.Message); md.Run (); md.Destroy (); return; } ThreadAssist.ProxyToMain (() => { do_export_flickr.Sensitive = args.Auth != null; if (args.Auth != null) { token = args.Auth.Token; auth = args.Auth; CurrentState = State.Authorized; Preferences.Set (current_service.PreferencePath, token); } else { CurrentState = State.Disconnected; } }); } class AuthorizationEventArgs : EventArgs { Exception e; Auth auth; public Exception Exception { get { return e; } set { e = value; } } public Auth Auth { get { return auth; } set { auth = value; } } } public void HandleSizeActive (object sender, EventArgs args) { size_spin.Sensitive = scale_check.Active; } void Logout () { token = null; auth = null; fr = new FlickrRemote (token, current_service); Preferences.Set (current_service.PreferencePath, string.Empty); CurrentState = State.Disconnected; } void Login () { try { fr = new FlickrRemote (token, current_service); fr.TryWebLogin(); CurrentState = State.Connected; } catch (Exception e) { if (e is FlickrApiException && (e as FlickrApiException).Code == 98) { Logout (); Login (); } else { var md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on"), e.Message); md.Run (); md.Destroy (); CurrentState = State.Disconnected; } } } void HandleProgressChanged (ProgressItem item) { //System.Console.WriteLine ("Changed value = {0}", item.Value); progress_dialog.Fraction = (photo_index - 1.0 + item.Value) / (double) selection.Count; } FileInfo info; void HandleFlickrProgress (object sender, UploadProgressEventArgs args) { if (args.UploadComplete) { progress_dialog.Fraction = photo_index / (double) selection.Count; progress_dialog.ProgressText = string.Format (Catalog.GetString ("Waiting for response {0} of {1}"), photo_index, selection.Count); } progress_dialog.Fraction = (photo_index - 1.0 + (args.BytesSent / (double) info.Length)) / (double) selection.Count; } class DateComparer : IComparer { public int Compare (object left, object right) { return DateTime.Compare ((left as IPhoto).Time, (right as IPhoto).Time); } } void Upload () { progress_item = new ProgressItem (); progress_item.Changed += HandleProgressChanged; fr.Connection.OnUploadProgress += HandleFlickrProgress; var ids = new List<string> (); IPhoto [] photos = selection.Items; Array.Sort (photos, new DateComparer ()); for (int index = 0; index < photos.Length; index++) { try { IPhoto photo = photos [index]; progress_dialog.Message = string.Format ( Catalog.GetString ("Uploading picture \"{0}\""), photo.Name); progress_dialog.Fraction = photo_index / (double)selection.Count; photo_index++; progress_dialog.ProgressText = string.Format ( Catalog.GetString ("{0} of {1}"), photo_index, selection.Count); info = new FileInfo (photo.DefaultVersion.Uri.LocalPath); var stack = new FilterSet (); if (scale) stack.Add (new ResizeFilter ((uint)size)); string id = fr.Upload (photo, stack, is_public, is_family, is_friend); ids.Add (id); if (App.Instance.Database != null && photo is Photo) App.Instance.Database.Exports.Create ((photo as Photo).Id, (photo as Photo).DefaultVersionId, ExportStore.FlickrExportType, auth.User.UserId + ":" + auth.User.UserName + ":" + current_service.Name + ":" + id); } catch (Exception e) { progress_dialog.Message = string.Format (Catalog.GetString ("Error Uploading To {0}: {1}"), current_service.Name, e.Message); progress_dialog.ProgressText = Catalog.GetString ("Error"); Log.Exception (e); if (progress_dialog.PerformRetrySkip ()) { index--; photo_index--; } } } progress_dialog.Message = Catalog.GetString ("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Catalog.GetString ("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (open && ids.Count != 0) { string view_url; if (current_service.Name == "Zooomr.com") view_url = string.Format ("http://www.{0}/photos/{1}/", current_service.Name, auth.User.UserName); else { view_url = string.Format ("http://www.{0}/tools/uploader_edit.gne?ids", current_service.Name); bool first = true; foreach (string id in ids) { view_url = view_url + (first ? "=" : ",") + id; first = false; } } GtkBeans.Global.ShowUri (Dialog.Screen, view_url); } } void HandleClicked (object sender, EventArgs args) { switch (CurrentState) { case State.Disconnected: Login (); break; case State.Connected: StartAuth (); break; case State.InAuth: break; case State.Authorized: Logout (); Login (); break; } } void HandlePublicChanged (object sender, EventArgs args) { bool sensitive = ! public_radio.Active; friend_check.Sensitive = sensitive; family_check.Sensitive = sensitive; } void HandleTagChanged (object sender, EventArgs args) { hierarchy_check.Sensitive = tag_check.Active; } void HandleHierarchyChanged (object sender, EventArgs args) { ignore_top_level_check.Sensitive = hierarchy_check.Active; } void HandleResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId != Gtk.ResponseType.Ok) { if (command_thread != null && command_thread.IsAlive) command_thread.Abort (); Dialog.Destroy (); return; } if (fr.CheckLogin() == null) { do_export_flickr.Sensitive = false; var md = new HigMessageDialog (Dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Unable to log on."), string.Format (Catalog.GetString ("F-Spot was unable to log on to {0}. Make sure you have given the authentication using {0} web browser interface."), current_service.Name)); md.Run (); md.Destroy (); return; } fr.ExportTags = tag_check.Active; fr.ExportTagHierarchy = hierarchy_check.Active; fr.ExportIgnoreTopLevel = ignore_top_level_check.Active; open = open_check.Active; scale = scale_check.Active; is_public = public_radio.Active; is_family = family_check.Active; is_friend = friend_check.Active; if (scale) size = size_spin.ValueAsInt; command_thread = new Thread (new ThreadStart (Upload)); command_thread.Name = Catalog.GetString ("Uploading Pictures"); Dialog.Destroy (); progress_dialog = new ThreadProgressDialog (command_thread, selection.Count); progress_dialog.Start (); // Save these settings for next time Preferences.Set (SCALE_KEY, scale); Preferences.Set (SIZE_KEY, size); Preferences.Set (BROWSER_KEY, open); Preferences.Set (TAGS_KEY, tag_check.Active); Preferences.Set (PUBLIC_KEY, public_radio.Active); Preferences.Set (FAMILY_KEY, family_check.Active); Preferences.Set (FRIENDS_KEY, friend_check.Active); Preferences.Set (TAG_HIERARCHY_KEY, hierarchy_check.Active); Preferences.Set (IGNORE_TOP_LEVEL_KEY, ignore_top_level_check.Active); Preferences.Set (current_service.PreferencePath, fr.Token); } void LoadPreference (string key) { switch (key) { case SCALE_KEY: scale_check.Active = Preferences.Get<bool> (key); break; case SIZE_KEY: size_spin.Value = (double) Preferences.Get<int> (key); break; case BROWSER_KEY: open_check.Active = Preferences.Get<bool> (key); break; case TAGS_KEY: tag_check.Active = Preferences.Get<bool> (key); break; case TAG_HIERARCHY_KEY: hierarchy_check.Active = Preferences.Get<bool> (key); break; case IGNORE_TOP_LEVEL_KEY: ignore_top_level_check.Active = Preferences.Get<bool> (key); break; case FlickrRemote.TOKEN_FLICKR: case FlickrRemote.TOKEN_23HQ: case FlickrRemote.TOKEN_ZOOOMR: token = Preferences.Get<string> (key); break; case PUBLIC_KEY: public_radio.Active = Preferences.Get<bool> (key); break; case FAMILY_KEY: family_check.Active = Preferences.Get<bool> (key); break; case FRIENDS_KEY: friend_check.Active = Preferences.Get<bool> (key); break; /* case Preferences.EXPORT_FLICKR_EMAIL: /* case Preferences.EXPORT_FLICKR_EMAIL: email_entry.Text = (string) val; break; */ } } Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using QuantConnect.Data.Market; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Orders.Fills; using QuantConnect.Orders.Slippage; using QuantConnect.Securities; using QuantConnect.Securities.Equity; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Brokerages { /// <summary> /// Provides a default implementation of <see cref="IBrokerageModel"/> that allows all orders and uses /// the default transaction models /// </summary> public class DefaultBrokerageModel : IBrokerageModel { /// <summary> /// The default markets for the backtesting brokerage /// </summary> public static readonly IReadOnlyDictionary<SecurityType, string> DefaultMarketMap = new Dictionary<SecurityType, string> { {SecurityType.Base, Market.USA}, {SecurityType.Equity, Market.USA}, {SecurityType.Option, Market.USA}, {SecurityType.Future, Market.USA}, {SecurityType.Forex, Market.FXCM}, {SecurityType.Cfd, Market.FXCM} }.ToReadOnlyDictionary(); /// <summary> /// Gets or sets the account type used by this model /// </summary> public virtual AccountType AccountType { get; private set; } /// <summary> /// Gets a map of the default markets to be used for each security type /// </summary> public virtual IReadOnlyDictionary<SecurityType, string> DefaultMarkets { get { return DefaultMarketMap; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultBrokerageModel"/> class /// </summary> /// <param name="accountType">The type of account to be modelled, defaults to /// <see cref="QuantConnect.AccountType.Margin"/></param> public DefaultBrokerageModel(AccountType accountType = AccountType.Margin) { AccountType = accountType; } /// <summary> /// Returns true if the brokerage could accept this order. This takes into account /// order type, security type, and order size limits. /// </summary> /// <remarks> /// For example, a brokerage may have no connectivity at certain times, or an order rate/size limit /// </remarks> /// <param name="security">The security being ordered</param> /// <param name="order">The order to be processed</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be submitted</param> /// <returns>True if the brokerage could process the order, false otherwise</returns> public virtual bool CanSubmitOrder(Security security, Order order, out BrokerageMessageEvent message) { message = null; return true; } /// <summary> /// Returns true if the brokerage would allow updating the order as specified by the request /// </summary> /// <param name="security">The security of the order</param> /// <param name="order">The order to be updated</param> /// <param name="request">The requested update to be made to the order</param> /// <param name="message">If this function returns false, a brokerage message detailing why the order may not be updated</param> /// <returns>True if the brokerage would allow updating the order, false otherwise</returns> public virtual bool CanUpdateOrder(Security security, Order order, UpdateOrderRequest request, out BrokerageMessageEvent message) { message = null; return true; } /// <summary> /// Returns true if the brokerage would be able to execute this order at this time assuming /// market prices are sufficient for the fill to take place. This is used to emulate the /// brokerage fills in backtesting and paper trading. For example some brokerages may not perform /// executions during extended market hours. This is not intended to be checking whether or not /// the exchange is open, that is handled in the Security.Exchange property. /// </summary> /// <param name="security">The security being traded</param> /// <param name="order">The order to test for execution</param> /// <returns>True if the brokerage would be able to perform the execution, false otherwise</returns> public virtual bool CanExecuteOrder(Security security, Order order) { return true; } /// <summary> /// Applies the split to the specified order ticket /// </summary> /// <remarks> /// This default implementation will update the orders to maintain a similar market value /// </remarks> /// <param name="tickets">The open tickets matching the split event</param> /// <param name="split">The split event data</param> public virtual void ApplySplit(List<OrderTicket> tickets, Split split) { // by default we'll just update the orders to have the same notional value var splitFactor = split.SplitFactor; tickets.ForEach(ticket => ticket.Update(new UpdateOrderFields { Quantity = (int?) (ticket.Quantity/splitFactor), LimitPrice = ticket.OrderType.IsLimitOrder() ? ticket.Get(OrderField.LimitPrice)*splitFactor : (decimal?) null, StopPrice = ticket.OrderType.IsStopOrder() ? ticket.Get(OrderField.StopPrice)*splitFactor : (decimal?) null })); } /// <summary> /// Gets the brokerage's leverage for the specified security /// </summary> /// <param name="security">The security's whose leverage we seek</param> /// <returns>The leverage for the specified security</returns> public decimal GetLeverage(Security security) { switch (security.Type) { case SecurityType.Equity: return 2m; case SecurityType.Forex: case SecurityType.Cfd: return 50m; case SecurityType.Base: case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return 1m; } } /// <summary> /// Gets a new fill model that represents this brokerage's fill behavior /// </summary> /// <param name="security">The security to get fill model for</param> /// <returns>The new fill model for this brokerage</returns> public virtual IFillModel GetFillModel(Security security) { return new ImmediateFillModel(); } /// <summary> /// Gets a new fee model that represents this brokerage's fee structure /// </summary> /// <param name="security">The security to get a fee model for</param> /// <returns>The new fee model for this brokerage</returns> public virtual IFeeModel GetFeeModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Forex: case SecurityType.Cfd: return new ConstantFeeModel(0m); case SecurityType.Equity: case SecurityType.Option: case SecurityType.Future: return new InteractiveBrokersFeeModel(); case SecurityType.Commodity: default: return new ConstantFeeModel(0m); } } /// <summary> /// Gets a new slippage model that represents this brokerage's fill slippage behavior /// </summary> /// <param name="security">The security to get a slippage model for</param> /// <returns>The new slippage model for this brokerage</returns> public virtual ISlippageModel GetSlippageModel(Security security) { switch (security.Type) { case SecurityType.Base: case SecurityType.Equity: return new ConstantSlippageModel(0); case SecurityType.Forex: case SecurityType.Cfd: return new ConstantSlippageModel(0); case SecurityType.Commodity: case SecurityType.Option: case SecurityType.Future: default: return new ConstantSlippageModel(0); } } /// <summary> /// Gets a new settlement model for the security /// </summary> /// <param name="security">The security to get a settlement model for</param> /// <param name="accountType">The account type</param> /// <returns>The settlement model for this brokerage</returns> public virtual ISettlementModel GetSettlementModel(Security security, AccountType accountType) { if (accountType == AccountType.Cash) { switch (security.Type) { case SecurityType.Equity: return new DelayedSettlementModel(Equity.DefaultSettlementDays, Equity.DefaultSettlementTime); case SecurityType.Option: return new DelayedSettlementModel(Option.DefaultSettlementDays, Option.DefaultSettlementTime); } } return new ImmediateSettlementModel(); } } }
using System; using System.Collections.Generic; using System.Text; using TradeAndTravel; namespace TradeAndTravel { public class Iron : Item { private const int GeneralIronValue = 3; public Iron(string name, Location location = null) : base(name, Iron.GeneralIronValue, ItemType.Iron, location) { } } public class Wood : Item { private int generalWoodValue; public Wood(string name, Location location = null) : base(name, 2, ItemType.Wood, location) { } public override void UpdateWithInteraction(string interaction) { if (this.generalWoodValue != 0) this.generalWoodValue -= 1; base.UpdateWithInteraction(interaction); } } public class Weapon : Item { const int GeneralWeaponValue = 10; public Weapon(string name, Location location = null) : base(name, Weapon.GeneralWeaponValue, ItemType.Weapon, location) { } } public class Armor : Item { const int GeneralArmorValue = 5; public Armor(string name, Location location = null) : base(name, Armor.GeneralArmorValue, ItemType.Armor, location) { } static List<ItemType> GetComposingItems() { return new List<ItemType>() { ItemType.Iron }; } } } namespace TradeAndTravel { public class Engine { protected InteractionManager interactionManager; public Engine(InteractionManager interactionManager) { this.interactionManager = interactionManager; } public void ParseAndDispatch(string command) { this.interactionManager.HandleInteraction(command.Split(' ')); } public void Start() { bool endCommandReached = false; while (!endCommandReached) { string command = Console.ReadLine(); if (command != "end") { this.ParseAndDispatch(command); } else { endCommandReached = true; } } } } } namespace TradeAndTravel { public interface IGatheringLocation { ItemType GatheredType { get; } ItemType RequiredItem { get; } Item ProduceItem(string name); } } namespace TradeAndTravel { public class InteractionManager { const int InitialPersonMoney = 100; protected Dictionary<Person, int> moneyByPerson = new Dictionary<Person, int>(); protected Dictionary<Item, Person> ownerByItem = new Dictionary<Item, Person>(); protected Dictionary<Location, List<Item>> strayItemsByLocation = new Dictionary<Location, List<Item>>(); protected HashSet<Location> locations = new HashSet<Location>(); protected HashSet<Person> people = new HashSet<Person>(); protected Dictionary<string, Person> personByName = new Dictionary<string, Person>(); protected Dictionary<string, Location> locationByName = new Dictionary<string, Location>(); protected Dictionary<Location, List<Person>> peopleByLocation = new Dictionary<Location, List<Person>>(); public void HandleInteraction(string[] commandWords) { if (commandWords[0] == "create") { this.HandleCreationCommand(commandWords); } else { var actor = this.personByName[commandWords[0]]; this.HandlePersonCommand(commandWords, actor); } } protected virtual void HandlePersonCommand(string[] commandWords, Person actor) { switch (commandWords[1]) { case "drop": HandleDropInteraction(actor); break; case "pickup": HandlePickUpInteraction(actor); break; case "sell": this.HandleSellInteraction(commandWords, actor); break; case "buy": HandleBuyInteraction(commandWords, actor); break; case "inventory": HandleListInventoryInteraction(actor); break; case "money": Console.WriteLine(moneyByPerson[actor]); break; case "travel": HandleTravelInteraction(commandWords, actor); break; default: break; } } private void HandleTravelInteraction(string[] commandWords, Person actor) { var traveller = actor as ITraveller; if (traveller != null) { var targetLocation = this.locationByName[commandWords[2]]; peopleByLocation[traveller.Location].Remove(actor); traveller.TravelTo(targetLocation); peopleByLocation[traveller.Location].Add(actor); foreach (var item in actor.ListInventory()) { item.UpdateWithInteraction("travel"); } } } private void HandleListInventoryInteraction(Person actor) { var inventory = actor.ListInventory(); foreach (var item in inventory) { if (ownerByItem[item] == actor) { Console.WriteLine(item.Name); item.UpdateWithInteraction("inventory"); } } if (inventory.Count == 0) { Console.WriteLine("empty"); } } private void HandlePickUpInteraction(Person actor) { foreach (var item in strayItemsByLocation[actor.Location]) { this.AddToPerson(actor, item); item.UpdateWithInteraction("pickup"); } strayItemsByLocation[actor.Location].Clear(); } private void HandleDropInteraction(Person actor) { foreach (var item in actor.ListInventory()) { if (ownerByItem[item] == actor) { strayItemsByLocation[actor.Location].Add(item); this.RemoveFromPerson(actor, item); item.UpdateWithInteraction("drop"); } } } private void HandleBuyInteraction(string[] commandWords, Person actor) { Item saleItem = null; string saleItemName = commandWords[2]; var buyer = personByName[commandWords[3]] as Shopkeeper; if (buyer != null && peopleByLocation[actor.Location].Contains(buyer)) { foreach (var item in buyer.ListInventory()) { if (ownerByItem[item] == buyer && saleItemName == item.Name) { saleItem = item; } } var price = buyer.CalculateSellingPrice(saleItem); moneyByPerson[buyer] += price; moneyByPerson[actor] -= price; this.RemoveFromPerson(buyer, saleItem); this.AddToPerson(actor, saleItem); saleItem.UpdateWithInteraction("buy"); } } private void HandleSellInteraction(string[] commandWords, Person actor) { Item saleItem = null; string saleItemName = commandWords[2]; foreach (var item in actor.ListInventory()) { if (ownerByItem[item] == actor && saleItemName == item.Name) { saleItem = item; } } var buyer = personByName[commandWords[3]] as Shopkeeper; if (buyer != null && peopleByLocation[actor.Location].Contains(buyer)) { var price = buyer.CalculateBuyingPrice(saleItem); moneyByPerson[buyer] -= price; moneyByPerson[actor] += price; this.RemoveFromPerson(actor, saleItem); this.AddToPerson(buyer, saleItem); saleItem.UpdateWithInteraction("sell"); } } protected void AddToPerson(Person actor, Item item) { actor.AddToInventory(item); ownerByItem[item] = actor; } protected void RemoveFromPerson(Person actor, Item item) { actor.RemoveFromInventory(item); ownerByItem[item] = null; } protected void HandleCreationCommand(string[] commandWords) { if (commandWords[1] == "item") { string itemTypeString = commandWords[2]; string itemNameString = commandWords[3]; string itemLocationString = commandWords[4]; this.HandleItemCreation(itemTypeString, itemNameString, itemLocationString); } else if (commandWords[1] == "location") { string locationTypeString = commandWords[2]; string locationNameString = commandWords[3]; this.HandleLocationCreation(locationTypeString, locationNameString); } else { string personTypeString = commandWords[1]; string personNameString = commandWords[2]; string personLocationString = commandWords[3]; this.HandlePersonCreation(personTypeString, personNameString, personLocationString); } } protected virtual void HandleLocationCreation(string locationTypeString, string locationName) { Location location = CreateLocation(locationTypeString, locationName); locations.Add(location); strayItemsByLocation[location] = new List<Item>(); peopleByLocation[location] = new List<Person>(); locationByName[locationName] = location; } protected virtual void HandlePersonCreation(string personTypeString, string personNameString, string personLocationString) { var personLocation = locationByName[personLocationString]; Person person = CreatePerson(personTypeString, personNameString, personLocation); personByName[personNameString] = person; peopleByLocation[personLocation].Add(person); moneyByPerson[person] = InteractionManager.InitialPersonMoney; } protected virtual void HandleItemCreation(string itemTypeString, string itemNameString, string itemLocationString) { var itemLocation = locationByName[itemLocationString]; Item item = null; item = CreateItem(itemTypeString, itemNameString, itemLocation, item); ownerByItem[item] = null; strayItemsByLocation[itemLocation].Add(item); } protected virtual Item CreateItem(string itemTypeString, string itemNameString, Location itemLocation, Item item) { switch (itemTypeString) { case "armor": item = new Armor(itemNameString, itemLocation); break; default: break; } return item; } protected virtual Person CreatePerson(string personTypeString, string personNameString, Location personLocation) { Person person = null; switch (personTypeString) { case "shopkeeper": person = new Shopkeeper(personNameString, personLocation); break; case "traveller": person = new Traveller(personNameString, personLocation); break; default: break; } return person; } protected virtual Location CreateLocation(string locationTypeString, string locationName) { Location location = null; switch (locationTypeString) { case "town": location = new Town(locationName); break; default: break; } return location; } } } namespace TradeAndTravel { public interface IShopkeeper { int CalculateSellingPrice(Item item); int CalculateBuyingPrice(Item item); } } namespace TradeAndTravel { public abstract class Item : WorldObject { public ItemType ItemType { get; private set; } public int Value { get; protected set; } protected Item(string name, int itemValue, string type, Location location = null) : base(name) { this.Value = itemValue; foreach (var itemType in (ItemType[])Enum.GetValues(typeof(ItemType))) { if (itemType.ToString() == type) { this.ItemType = itemType; } } } protected Item(string name, int itemValue, ItemType type, Location location = null) : base(name) { this.Value = itemValue; this.ItemType = type; } public virtual void UpdateWithInteraction(string interaction) { } } } namespace TradeAndTravel { public enum ItemType { Weapon, Armor, Wood, Iron, } } namespace TradeAndTravel { public interface ITraveller { void TravelTo(Location location); Location Location { get; } } } namespace TradeAndTravel { public abstract class Location : WorldObject { public LocationType LocationType { get; private set; } public Location(string name, string type) : base(name) { foreach (var locType in (LocationType[])Enum.GetValues(typeof(LocationType))) { if (locType.ToString() == type) { this.LocationType = locType; } } } public Location(string name, LocationType type) : base(name) { this.LocationType = type; } } } namespace TradeAndTravel { public enum LocationType { Mine, Town, Forest, } } namespace TradeAndTravel { public class Person : WorldObject { HashSet<Item> inventoryItems; public Location Location { get; protected set; } public Person(string name, Location location) : base(name) { this.Location = location; this.inventoryItems = new HashSet<Item>(); } public void AddToInventory(Item item) { this.inventoryItems.Add(item); } public void RemoveFromInventory(Item item) { this.inventoryItems.Remove(item); } public List<Item> ListInventory() { List<Item> items = new List<Item>(); foreach (var item in this.inventoryItems) { items.Add(item); } return items; } } } namespace TradeAndTravel { public class NewInteractionManager : InteractionManager { protected override Item CreateItem(string itemTypeString, string itemNameString, Location itemLocation, Item item) { switch (itemTypeString) { case "weapon": item = new Weapon(itemNameString, itemLocation); break; case "wood": item = new Wood(itemNameString, itemLocation); break; case "iron": item = new Iron(itemNameString, itemLocation); break; default: return base.CreateItem(itemTypeString, itemNameString, itemLocation, item); } return item; } protected override Location CreateLocation(string locationTypeString, string locationName) { Location location = null; switch (locationTypeString) { case "mine": location = new Mine(locationName); break; case "forest": location = new Forest(locationName); break; default: return base.CreateLocation(locationTypeString, locationName); } return location; } protected override Person CreatePerson(string personTypeString, string personNameString, Location personLocation) { Person person = null; switch (personTypeString) { case "merchant": person = new Merchant(personNameString, personLocation); break; default: return base.CreatePerson(personTypeString, personNameString, personLocation); } return person; } } class Program { static void Main(string[] args) { var myIntManager = new NewInteractionManager(); var engine = new Engine(myIntManager); engine.Start(); } } } namespace TradeAndTravel { public class Shopkeeper : Person, IShopkeeper { public Shopkeeper(string name, Location location) : base(name, location) { } public virtual int CalculateSellingPrice(Item item) { return item.Value; } public virtual int CalculateBuyingPrice(Item item) { return item.Value / 2; } } } namespace TradeAndTravel { public class Forest : Location,IGatheringLocation { public Forest(string name) : base(name, LocationType.Forest) { } public ItemType GatheredType { get { return ItemType.Wood; } } public ItemType RequiredItem { get { return ItemType.Weapon; } } public Item ProduceItem(string name) { throw new NotImplementedException(); } } public class Mine : Location,IGatheringLocation { public Mine(string name) : base(name, LocationType.Mine) { } public ItemType GatheredType { get { return ItemType.Iron; } } public ItemType RequiredItem { get { return ItemType.Armor; } } public Item ProduceItem(string name) { throw new NotImplementedException(); } } public class Town : Location { public Town(string name) : base(name, LocationType.Town) { } } } namespace TradeAndTravel { public class Merchant : Shopkeeper, ITraveller { public Merchant(string name, Location location) : base(name, location) { } public void TravelTo(Location location) { this.Location = location; } } public class Traveller : Person, ITraveller { public Traveller(string name, Location location) : base(name, location) { } public virtual void TravelTo(Location location) { this.Location = location; } } } namespace TradeAndTravel { public abstract class WorldObject { static readonly Random random = new Random(); public string Id { get; private set; } private const int IdLength = 128; private const string IdChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789_"; private static HashSet<string> allObjectIds = new HashSet<string>(); public string Name { get; protected set; } protected WorldObject(string name = "") { this.Name = name; this.Id = WorldObject.GenerateObjectId(); } public static string GenerateObjectId() { StringBuilder resultBuilder = new StringBuilder(); string result; do { for (int i = 0; i < WorldObject.IdLength; i++) { resultBuilder.Append(IdChars[random.Next(0, WorldObject.IdChars.Length)]); } result = resultBuilder.ToString(); } while (allObjectIds.Contains(result)); return result; } public override int GetHashCode() { return this.Id.GetHashCode(); } public override bool Equals(object obj) { return this.Id.Equals((obj as WorldObject).Id); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.IO; using System.IO.Compression; using System.Reflection; using System.Security.Cryptography; using System.Text; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; namespace OpenSim.Data.MySQL { public class MySQLXAssetData : IXAssetDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected virtual Assembly Assembly { get { return GetType().Assembly; } } /// <summary> /// Number of days that must pass before we update the access time on an asset when it has been fetched. /// </summary> private const int DaysBetweenAccessTimeUpdates = 30; private bool m_enableCompression = false; private string m_connectionString; /// <summary> /// We can reuse this for all hashing since all methods are single-threaded through m_dbBLock /// </summary> private HashAlgorithm hasher = new SHA256CryptoServiceProvider(); #region IPlugin Members public string Version { get { return "1.0.0.0"; } } /// <summary> /// <para>Initialises Asset interface</para> /// <para> /// <list type="bullet"> /// <item>Loads and initialises the MySQL storage plugin.</item> /// <item>Warns and uses the obsolete mysql_connection.ini if connect string is empty.</item> /// <item>Check for migration</item> /// </list> /// </para> /// </summary> /// <param name="connect">connect string</param> public void Initialise(string connect) { m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[MYSQL XASSETDATA]: THIS PLUGIN IS STRICTLY EXPERIMENTAL."); m_log.ErrorFormat("[MYSQL XASSETDATA]: DO NOT USE FOR ANY DATA THAT YOU DO NOT MIND LOSING."); m_log.ErrorFormat("[MYSQL XASSETDATA]: DATABASE TABLES CAN CHANGE AT ANY TIME, CAUSING EXISTING DATA TO BE LOST."); m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_log.ErrorFormat("[MYSQL XASSETDATA]: ***********************************************************"); m_connectionString = connect; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "XAssetStore"); m.Update(); dbcon.Close(); } } public void Initialise() { throw new NotImplementedException(); } public void Dispose() { } /// <summary> /// The name of this DB provider /// </summary> public string Name { get { return "MySQL XAsset storage engine"; } } #endregion #region IAssetDataPlugin Members /// <summary> /// Fetch Asset <paramref name="assetID"/> from database /// </summary> /// <param name="assetID">Asset UUID to fetch</param> /// <returns>Return the asset</returns> /// <remarks>On failure : throw an exception and attempt to reconnect to database</remarks> public AssetBase GetAsset(UUID assetID) { // m_log.DebugFormat("[MYSQL XASSET DATA]: Looking for asset {0}", assetID); AssetBase asset = null; int accessTime = 0; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand( "SELECT Name, Description, AccessTime, AssetType, Local, Temporary, AssetFlags, CreatorID, Data FROM XAssetsMeta JOIN XAssetsData ON XAssetsMeta.Hash = XAssetsData.Hash WHERE ID=?ID", dbcon)) { cmd.Parameters.AddWithValue("?ID", assetID.ToString()); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { asset = new AssetBase(assetID, (string)dbReader["Name"], (sbyte)dbReader["AssetType"], dbReader["CreatorID"].ToString()); asset.Data = (byte[])dbReader["Data"]; asset.Description = (string)dbReader["Description"]; string local = dbReader["Local"].ToString(); if (local.Equals("1") || local.Equals("true", StringComparison.InvariantCultureIgnoreCase)) asset.Local = true; else asset.Local = false; asset.Temporary = Convert.ToBoolean(dbReader["Temporary"]); asset.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]); accessTime = (int)dbReader["AccessTime"]; } } } catch (Exception e) { m_log.Error(string.Format("[MYSQL XASSET DATA]: Failure fetching asset {0}", assetID), e); } } dbcon.Close(); } if(asset == null) return asset; if(accessTime > 0) { try { UpdateAccessTime(asset.Metadata, accessTime); } catch { } } if (m_enableCompression && asset.Data != null) { using(MemoryStream ms = new MemoryStream(asset.Data)) using(GZipStream decompressionStream = new GZipStream(ms, CompressionMode.Decompress)) { using(MemoryStream outputStream = new MemoryStream()) { decompressionStream.CopyTo(outputStream, int.MaxValue); // int compressedLength = asset.Data.Length; asset.Data = outputStream.ToArray(); } // m_log.DebugFormat( // "[XASSET DB]: Decompressed {0} {1} to {2} bytes from {3}", // asset.ID, asset.Name, asset.Data.Length, compressedLength); } } return asset; } /// <summary> /// Create an asset in database, or update it if existing. /// </summary> /// <param name="asset">Asset UUID to create</param> /// <remarks>On failure : Throw an exception and attempt to reconnect to database</remarks> public void StoreAsset(AssetBase asset) { // m_log.DebugFormat("[XASSETS DB]: Storing asset {0} {1}", asset.Name, asset.ID); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlTransaction transaction = dbcon.BeginTransaction()) { string assetName = asset.Name; if (asset.Name.Length > AssetBase.MAX_ASSET_NAME) { assetName = asset.Name.Substring(0, AssetBase.MAX_ASSET_NAME); m_log.WarnFormat( "[XASSET DB]: Name '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Name, asset.ID, asset.Name.Length, assetName.Length); } string assetDescription = asset.Description; if (asset.Description.Length > AssetBase.MAX_ASSET_DESC) { assetDescription = asset.Description.Substring(0, AssetBase.MAX_ASSET_DESC); m_log.WarnFormat( "[XASSET DB]: Description '{0}' for asset {1} truncated from {2} to {3} characters on add", asset.Description, asset.ID, asset.Description.Length, assetDescription.Length); } if (m_enableCompression) { MemoryStream outputStream = new MemoryStream(); using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress, false)) { // Console.WriteLine(WebUtil.CopyTo(new MemoryStream(asset.Data), compressionStream, int.MaxValue)); // We have to close the compression stream in order to make sure it writes everything out to the underlying memory output stream. compressionStream.Close(); byte[] compressedData = outputStream.ToArray(); asset.Data = compressedData; } } byte[] hash = hasher.ComputeHash(asset.Data); // m_log.DebugFormat( // "[XASSET DB]: Compressed data size for {0} {1}, hash {2} is {3}", // asset.ID, asset.Name, hash, compressedData.Length); try { using (MySqlCommand cmd = new MySqlCommand( "replace INTO XAssetsMeta(ID, Hash, Name, Description, AssetType, Local, Temporary, CreateTime, AccessTime, AssetFlags, CreatorID)" + "VALUES(?ID, ?Hash, ?Name, ?Description, ?AssetType, ?Local, ?Temporary, ?CreateTime, ?AccessTime, ?AssetFlags, ?CreatorID)", dbcon)) { // create unix epoch time int now = (int)Utils.DateTimeToUnixTime(DateTime.UtcNow); cmd.Parameters.AddWithValue("?ID", asset.ID); cmd.Parameters.AddWithValue("?Hash", hash); cmd.Parameters.AddWithValue("?Name", assetName); cmd.Parameters.AddWithValue("?Description", assetDescription); cmd.Parameters.AddWithValue("?AssetType", asset.Type); cmd.Parameters.AddWithValue("?Local", asset.Local); cmd.Parameters.AddWithValue("?Temporary", asset.Temporary); cmd.Parameters.AddWithValue("?CreateTime", now); cmd.Parameters.AddWithValue("?AccessTime", now); cmd.Parameters.AddWithValue("?CreatorID", asset.Metadata.CreatorID); cmd.Parameters.AddWithValue("?AssetFlags", (int)asset.Flags); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.ErrorFormat("[ASSET DB]: MySQL failure creating asset metadata {0} with name \"{1}\". Error: {2}", asset.FullID, asset.Name, e.Message); transaction.Rollback(); return; } if (!ExistsData(dbcon, transaction, hash)) { try { using (MySqlCommand cmd = new MySqlCommand( "INSERT INTO XAssetsData(Hash, Data) VALUES(?Hash, ?Data)", dbcon)) { cmd.Parameters.AddWithValue("?Hash", hash); cmd.Parameters.AddWithValue("?Data", asset.Data); cmd.ExecuteNonQuery(); } } catch (Exception e) { m_log.ErrorFormat("[XASSET DB]: MySQL failure creating asset data {0} with name \"{1}\". Error: {2}", asset.FullID, asset.Name, e.Message); transaction.Rollback(); return; } } transaction.Commit(); } dbcon.Close(); } } /// <summary> /// Updates the access time of the asset if it was accessed above a given threshhold amount of time. /// </summary> /// <remarks> /// This gives us some insight into assets which haven't ben accessed for a long period. This is only done /// over the threshold time to avoid excessive database writes as assets are fetched. /// </remarks> /// <param name='asset'></param> /// <param name='accessTime'></param> private void UpdateAccessTime(AssetMetadata assetMetadata, int accessTime) { DateTime now = DateTime.UtcNow; if ((now - Utils.UnixTimeToDateTime(accessTime)).TotalDays < DaysBetweenAccessTimeUpdates) return; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); MySqlCommand cmd = new MySqlCommand("update XAssetsMeta set AccessTime=?AccessTime where ID=?ID", dbcon); try { using (cmd) { // create unix epoch time cmd.Parameters.AddWithValue("?ID", assetMetadata.ID); cmd.Parameters.AddWithValue("?AccessTime", (int)Utils.DateTimeToUnixTime(now)); cmd.ExecuteNonQuery(); } } catch (Exception) { m_log.ErrorFormat( "[XASSET MYSQL DB]: Failure updating access_time for asset {0} with name {1}", assetMetadata.ID, assetMetadata.Name); } dbcon.Close(); } } /// <summary> /// We assume we already have the m_dbLock. /// </summary> /// TODO: need to actually use the transaction. /// <param name="dbcon"></param> /// <param name="transaction"></param> /// <param name="hash"></param> /// <returns></returns> private bool ExistsData(MySqlConnection dbcon, MySqlTransaction transaction, byte[] hash) { // m_log.DebugFormat("[ASSETS DB]: Checking for asset {0}", uuid); bool exists = false; using (MySqlCommand cmd = new MySqlCommand("SELECT Hash FROM XAssetsData WHERE Hash=?Hash", dbcon)) { cmd.Parameters.AddWithValue("?Hash", hash); try { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { // m_log.DebugFormat("[ASSETS DB]: Found asset {0}", uuid); exists = true; } } } catch (Exception e) { m_log.ErrorFormat( "[XASSETS DB]: MySql failure in ExistsData fetching hash {0}. Exception {1}{2}", hash, e.Message, e.StackTrace); } } return exists; } /// <summary> /// Check if the assets exist in the database. /// </summary> /// <param name="uuids">The asset UUID's</param> /// <returns>For each asset: true if it exists, false otherwise</returns> public bool[] AssetsExist(UUID[] uuids) { if (uuids.Length == 0) return new bool[0]; HashSet<UUID> exists = new HashSet<UUID>(); string ids = "'" + string.Join("','", uuids) + "'"; string sql = string.Format("SELECT ID FROM assets WHERE ID IN ({0})", ids); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(sql, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { UUID id = DBGuid.FromDB(dbReader["ID"]); exists.Add(id); } } } } bool[] results = new bool[uuids.Length]; for (int i = 0; i < uuids.Length; i++) results[i] = exists.Contains(uuids[i]); return results; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using(MySqlCommand cmd = new MySqlCommand("SELECT Name, Description, AccessTime, AssetType, Temporary, ID, AssetFlags, CreatorID FROM XAssetsMeta LIMIT ?start, ?count",dbcon)) { cmd.Parameters.AddWithValue("?start",start); cmd.Parameters.AddWithValue("?count", count); try { using (MySqlDataReader dbReader = cmd.ExecuteReader()) { while (dbReader.Read()) { AssetMetadata metadata = new AssetMetadata(); metadata.Name = (string)dbReader["Name"]; metadata.Description = (string)dbReader["Description"]; metadata.Type = (sbyte)dbReader["AssetType"]; metadata.Temporary = Convert.ToBoolean(dbReader["Temporary"]); // Not sure if this is correct. metadata.Flags = (AssetFlags)Convert.ToInt32(dbReader["AssetFlags"]); metadata.FullID = DBGuid.FromDB(dbReader["ID"]); metadata.CreatorID = dbReader["CreatorID"].ToString(); // We'll ignore this for now - it appears unused! // metadata.SHA1 = dbReader["hash"]); UpdateAccessTime(metadata, (int)dbReader["AccessTime"]); retList.Add(metadata); } } } catch (Exception e) { m_log.Error("[XASSETS DB]: MySql failure fetching asset set" + Environment.NewLine + e.ToString()); } } dbcon.Close(); } return retList; } public bool Delete(string id) { // m_log.DebugFormat("[XASSETS DB]: Deleting asset {0}", id); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand("delete from XAssetsMeta where ID=?ID", dbcon)) { cmd.Parameters.AddWithValue("?ID", id); cmd.ExecuteNonQuery(); } // TODO: How do we deal with data from deleted assets? Probably not easily reapable unless we // keep a reference count (?) dbcon.Close(); } return true; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Facebook { sealed class AndroidFacebook : AbstractFacebook, IFacebook { public const int BrowserDialogMode = 0; private const string AndroidJavaFacebookClass = "com.facebook.unity.FB"; private const string CallbackIdKey = "callback_id"; // key Hash used for Android SDK private string keyHash; public string KeyHash { get { return keyHash; } } #region IFacebook public override int DialogMode { get { return BrowserDialogMode; } set { } } public override bool LimitEventUsage { get { return limitEventUsage; } set { limitEventUsage = value; CallFB("SetLimitEventUsage", value.ToString()); } } #endregion private FacebookDelegate deepLinkDelegate; #region FBJava #if UNITY_ANDROID private AndroidJavaClass fbJava; private AndroidJavaClass FB { get { if (fbJava == null) { fbJava = new AndroidJavaClass(AndroidJavaFacebookClass); if (fbJava == null) { throw new MissingReferenceException(string.Format("AndroidFacebook failed to load {0} class", AndroidJavaFacebookClass)); } } return fbJava; } } #endif private void CallFB(string method, string args) { #if UNITY_ANDROID FB.CallStatic(method, args); #else FbDebug.Error("Using Android when not on an Android build! Doesn't Work!"); #endif } #endregion #region FBAndroid protected override void OnAwake() { keyHash = ""; #if DEBUG AndroidJNIHelper.debug = true; #endif } private bool IsErrorResponse(string response) { //var res = MiniJSON.Json.Deserialize(response); return false; } private InitDelegate onInitComplete = null; public override void Init( InitDelegate onInitComplete, string appId, bool cookie = false, bool logging = true, bool status = true, bool xfbml = false, string channelUrl = "", string authResponse = null, bool frictionlessRequests = false, HideUnityDelegate hideUnityDelegate = null) { if (string.IsNullOrEmpty(appId)) { throw new ArgumentException("appId cannot be null or empty!"); } var parameters = new Dictionary<string, object>(); parameters.Add("appId", appId); if (cookie != false) { parameters.Add("cookie", true); } if (logging != true) { parameters.Add("logging", false); } if (status != true) { parameters.Add("status", false); } if (xfbml != false) { parameters.Add("xfbml", true); } if (!string.IsNullOrEmpty(channelUrl)) { parameters.Add("channelUrl", channelUrl); } if (!string.IsNullOrEmpty(authResponse)) { parameters.Add("authResponse", authResponse); } if (frictionlessRequests != false) { parameters.Add("frictionlessRequests", true); } var paramJson = MiniJSON.Json.Serialize(parameters); this.onInitComplete = onInitComplete; this.CallFB("Init", paramJson.ToString()); } public void OnInitComplete(string message) { OnLoginComplete(message); if (this.onInitComplete != null) { this.onInitComplete(); } } public override void Login(string scope = "", FacebookDelegate callback = null) { var parameters = new Dictionary<string, object>(); parameters.Add("scope", scope); var paramJson = MiniJSON.Json.Serialize(parameters); AddAuthDelegate(callback); this.CallFB("Login", paramJson); } public void OnLoginComplete(string message) { var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (parameters.ContainsKey("user_id")) { isLoggedIn = true; userId = (string)parameters["user_id"]; accessToken = (string)parameters["access_token"]; } if (parameters.ContainsKey("key_hash")) { keyHash = (string)parameters["key_hash"]; } OnAuthResponse(new FBResult(message)); } public override void Logout() { this.CallFB("Logout", ""); } public void OnLogoutComplete(string message) { isLoggedIn = false; userId = ""; accessToken = ""; } public override void AppRequest( string message, string[] to = null, string filters = "", string[] excludeIds = null, int? maxRecipients = null, string data = "", string title = "", FacebookDelegate callback = null) { Dictionary<string, object> paramsDict = new Dictionary<string, object>(); // Marshal all the above into the thing paramsDict["message"] = message; if (callback != null) { paramsDict["callback_id"] = AddFacebookDelegate(callback); } if (to != null) { paramsDict["to"] = string.Join(",", to); } if (!string.IsNullOrEmpty(filters)) { paramsDict["filters"] = filters; } if (maxRecipients != null) { paramsDict["max_recipients"] = maxRecipients.Value; } if (!string.IsNullOrEmpty(data)) { paramsDict["data"] = data; } if (!string.IsNullOrEmpty(title)) { paramsDict["title"] = title; } CallFB("AppRequest", MiniJSON.Json.Serialize(paramsDict)); } public void OnAppRequestsComplete(string message) { var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (rawResult.ContainsKey(CallbackIdKey)) { var result = new Dictionary<string, object>(); var callbackId = (string)rawResult[CallbackIdKey]; rawResult.Remove(CallbackIdKey); if (rawResult.Count > 0) { List<string> to = new List<string>(rawResult.Count - 1); foreach (string key in rawResult.Keys) { if (!key.StartsWith("to")) { result[key] = rawResult[key]; continue; } to.Add((string)rawResult[key]); } result.Add("to", to); rawResult.Clear(); OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result))); } else { //if we make it here java returned a callback message with only an id //this isnt supposed to happen OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create")); } } } public override void FeedRequest( string toId = "", string link = "", string linkName = "", string linkCaption = "", string linkDescription = "", string picture = "", string mediaSource = "", string actionName = "", string actionLink = "", string reference = "", Dictionary<string, string[]> properties = null, FacebookDelegate callback = null) { Dictionary<string, object> paramsDict = new Dictionary<string, object>(); // Marshal all the above into the thing if (!string.IsNullOrEmpty(toId)) { paramsDict.Add("to", toId); } if (!string.IsNullOrEmpty(link)) { paramsDict.Add("link", link); } if (!string.IsNullOrEmpty(linkName)) { paramsDict.Add("name", linkName); } if (!string.IsNullOrEmpty(linkCaption)) { paramsDict.Add("caption", linkCaption); } if (!string.IsNullOrEmpty(linkDescription)) { paramsDict.Add("description", linkDescription); } if (!string.IsNullOrEmpty(picture)) { paramsDict.Add("picture", picture); } if (!string.IsNullOrEmpty(mediaSource)) { paramsDict.Add("source", mediaSource); } if (!string.IsNullOrEmpty(actionName) && !string.IsNullOrEmpty(actionLink)) { Dictionary<string, object> dict = new Dictionary<string, object>(); dict.Add("name", actionName); dict.Add("link", actionLink); paramsDict.Add("actions", new[] { dict }); } if (!string.IsNullOrEmpty(reference)) { paramsDict.Add("ref", reference); } if (properties != null) { Dictionary<string, object> newObj = new Dictionary<string, object>(); foreach (KeyValuePair<string, string[]> pair in properties) { if (pair.Value.Length < 1) continue; if (pair.Value.Length == 1) { // String-string newObj.Add(pair.Key, pair.Value[0]); } else { // String-Object with two parameters Dictionary<string, object> innerObj = new Dictionary<string, object>(); innerObj.Add("text", pair.Value[0]); innerObj.Add("href", pair.Value[1]); newObj.Add(pair.Key, innerObj); } } paramsDict.Add("properties", newObj); } CallFB("FeedRequest", MiniJSON.Json.Serialize(paramsDict)); } public void OnFeedRequestComplete(string message) { } public override void Pay( string product, string action = "purchaseitem", int quantity = 1, int? quantityMin = null, int? quantityMax = null, string requestId = null, string pricepointId = null, string testCurrency = null, FacebookDelegate callback = null) { throw new PlatformNotSupportedException("There is no Facebook Pay Dialog on Android"); } public override void GetDeepLink(FacebookDelegate callback) { if (callback != null) { deepLinkDelegate = callback; CallFB("GetDeepLink", ""); } } public void OnGetDeepLinkComplete(string message) { var rawResult = (Dictionary<string, object>) MiniJSON.Json.Deserialize(message); if (deepLinkDelegate != null) { object deepLink = ""; rawResult.TryGetValue("deep_link", out deepLink); deepLinkDelegate(new FBResult(deepLink.ToString())); } } public override void AppEventsLogEvent( string logEvent, float? valueToSum = null, Dictionary<string, object> parameters = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["logEvent"] = logEvent; if (valueToSum.HasValue) { paramsDict["valueToSum"] = valueToSum.Value; } if (parameters != null) { paramsDict["parameters"] = ToStringDict(parameters); } CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict)); } public override void AppEventsLogPurchase( float logPurchase, string currency = "USD", Dictionary<string, object> parameters = null) { var paramsDict = new Dictionary<string, object>(); paramsDict["logPurchase"] = logPurchase; paramsDict["currency"] = (!string.IsNullOrEmpty(currency)) ? currency : "USD"; if (parameters != null) { paramsDict["parameters"] = ToStringDict(parameters); } CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict)); } #endregion #region Helper Functions public override void PublishInstall(string appId, FacebookDelegate callback = null) { var parameters = new Dictionary<string, string>(2); parameters["app_id"] = appId; if (callback != null) { parameters["callback_id"] = AddFacebookDelegate(callback); } CallFB("PublishInstall", MiniJSON.Json.Serialize(parameters)); } public void OnPublishInstallComplete(string message) { var response = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message); if (response.ContainsKey("callback_id")) { OnFacebookResponse((string)response["callback_id"], new FBResult("")); } } private Dictionary<string, string> ToStringDict(Dictionary<string, object> dict) { if (dict == null) { return null; } var newDict = new Dictionary<string, string>(); foreach (KeyValuePair<string, object> kvp in dict) { newDict[kvp.Key] = kvp.Value.ToString(); } return newDict; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; namespace System { internal static class UriHelper { internal static readonly char[] s_hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; internal static readonly Encoding s_noFallbackCharUTF8 = Encoding.GetEncoding( Encoding.UTF8.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback("")); // http://host/Path/Path/File?Query is the base of // - http://host/Path/Path/File/ ... (those "File" words may be different in semantic but anyway) // - http://host/Path/Path/#Fragment // - http://host/Path/Path/?Query // - http://host/Path/Path/MoreDir/ ... // - http://host/Path/Path/OtherFile?Query // - http://host/Path/Path/Fl // - http://host/Path/Path/ // // It is not a base for // - http://host/Path/Path (that last "Path" is not considered as a directory) // - http://host/Path/Path?Query // - http://host/Path/Path#Fragment // - http://host/Path/Path2/ // - http://host/Path/Path2/MoreDir // - http://host/Path/File // // ASSUMES that strings like http://host/Path/Path/MoreDir/../../ have been canonicalized before going to this method. // ASSUMES that back slashes already have been converted if applicable. // internal static unsafe bool TestForSubPath(char* selfPtr, ushort selfLength, char* otherPtr, ushort otherLength, bool ignoreCase) { ushort i = 0; char chSelf; char chOther; bool AllSameBeforeSlash = true; for (; i < selfLength && i < otherLength; ++i) { chSelf = *(selfPtr + i); chOther = *(otherPtr + i); if (chSelf == '?' || chSelf == '#') { // survived so far and selfPtr does not have any more path segments return true; } // If selfPtr terminates a path segment, so must otherPtr if (chSelf == '/') { if (chOther != '/') { // comparison has failed return false; } // plus the segments must be the same if (!AllSameBeforeSlash) { // comparison has failed return false; } //so far so good AllSameBeforeSlash = true; continue; } // if otherPtr terminates then selfPtr must not have any more path segments if (chOther == '?' || chOther == '#') { break; } if (!ignoreCase) { if (chSelf != chOther) { AllSameBeforeSlash = false; } } else { if (char.ToLowerInvariant(chSelf) != char.ToLowerInvariant(chOther)) { AllSameBeforeSlash = false; } } } // If self is longer then it must not have any more path segments for (; i < selfLength; ++i) { if ((chSelf = *(selfPtr + i)) == '?' || chSelf == '#') { return true; } if (chSelf == '/') { return false; } } //survived by getting to the end of selfPtr return true; } // - forceX characters are always escaped if found // - rsvd character will remain unescaped // // start - starting offset from input // end - the exclusive ending offset in input // destPos - starting offset in dest for output, on return this will be an exclusive "end" in the output. // // In case "dest" has lack of space it will be reallocated by preserving the _whole_ content up to current destPos // // Returns null if nothing has to be escaped AND passed dest was null, otherwise the resulting array with the updated destPos // private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; internal static unsafe char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { if (end - start >= Uri.c_MaxUriBufferSize) throw new UriFormatException(SR.net_uri_SizeLimit); int i = start; int prevInputPos = start; byte* bytes = stackalloc byte[c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar]; // 40*4=160 fixed (char* pStr = input) { for (; i < end; ++i) { char ch = pStr[i]; // a Unicode ? if (ch > '\x7F') { short maxSize = (short)Math.Min(end - i, (int)c_MaxUnicodeCharsReallocate - 1); short count = 1; for (; count < maxSize && pStr[i + count] > '\x7f'; ++count) ; // Is the last a high surrogate? if (pStr[i + count - 1] >= 0xD800 && pStr[i + count - 1] <= 0xDBFF) { // Should be a rare case where the app tries to feed an invalid Unicode surrogates pair if (count == 1 || count == end - i) throw new UriFormatException(SR.net_uri_BadString); // need to grab one more char as a Surrogate except when it's a bogus input ++count; } dest = EnsureDestinationSize(pStr, dest, i, (short)(count * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte), c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar * c_EncodedCharsPerByte, ref destPos, prevInputPos); short numberOfBytes = (short)Encoding.UTF8.GetBytes(pStr + i, count, bytes, c_MaxUnicodeCharsReallocate * c_MaxUTF_8BytesPerUnicodeChar); // This is the only exception that built in UriParser can throw after a Uri ctor. // Should not happen unless the app tries to feed an invalid Unicode String if (numberOfBytes == 0) throw new UriFormatException(SR.net_uri_BadString); i += (count - 1); for (count = 0; count < numberOfBytes; ++count) EscapeAsciiChar((char)bytes[count], dest, ref destPos); prevInputPos = i + 1; } else if (ch == '%' && rsvd == '%') { // Means we don't reEncode '%' but check for the possible escaped sequence dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); if (i + 2 < end && EscapedAscii(pStr[i + 1], pStr[i + 2]) != Uri.c_DummyChar) { // leave it escaped dest[destPos++] = '%'; dest[destPos++] = pStr[i + 1]; dest[destPos++] = pStr[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } prevInputPos = i + 1; } else if (ch == force1 || ch == force2) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } else if (ch != rsvd && (isUriString ? !IsReservedUnreservedOrHash(ch) : !IsUnreserved(ch))) { dest = EnsureDestinationSize(pStr, dest, i, c_EncodedCharsPerByte, c_MaxAsciiCharsReallocate * c_EncodedCharsPerByte, ref destPos, prevInputPos); EscapeAsciiChar(ch, dest, ref destPos); prevInputPos = i + 1; } } if (prevInputPos != i) { // need to fill up the dest array ? if (prevInputPos != start || dest != null) dest = EnsureDestinationSize(pStr, dest, i, 0, 0, ref destPos, prevInputPos); } } return dest; } // // ensure destination array has enough space and contains all the needed input stuff // private static unsafe char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if ((object)dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { // allocating or reallocating array by ensuring enough space based on maxCharsToAdd. char[] newresult = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if ((object)dest != null && destPos != 0) Buffer.BlockCopy(dest, 0, newresult, 0, destPos << 1); dest = newresult; } // ensuring we copied everything form the input string left before last escaping while (prevInputPos != currentInputPos) dest[destPos++] = pStr[prevInputPos++]; return dest; } // // This method will assume that any good Escaped Sequence will be unescaped in the output // - Assumes Dest.Length - detPosition >= end-start // - UnescapeLevel controls various modes of operation // - Any "bad" escape sequence will remain as is or '%' will be escaped. // - destPosition tells the starting index in dest for placing the result. // On return destPosition tells the last character + 1 position in the "dest" array. // - The control chars and chars passed in rsdvX parameters may be re-escaped depending on UnescapeLevel // - It is a RARE case when Unescape actually needs escaping some characters mentioned above. // For this reason it returns a char[] that is usually the same ref as the input "dest" value. // internal static unsafe char[] UnescapeString(string input, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { fixed (char* pStr = input) { return UnescapeString(pStr, start, end, dest, ref destPosition, rsvd1, rsvd2, rsvd3, unescapeMode, syntax, isQuery); } } internal static unsafe char[] UnescapeString(char* pStr, int start, int end, char[] dest, ref int destPosition, char rsvd1, char rsvd2, char rsvd3, UnescapeMode unescapeMode, UriParser syntax, bool isQuery) { byte[] bytes = null; byte escapedReallocations = 0; bool escapeReserved = false; int next = start; bool iriParsing = Uri.IriParsingStatic(syntax) && ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.EscapeUnescape); char[] unescapedChars = null; while (true) { // we may need to re-pin dest[] fixed (char* pDest = dest) { if ((unescapeMode & UnescapeMode.EscapeUnescape) == UnescapeMode.CopyOnly) { while (start < end) pDest[destPosition++] = pStr[start++]; return dest; } while (true) { char ch = (char)0; for (; next < end; ++next) { if ((ch = pStr[next]) == '%') { if ((unescapeMode & UnescapeMode.Unescape) == 0) { // re-escape, don't check anything else escapeReserved = true; } else if (next + 2 < end) { ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); // Unescape a good sequence if full unescape is requested if (unescapeMode >= UnescapeMode.UnescapeAll) { if (ch == Uri.c_DummyChar) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } continue; } } // re-escape % from an invalid sequence else if (ch == Uri.c_DummyChar) { if ((unescapeMode & UnescapeMode.Escape) != 0) escapeReserved = true; else continue; // we should throw instead but since v1.0 would just print '%' } // Do not unescape '%' itself unless full unescape is requested else if (ch == '%') { next += 2; continue; } // Do not unescape a reserved char unless full unescape is requested else if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { next += 2; continue; } // Do not unescape a dangerous char unless it's V1ToStringFlags mode else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && IsNotSafeForUnescape(ch)) { next += 2; continue; } else if (iriParsing && ((ch <= '\x9F' && IsNotSafeForUnescape(ch)) || (ch > '\x9F' && !IriHelper.CheckIriUnicodeRange(ch, isQuery)))) { // check if unenscaping gives a char outside iri range // if it does then keep it escaped next += 2; continue; } // unescape escaped char or escape % break; } else if (unescapeMode >= UnescapeMode.UnescapeAll) { if (unescapeMode >= UnescapeMode.UnescapeAllOrThrow) { // Should be a rare case where the app tries to feed an invalid escaped sequence throw new UriFormatException(SR.net_uri_BadString); } // keep a '%' as part of a bogus sequence continue; } else { escapeReserved = true; } // escape (escapeReserved==true) or otherwise unescape the sequence break; } else if ((unescapeMode & (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) == (UnescapeMode.Unescape | UnescapeMode.UnescapeAll)) { continue; } else if ((unescapeMode & UnescapeMode.Escape) != 0) { // Could actually escape some of the characters if (ch == rsvd1 || ch == rsvd2 || ch == rsvd3) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } else if ((unescapeMode & UnescapeMode.V1ToStringFlag) == 0 && (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F'))) { // found an unescaped reserved character -> escape it escapeReserved = true; break; } } } //copy off previous characters from input while (start < next) pDest[destPosition++] = pStr[start++]; if (next != end) { if (escapeReserved) { //escape that char // Since this should be _really_ rare case, reallocate with constant size increase of 30 rsvd-type characters. if (escapedReallocations == 0) { escapedReallocations = 30; char[] newDest = new char[dest.Length + escapedReallocations * 3]; fixed (char* pNewDest = &newDest[0]) { for (int i = 0; i < destPosition; ++i) pNewDest[i] = pDest[i]; } dest = newDest; // re-pin new dest[] array goto dest_fixed_loop_break; } else { --escapedReallocations; EscapeAsciiChar(pStr[next], dest, ref destPosition); escapeReserved = false; start = ++next; continue; } } // unescaping either one Ascii or possibly multiple Unicode if (ch <= '\x7F') { //ASCII dest[destPosition++] = ch; next += 3; start = next; continue; } // Unicode int byteCount = 1; // lazy initialization of max size, will reuse the array for next sequences if ((object)bytes == null) bytes = new byte[end - next]; bytes[0] = (byte)ch; next += 3; while (next < end) { // Check on exit criterion if ((ch = pStr[next]) != '%' || next + 2 >= end) break; // already made sure we have 3 characters in str ch = EscapedAscii(pStr[next + 1], pStr[next + 2]); //invalid hex sequence ? if (ch == Uri.c_DummyChar) break; // character is not part of a UTF-8 sequence ? else if (ch < '\x80') break; else { //a UTF-8 sequence bytes[byteCount++] = (byte)ch; next += 3; } } if (unescapedChars == null || unescapedChars.Length < bytes.Length) { unescapedChars = new char[bytes.Length]; } int charCount = s_noFallbackCharUTF8.GetChars(bytes, 0, byteCount, unescapedChars, 0); start = next; // match exact bytes // Do not unescape chars not allowed by Iri // need to check for invalid utf sequences that may not have given any chars MatchUTF8Sequence(pDest, dest, ref destPosition, unescapedChars.AsSpan(0, charCount), charCount, bytes, byteCount, isQuery, iriParsing); } if (next == end) goto done; } dest_fixed_loop_break:; } } done: return dest; } // // Need to check for invalid utf sequences that may not have given any chars. // We got the unescaped chars, we then re-encode them and match off the bytes // to get the invalid sequence bytes that we just copy off // internal static unsafe void MatchUTF8Sequence(char* pDest, char[] dest, ref int destOffset, Span<char> unescapedChars, int charCount, byte[] bytes, int byteCount, bool isQuery, bool iriParsing) { Span<byte> maxUtf8EncodedSpan = stackalloc byte[4]; int count = 0; fixed (char* unescapedCharsPtr = unescapedChars) { for (int j = 0; j < charCount; ++j) { bool isHighSurr = char.IsHighSurrogate(unescapedCharsPtr[j]); Span<byte> encodedBytes = maxUtf8EncodedSpan; int bytesWritten = Encoding.UTF8.GetBytes(unescapedChars.Slice(j, isHighSurr ? 2 : 1), encodedBytes); encodedBytes = encodedBytes.Slice(0, bytesWritten); // we have to keep unicode chars outside Iri range escaped bool inIriRange = false; if (iriParsing) { if (!isHighSurr) inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], isQuery); else { bool surrPair = false; inIriRange = IriHelper.CheckIriUnicodeRange(unescapedChars[j], unescapedChars[j + 1], ref surrPair, isQuery); } } while (true) { // Escape any invalid bytes that were before this character while (bytes[count] != encodedBytes[0]) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } // check if all bytes match bool allBytesMatch = true; int k = 0; for (; k < encodedBytes.Length; ++k) { if (bytes[count + k] != encodedBytes[k]) { allBytesMatch = false; break; } } if (allBytesMatch) { count += encodedBytes.Length; if (iriParsing) { if (!inIriRange) { // need to keep chars not allowed as escaped for (int l = 0; l < encodedBytes.Length; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)encodedBytes[l], dest, ref destOffset); } } else if (!UriHelper.IsBidiControlCharacter(unescapedCharsPtr[j]) || !UriParser.DontKeepUnicodeBidiFormattingCharacters) { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } } else { //copy chars Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j]; if (isHighSurr) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); pDest[destOffset++] = unescapedCharsPtr[j + 1]; } } break; // break out of while (true) since we've matched this char bytes } else { // copy bytes till place where bytes don't match for (int l = 0; l < k; ++l) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } } if (isHighSurr) j++; } } // Include any trailing invalid sequences while (count < byteCount) { Debug.Assert(dest.Length > destOffset, "Destination length exceeded destination offset."); EscapeAsciiChar((char)bytes[count++], dest, ref destOffset); } } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = s_hexUpperChars[(ch & 0xf0) >> 4]; to[pos++] = s_hexUpperChars[ch & 0xf]; } internal static char EscapedAscii(char digit, char next) { if (!(((digit >= '0') && (digit <= '9')) || ((digit >= 'A') && (digit <= 'F')) || ((digit >= 'a') && (digit <= 'f')))) { return Uri.c_DummyChar; } int res = (digit <= '9') ? ((int)digit - (int)'0') : (((digit <= 'F') ? ((int)digit - (int)'A') : ((int)digit - (int)'a')) + 10); if (!(((next >= '0') && (next <= '9')) || ((next >= 'A') && (next <= 'F')) || ((next >= 'a') && (next <= 'f')))) { return Uri.c_DummyChar; } return (char)((res << 4) + ((next <= '9') ? ((int)next - (int)'0') : (((next <= 'F') ? ((int)next - (int)'A') : ((int)next - (int)'a')) + 10))); } internal const string RFC3986ReservedMarks = @";/?:@&=+$,#[]!'()*"; private const string RFC2396ReservedMarks = @";/?:@&=+$,"; private const string RFC3986UnreservedMarks = @"-_.~"; private const string RFC2396UnreservedMarks = @"-_.~*'()!"; private const string AdditionalUnsafeToUnescape = @"%\#";// While not specified as reserved, these are still unsafe to unescape. // When unescaping in safe mode, do not unescape the RFC 3986 reserved set: // gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" // / "*" / "+" / "," / ";" / "=" // // In addition, do not unescape the following unsafe characters: // excluded = "%" / "\" // // This implementation used to use the following variant of the RFC 2396 reserved set. // That behavior is now disabled by default, and is controlled by a UriSyntax property. // reserved = ";" | "/" | "?" | "@" | "&" | "=" | "+" | "$" | "," // excluded = control | "#" | "%" | "\" internal static bool IsNotSafeForUnescape(char ch) { if (ch <= '\x1F' || (ch >= '\x7F' && ch <= '\x9F')) { return true; } else if (UriParser.DontEnableStrictRFC3986ReservedCharacterSets) { if ((ch != ':' && (RFC2396ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0))) { return true; } } else if ((RFC3986ReservedMarks.IndexOf(ch) >= 0) || (AdditionalUnsafeToUnescape.IndexOf(ch) >= 0)) { return true; } return false; } private static unsafe bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return (RFC3986ReservedMarks.IndexOf(c) >= 0); } internal static unsafe bool IsUnreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } internal static bool Is3986Unreserved(char c) { if (UriHelper.IsAsciiLetterOrDigit(c)) { return true; } return (RFC3986UnreservedMarks.IndexOf(c) >= 0); } // // Is this a gen delim char from RFC 3986 // internal static bool IsGenDelim(char ch) { return (ch == ':' || ch == '/' || ch == '?' || ch == '#' || ch == '[' || ch == ']' || ch == '@'); } internal static readonly char[] s_WSchars = new char[] { ' ', '\n', '\r', '\t' }; internal static bool IsLWS(char ch) { return (ch <= ' ') && (ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'); } //Only consider ASCII characters internal static bool IsAsciiLetter(char character) { return (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); } internal static bool IsAsciiLetterOrDigit(char character) { return IsAsciiLetter(character) || (character >= '0' && character <= '9'); } // // Is this a Bidirectional control char.. These get stripped // internal static bool IsBidiControlCharacter(char ch) { return (ch == '\u200E' /*LRM*/ || ch == '\u200F' /*RLM*/ || ch == '\u202A' /*LRE*/ || ch == '\u202B' /*RLE*/ || ch == '\u202C' /*PDF*/ || ch == '\u202D' /*LRO*/ || ch == '\u202E' /*RLO*/); } // // Strip Bidirectional control characters from this string // internal static unsafe string StripBidiControlCharacter(char* strToClean, int start, int length) { if (length <= 0) return ""; char[] cleanStr = new char[length]; int count = 0; for (int i = 0; i < length; ++i) { char c = strToClean[start + i]; if (c < '\u200E' || c > '\u202E' || !IsBidiControlCharacter(c)) { cleanStr[count++] = c; } } return new string(cleanStr, 0, count); } } }
/* * 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. */ // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/ using System; using System.Collections.Generic; using Thrift.Collections; using Thrift.Test; //generated code using Thrift.Transport; using Thrift.Protocol; using Thrift.Server; namespace Test { public class TestServer { public class TestHandler : ThriftTest.Iface { public TServer server; public TestHandler() { } public void testVoid() { Console.WriteLine("testVoid()"); } public string testString(string thing) { Console.WriteLine("teststring(\"" + thing + "\")"); return thing; } public sbyte testByte(sbyte thing) { Console.WriteLine("testByte(" + thing + ")"); return thing; } public int testI32(int thing) { Console.WriteLine("testI32(" + thing + ")"); return thing; } public long testI64(long thing) { Console.WriteLine("testI64(" + thing + ")"); return thing; } public double testDouble(double thing) { Console.WriteLine("testDouble(" + thing + ")"); return thing; } public Xtruct testStruct(Xtruct thing) { Console.WriteLine("testStruct({" + "\"" + thing.String_thing + "\", " + thing.Byte_thing + ", " + thing.I32_thing + ", " + thing.I64_thing + "})"); return thing; } public Xtruct2 testNest(Xtruct2 nest) { Xtruct thing = nest.Struct_thing; Console.WriteLine("testNest({" + nest.Byte_thing + ", {" + "\"" + thing.String_thing + "\", " + thing.Byte_thing + ", " + thing.I32_thing + ", " + thing.I64_thing + "}, " + nest.I32_thing + "})"); return nest; } public Dictionary<int, int> testMap(Dictionary<int, int> thing) { Console.WriteLine("testMap({"); bool first = true; foreach (int key in thing.Keys) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(key + " => " + thing[key]); } Console.WriteLine("})"); return thing; } public Dictionary<string, string> testStringMap(Dictionary<string, string> thing) { Console.WriteLine("testStringMap({"); bool first = true; foreach (string key in thing.Keys) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(key + " => " + thing[key]); } Console.WriteLine("})"); return thing; } public THashSet<int> testSet(THashSet<int> thing) { Console.WriteLine("testSet({"); bool first = true; foreach (int elem in thing) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(elem); } Console.WriteLine("})"); return thing; } public List<int> testList(List<int> thing) { Console.WriteLine("testList({"); bool first = true; foreach (int elem in thing) { if (first) { first = false; } else { Console.WriteLine(", "); } Console.WriteLine(elem); } Console.WriteLine("})"); return thing; } public Numberz testEnum(Numberz thing) { Console.WriteLine("testEnum(" + thing + ")"); return thing; } public long testTypedef(long thing) { Console.WriteLine("testTypedef(" + thing + ")"); return thing; } public Dictionary<int, Dictionary<int, int>> testMapMap(int hello) { Console.WriteLine("testMapMap(" + hello + ")"); Dictionary<int, Dictionary<int, int>> mapmap = new Dictionary<int, Dictionary<int, int>>(); Dictionary<int, int> pos = new Dictionary<int, int>(); Dictionary<int, int> neg = new Dictionary<int, int>(); for (int i = 1; i < 5; i++) { pos[i] = i; neg[-i] = -i; } mapmap[4] = pos; mapmap[-4] = neg; return mapmap; } public Dictionary<long, Dictionary<Numberz, Insanity>> testInsanity(Insanity argument) { Console.WriteLine("testInsanity()"); Xtruct hello = new Xtruct(); hello.String_thing = "Hello2"; hello.Byte_thing = 2; hello.I32_thing = 2; hello.I64_thing = 2; Xtruct goodbye = new Xtruct(); goodbye.String_thing = "Goodbye4"; goodbye.Byte_thing = (sbyte)4; goodbye.I32_thing = 4; goodbye.I64_thing = (long)4; Insanity crazy = new Insanity(); crazy.UserMap = new Dictionary<Numberz, long>(); crazy.UserMap[Numberz.EIGHT] = (long)8; crazy.Xtructs = new List<Xtruct>(); crazy.Xtructs.Add(goodbye); Insanity looney = new Insanity(); crazy.UserMap[Numberz.FIVE] = (long)5; crazy.Xtructs.Add(hello); Dictionary<Numberz, Insanity> first_map = new Dictionary<Numberz, Insanity>(); Dictionary<Numberz, Insanity> second_map = new Dictionary<Numberz, Insanity>(); ; first_map[Numberz.TWO] = crazy; first_map[Numberz.THREE] = crazy; second_map[Numberz.SIX] = looney; Dictionary<long, Dictionary<Numberz, Insanity>> insane = new Dictionary<long, Dictionary<Numberz, Insanity>>(); insane[(long)1] = first_map; insane[(long)2] = second_map; return insane; } public Xtruct testMulti(sbyte arg0, int arg1, long arg2, Dictionary<short, string> arg3, Numberz arg4, long arg5) { Console.WriteLine("testMulti()"); Xtruct hello = new Xtruct(); ; hello.String_thing = "Hello2"; hello.Byte_thing = arg0; hello.I32_thing = arg1; hello.I64_thing = arg2; return hello; } public void testException(string arg) { Console.WriteLine("testException(" + arg + ")"); if (arg == "Xception") { Xception x = new Xception(); x.ErrorCode = 1001; x.Message = "This is an Xception"; throw x; } return; } public Xtruct testMultiException(string arg0, string arg1) { Console.WriteLine("testMultiException(" + arg0 + ", " + arg1 + ")"); if (arg0 == "Xception") { Xception x = new Xception(); x.ErrorCode = 1001; x.Message = "This is an Xception"; throw x; } else if (arg0 == "Xception2") { Xception2 x = new Xception2(); x.ErrorCode = 2002; x.Struct_thing = new Xtruct(); x.Struct_thing.String_thing = "This is an Xception2"; throw x; } Xtruct result = new Xtruct(); result.String_thing = arg1; return result; } public void testStop() { if (server != null) { server.Stop(); } } public void testOneway(int arg) { Console.WriteLine("testOneway(" + arg + "), sleeping..."); System.Threading.Thread.Sleep(arg * 1000); Console.WriteLine("testOneway finished"); } } // class TestHandler public static void Execute(string[] args) { try { bool useBufferedSockets = false, useFramed = false; int port = 9090; if (args.Length > 0) { port = int.Parse(args[0]); if (args.Length > 1) { if ( args[1] == "raw" ) { // as default } else if ( args[1] == "buffered" ) { useBufferedSockets = true; } else if ( args[1] == "framed" ) { useFramed = true; } else { // Fall back to the older boolean syntax bool.TryParse(args[1], out useBufferedSockets); } } } // Processor TestHandler testHandler = new TestHandler(); ThriftTest.Processor testProcessor = new ThriftTest.Processor(testHandler); // Transport TServerSocket tServerSocket = new TServerSocket(port, 0, useBufferedSockets); // Simple Server TServer serverEngine; if ( useFramed ) serverEngine = new TSimpleServer(testProcessor, tServerSocket, new TFramedTransport.Factory()); else serverEngine = new TSimpleServer(testProcessor, tServerSocket); // ThreadPool Server // serverEngine = new TThreadPoolServer(testProcessor, tServerSocket); // Threaded Server // serverEngine = new TThreadedServer(testProcessor, tServerSocket); testHandler.server = serverEngine; // Run it Console.WriteLine("Starting the server on port " + port + (useBufferedSockets ? " with buffered socket" : "") + (useFramed ? " with framed transport" : "") + "..."); serverEngine.Serve(); } catch (Exception x) { Console.Error.Write(x); } Console.WriteLine("done."); } } }
// Copyright 2017 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. // This is a Keyboard Subclass that runs on device only. It displays the // full VR Keyboard. using UnityEngine; using UnityEngine.VR; using System; using System.Runtime.InteropServices; /// @cond namespace Gvr.Internal { public class AndroidNativeKeyboardProvider : IKeyboardProvider { private IntPtr renderEventFunction; // Android method names. private const string METHOD_NAME_GET_PACKAGE_MANAGER = "getPackageManager"; private const string METHOD_NAME_GET_PACKAGE_INFO = "getPackageInfo"; private const string PACKAGE_NAME_VRINPUTMETHOD = "com.google.android.vr.inputmethod"; private const string FIELD_NAME_VERSION_CODE = "versionCode"; // Min version for VrInputMethod. private const int MIN_VERSION_VRINPUTMETHOD = 170509062; // Library name. private const string dllName = "gvr_keyboard_shim_unity"; // Enum gvr_trigger_state. private const int TRIGGER_NONE = 0; private const int TRIGGER_PRESSED = 1; [StructLayout (LayoutKind.Sequential)] private struct gvr_clock_time_point { public long monotonic_system_time_nanos; } [StructLayout (LayoutKind.Sequential)] private struct gvr_recti { public int left; public int right; public int bottom; public int top; } [DllImport (GvrActivityHelper.GVR_DLL_NAME)] private static extern gvr_clock_time_point gvr_get_time_point_now(); [DllImport (dllName)] private static extern GvrKeyboardInputMode gvr_keyboard_get_input_mode(IntPtr keyboard_context); [DllImport (dllName)] private static extern void gvr_keyboard_set_input_mode(IntPtr keyboard_context, GvrKeyboardInputMode mode); #if UNITY_ANDROID [DllImport(dllName)] private static extern IntPtr gvr_keyboard_initialize(AndroidJavaObject app_context, AndroidJavaObject class_loader); #endif [DllImport (dllName)] private static extern IntPtr gvr_keyboard_create(IntPtr closure, GvrKeyboard.KeyboardCallback callback); // Gets a recommended world space matrix. [DllImport (dllName)] private static extern void gvr_keyboard_get_recommended_world_from_keyboard_matrix(float distance_from_eye, IntPtr matrix); // Sets the recommended world space matrix. The matrix may // contain a combination of translation/rotation/scaling information. [DllImport(dllName)] private static extern void gvr_keyboard_set_world_from_keyboard_matrix(IntPtr keyboard_context, IntPtr matrix); // Shows the keyboard [DllImport (dllName)] private static extern void gvr_keyboard_show(IntPtr keyboard_context); // Updates the keyboard with the controller's button state. [DllImport(dllName)] private static extern void gvr_keyboard_update_button_state(IntPtr keyboard_context, int buttonIndex, bool pressed); // Updates the controller ray on the keyboard. [DllImport(dllName)] private static extern bool gvr_keyboard_update_controller_ray(IntPtr keyboard_context, IntPtr vector3Start, IntPtr vector3End, IntPtr vector3Hit); // Returns the EditText with for the keyboard. [DllImport (dllName)] private static extern IntPtr gvr_keyboard_get_text(IntPtr keyboard_context); // Sets the edit_text for the keyboard. // @return 1 if the edit text could be set. 0 if it cannot be set. [DllImport (dllName)] private static extern int gvr_keyboard_set_text(IntPtr keyboard_context, IntPtr edit_text); // Hides the keyboard. [DllImport (dllName)] private static extern void gvr_keyboard_hide(IntPtr keyboard_context); // Destroys the keyboard. Resources related to the keyboard is released. [DllImport (dllName)] private static extern void gvr_keyboard_destroy(IntPtr keyboard_context); // Called once per frame to set the time index. [DllImport(dllName)] private static extern void GvrKeyboardSetFrameData(IntPtr keyboard_context, gvr_clock_time_point t); // Sets VR eye data in preparation for rendering a single eye's view. [DllImport(dllName)] private static extern void GvrKeyboardSetEyeData(int eye_type, Matrix4x4 modelview, Matrix4x4 projection, gvr_recti viewport); [DllImport(dllName)] private static extern IntPtr GetKeyboardRenderEventFunc(); // Private class data. private IntPtr keyboard_context = IntPtr.Zero; // Used in the GVR Unity C++ shim layer. private const int advanceID = 0x5DAC793B; private const int renderLeftID = 0x3CF97A3D; private const int renderRightID = 0x3CF97A3E; private const string KEYBOARD_JAVA_CLASS = "com.google.vr.keyboard.GvrKeyboardUnity"; private const long kPredictionTimeWithoutVsyncNanos = 50000000; private const int kGvrControllerButtonClick = 1; private GvrKeyboardInputMode mode = GvrKeyboardInputMode.DEFAULT; private string editorText = string.Empty; private Matrix4x4 worldMatrix; private bool isValid = false; private bool isReady = false; public string EditorText { get { IntPtr text = gvr_keyboard_get_text(keyboard_context); editorText = Marshal.PtrToStringAnsi(text); return editorText; } set { editorText = value; IntPtr text = Marshal.StringToHGlobalAnsi(editorText); gvr_keyboard_set_text(keyboard_context, text); } } public void SetInputMode(GvrKeyboardInputMode mode) { Debug.Log("Calling set input mode: " + mode); gvr_keyboard_set_input_mode(keyboard_context, mode); this.mode = mode; } public void OnPause() { } public void OnResume() { } public void ReadState(KeyboardState outState) { outState.editorText = editorText; outState.mode = mode; outState.worldMatrix = worldMatrix; outState.isValid = isValid; outState.isReady = isReady; } // Initialization function. public AndroidNativeKeyboardProvider() { #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { Debug.Log("Failed to get activity for keyboard."); return; } AndroidJavaObject context = GvrActivityHelper.GetApplicationContext(activity); if (context == null) { Debug.Log("Failed to get context for keyboard."); return; } AndroidJavaObject plugin = new AndroidJavaObject(KEYBOARD_JAVA_CLASS); if (plugin != null) { plugin.Call("initializeKeyboard", context); isValid = true; } #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Prevent compilation errors on 5.3.3 and lower. #if UNITY_HAS_GOOGLEVR UnityEngine.XR.InputTracking.disablePositionalTracking = true; #endif // UNITY_HAS_GOOGLEVR renderEventFunction = GetKeyboardRenderEventFunc(); } ~AndroidNativeKeyboardProvider() { gvr_keyboard_destroy(keyboard_context); } public bool Create(GvrKeyboard.KeyboardCallback keyboardEvent) { if (!IsVrInputMethodAppMinVersion(keyboardEvent)) { return false; } keyboard_context = gvr_keyboard_create(IntPtr.Zero, keyboardEvent); isReady = keyboard_context != IntPtr.Zero; return isReady; } public void Show(Matrix4x4 userMatrix, bool useRecommended, float distance, Matrix4x4 model) { if (useRecommended) { worldMatrix = getRecommendedMatrix(distance); } else { // Convert to GVR coordinates. Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); worldMatrix = flipZ * userMatrix * flipZ; worldMatrix = worldMatrix.transpose; } Matrix4x4 matToSet = worldMatrix * model.transpose; IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(matToSet)); Marshal.StructureToPtr(matToSet, mat_ptr, true); gvr_keyboard_set_world_from_keyboard_matrix(keyboard_context, mat_ptr); gvr_keyboard_show(keyboard_context); } public void UpdateData() { #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Update controller state. GvrBasePointer pointer = GvrPointerManager.Pointer; if (pointer != null && GvrController.State == GvrConnectionState.Connected) { bool pressed = GvrController.ClickButton; gvr_keyboard_update_button_state(keyboard_context, kGvrControllerButtonClick, pressed); Vector3 startPoint = pointer.PointerTransform.position; // Need to flip Z for native library startPoint.z *= -1; IntPtr start_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(startPoint)); Marshal.StructureToPtr(startPoint, start_ptr, true); Vector3 endPoint = pointer.LineEndPoint; // Need to flip Z for native library endPoint.z *= -1; IntPtr end_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(endPoint)); Marshal.StructureToPtr(endPoint, end_ptr, true); Vector3 hit = Vector3.one; IntPtr hit_ptr = Marshal.AllocHGlobal(Marshal.SizeOf(Vector3.zero)); Marshal.StructureToPtr(Vector3.zero, hit_ptr, true); gvr_keyboard_update_controller_ray(keyboard_context, start_ptr, end_ptr, hit_ptr); hit = (Vector3)Marshal.PtrToStructure(hit_ptr, typeof(Vector3)); hit.z *= -1; } #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR // Get time stamp. gvr_clock_time_point time = gvr_get_time_point_now(); time.monotonic_system_time_nanos += kPredictionTimeWithoutVsyncNanos; // Update frame data. GvrKeyboardSetFrameData(keyboard_context, time); GL.IssuePluginEvent(renderEventFunction, advanceID); } public void Render(int eye, Matrix4x4 modelview, Matrix4x4 projection, Rect viewport) { gvr_recti rect = new gvr_recti(); rect.left = (int)viewport.x; rect.top = (int)viewport.y + (int)viewport.height; rect.right = (int)viewport.x + (int)viewport.width; rect.bottom = (int)viewport.y; // For the modelview matrix, we need to convert it to a world-to-camera // matrix for GVR keyboard, hence the inverse. We need to convert left // handed to right handed, hence the multiply by flipZ. // Unity projection matrices are already in a form GVR needs. // Unity stores matrices row-major, so both get a final transpose to get // them column-major for GVR. Matrix4x4 flipZ = Matrix4x4.Scale(new Vector3(1, 1, -1)); GvrKeyboardSetEyeData(eye, (flipZ * modelview.inverse).transpose.inverse, projection.transpose, rect); GL.IssuePluginEvent(renderEventFunction, eye == 0 ? renderLeftID : renderRightID); } public void Hide() { gvr_keyboard_hide(keyboard_context); } // Return the recommended keyboard local to world space // matrix given a distance value by the user. This value should // be between 1 and 5 and will get clamped to that range. private Matrix4x4 getRecommendedMatrix(float inputDistance) { float distance = Mathf.Clamp(inputDistance, 1.0f, 5.0f); Matrix4x4 result = new Matrix4x4(); IntPtr mat_ptr = Marshal.AllocHGlobal(Marshal.SizeOf (result)); Marshal.StructureToPtr(result, mat_ptr, true); gvr_keyboard_get_recommended_world_from_keyboard_matrix(distance, mat_ptr); result = (Matrix4x4) Marshal.PtrToStructure(mat_ptr, typeof(Matrix4x4)); return result; } // Returns true if the VrInputMethod APK is at least as high as MIN_VERSION_VRINPUTMETHOD. private bool IsVrInputMethodAppMinVersion(GvrKeyboard.KeyboardCallback keyboardEvent) { #if UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR AndroidJavaObject activity = GvrActivityHelper.GetActivity(); if (activity == null) { Debug.Log("Failed to get activity for keyboard."); return false; } AndroidJavaObject packageManager = activity.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_MANAGER); if (packageManager == null) { Debug.Log("Failed to get activity package manager"); return false; } AndroidJavaObject info = packageManager.Call<AndroidJavaObject>(METHOD_NAME_GET_PACKAGE_INFO, PACKAGE_NAME_VRINPUTMETHOD, 0); if (info == null) { Debug.Log("Failed to get package info for com.google.android.apps.vr.inputmethod"); return false; } int versionCode = info.Get<int>(FIELD_NAME_VERSION_CODE); if (versionCode < MIN_VERSION_VRINPUTMETHOD) { keyboardEvent(IntPtr.Zero, GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED); return false; } return true; #else return true; #endif // UNITY_HAS_GOOGLEVR && UNITY_ANDROID && !UNITY_EDITOR } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.DirectoryServices.ActiveDirectory { internal enum NCFlags : int { InstanceTypeIsNCHead = 1, InstanceTypeIsWriteable = 4 } internal enum ApplicationPartitionType : int { Unknown = -1, ADApplicationPartition = 0, ADAMApplicationPartition = 1 } public class ApplicationPartition : ActiveDirectoryPartition { private bool _disposed = false; private ApplicationPartitionType _appType = (ApplicationPartitionType)(-1); private bool _committed = true; private DirectoryEntry _domainDNSEntry = null; private DirectoryEntry _crossRefEntry = null; private string _dnsName = null; private DirectoryServerCollection _cachedDirectoryServers = null; private bool _securityRefDomainModified = false; private string _securityRefDomain = null; #region constructors // Public Constructors public ApplicationPartition(DirectoryContext context, string distinguishedName) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, null, false); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, "domainDns"); } public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass) { // validate the parameters ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true); // call private function for creating the application partition CreateApplicationPartition(distinguishedName, objectClass); } // Internal Constructors internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr) : base(context, distinguishedName) { this.directoryEntryMgr = directoryEntryMgr; _appType = appType; _dnsName = dnsName; } internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, DirectoryEntryManager directoryEntryMgr) : this(context, distinguishedName, dnsName, GetApplicationPartitionType(context), directoryEntryMgr) { } #endregion constructors #region IDisposable // private Dispose method protected override void Dispose(bool disposing) { if (!_disposed) { try { // if there are any managed or unmanaged // resources to be freed, those should be done here // if disposing = true, only unmanaged resources should // be freed, else both managed and unmanaged. if (_crossRefEntry != null) { _crossRefEntry.Dispose(); _crossRefEntry = null; } if (_domainDNSEntry != null) { _domainDNSEntry.Dispose(); _domainDNSEntry = null; } _disposed = true; } finally { base.Dispose(); } } } #endregion IDisposable #region public methods public static ApplicationPartition GetApplicationPartition(DirectoryContext context) { // validate the context if (context == null) { throw new ArgumentNullException(nameof(context)); } // contexttype should be ApplicationPartiton if (context.ContextType != DirectoryContextType.ApplicationPartition) { throw new ArgumentException(SR.TargetShouldBeAppNCDnsName, nameof(context)); } // target must be ndnc dns name if (!context.isNdnc()) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } // work with copy of the context context = new DirectoryContext(context); // bind to the application partition head (this will verify credentials) string distinguishedName = Utils.GetDNFromDnsName(context.Name); DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry appNCHead = null; try { appNCHead = directoryEntryMgr.GetCachedDirectoryEntry(distinguishedName); // need to force the bind appNCHead.Bind(true); } catch (COMException e) { int errorCode = e.ErrorCode; if (errorCode == unchecked((int)0x8007203a)) { throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } return new ApplicationPartition(context, distinguishedName, context.Name, ApplicationPartitionType.ADApplicationPartition, directoryEntryMgr); } public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName) { ApplicationPartition partition = null; DirectoryEntryManager directoryEntryMgr = null; DirectoryContext appNCContext = null; // check that the argument is not null if (context == null) throw new ArgumentNullException(nameof(context)); if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } if (context.Name != null) { // the target should be a valid forest name, configset name or a server if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer())) { throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } } // check that the distingushed name of the application partition is not null or empty if (distinguishedName == null) throw new ArgumentNullException(nameof(distinguishedName)); if (distinguishedName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(distinguishedName)); if (!Utils.IsValidDNFormat(distinguishedName)) throw new ArgumentException(SR.InvalidDNFormat, nameof(distinguishedName)); // work with copy of the context context = new DirectoryContext(context); // search in the partitions container of the forest for // crossRef objects that have their nCName set to the specified distinguishedName directoryEntryMgr = new DirectoryEntryManager(context); DirectoryEntry partitionsEntry = null; try { partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } // build the filter StringBuilder str = new StringBuilder(15); str.Append("(&("); str.Append(PropertyManager.ObjectCategory); str.Append("=crossRef)("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.804:="); str.Append((int)SystemFlag.SystemFlagNtdsNC); str.Append(")(!("); str.Append(PropertyManager.SystemFlags); str.Append(":1.2.840.113556.1.4.803:="); str.Append((int)SystemFlag.SystemFlagNtdsDomain); str.Append("))("); str.Append(PropertyManager.NCName); str.Append("="); str.Append(Utils.GetEscapedFilterValue(distinguishedName)); str.Append("))"); string filter = str.ToString(); string[] propertiesToLoad = new string[2]; propertiesToLoad[0] = PropertyManager.DnsRoot; propertiesToLoad[1] = PropertyManager.NCName; ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/); SearchResult res = null; try { res = searcher.FindOne(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { partitionsEntry.Dispose(); } if (res == null) { // the specified application partition could not be found in the given forest throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } string appNCDnsName = null; try { appNCDnsName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? (string)res.Properties[PropertyManager.DnsRoot][0] : null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // verify that if the target is a server, then this partition is a naming context on it ApplicationPartitionType appType = GetApplicationPartitionType(context); if (context.ContextType == DirectoryContextType.DirectoryServer) { bool hostsCurrentPartition = false; DistinguishedName appNCDN = new DistinguishedName(distinguishedName); DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string namingContext in rootDSE.Properties[PropertyManager.NamingContexts]) { DistinguishedName dn = new DistinguishedName(namingContext); if (dn.Equals(appNCDN)) { hostsCurrentPartition = true; break; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } if (!hostsCurrentPartition) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } appNCContext = context; } else { // we need to find a server which hosts this application partition if (appType == ApplicationPartitionType.ADApplicationPartition) { int errorCode = 0; DomainControllerInfo domainControllerInfo; errorCode = Locator.DsGetDcNameWrapper(null, appNCDnsName, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindByName - domainControllerInfo.DomainControllerName.Length <= 2"); string serverName = domainControllerInfo.DomainControllerName.Substring(2); appNCContext = Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context); } else { // this will find an adam instance that hosts this partition and which is alive and responding. string adamInstName = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name; appNCContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context); } } partition = new ApplicationPartition(appNCContext, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), appNCDnsName, appType, directoryEntryMgr); return partition; } public DirectoryServer FindDirectoryServer() { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, false); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public DirectoryServer FindDirectoryServer(bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(null, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null); } return directoryServer; } public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD directoryServer = FindDirectoryServerInternal(siteName, forceRediscovery); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // forceRediscovery is ignored for ADAM Application partition directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName); } return directoryServer; } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(null); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, null)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDirectoryServersInternal(siteName); } else { // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection(); directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, siteName)); return directoryServers; } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers() { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(null); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(string siteName) { CheckIfDisposed(); if (siteName == null) { throw new ArgumentNullException(nameof(siteName)); } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // AD return FindAllDiscoverableDirectoryServersInternal(siteName); } else { // // throw exception for ADAM // throw new NotSupportedException(SR.OperationInvalidForADAM); } } public void Delete() { CheckIfDisposed(); // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // Get the partitions container and delete the crossRef entry for this // application partition DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { GetCrossRefEntry(); partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { partitionsEntry.Dispose(); } } public void Save() { CheckIfDisposed(); if (!_committed) { bool createManually = false; if (_appType == ApplicationPartitionType.ADApplicationPartition) { try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072029)) { // inappropriate authentication (we might have fallen back to NTLM) createManually = true; } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // for ADAM we always create the crossRef manually before creating the domainDNS object createManually = true; } if (createManually) { // we need to first save the cross ref entry try { InitializeCrossRef(partitionName); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { _domainDNSEntry.CommitChanges(); } catch (COMException e) { // //delete the crossRef entry // DirectoryEntry partitionsEntry = _crossRefEntry.Parent; try { partitionsEntry.Children.Remove(_crossRefEntry); } catch (COMException e2) { throw ExceptionHelper.GetExceptionFromCOMException(e2); } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } // if the crossRef is created manually we need to refresh the cross ref entry to get the changes that were made // due to the creation of the partition try { _crossRefEntry.RefreshCache(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } // When we create a domainDNS object on DC1 (Naming Master = DC2), // then internally DC1 will contact DC2 to create the disabled crossRef object. // DC2 will force replicate the crossRef object to DC1. DC1 will then create // the domainDNS object and enable the crossRef on DC1 (not DC2). // Here we need to force replicate the enabling of the crossRef to the FSMO (DC2) // so that we can later add replicas (which need to modify an attribute on the crossRef // on DC2, the FSMO, and can only be done if the crossRef on DC2 is enabled) // get the ntdsa name of the server on which the partition is created DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string primaryServerNtdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); // get the DN of the crossRef entry that needs to be replicated to the fsmo role if (_appType == ApplicationPartitionType.ADApplicationPartition) { // for AD we may not have the crossRef entry yet GetCrossRefEntry(); } string crossRefDN = (string)PropertyManager.GetPropertyValue(context, _crossRefEntry, PropertyManager.DistinguishedName); // Now set the operational attribute "replicateSingleObject" on the Rootdse of the fsmo role // to <ntdsa name of the source>:<DN of the crossRef object which needs to be replicated> DirectoryContext fsmoContext = Utils.GetNewDirectoryContext(GetNamingRoleOwner(), DirectoryContextType.DirectoryServer, context); DirectoryEntry fsmoRootDSE = DirectoryEntryManager.GetDirectoryEntry(fsmoContext, WellKnownDN.RootDSE); try { fsmoRootDSE.Properties[PropertyManager.ReplicateSingleObject].Value = primaryServerNtdsaName + ":" + crossRefDN; fsmoRootDSE.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { fsmoRootDSE.Dispose(); } // the partition has been created _committed = true; // commit the replica locations information or security reference domain if applicable if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { if (_cachedDirectoryServers != null) { _crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].AddRange(_cachedDirectoryServers.GetMultiValuedProperty()); } if (_securityRefDomainModified) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = _securityRefDomain; } try { _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } else { // just save the crossRef entry for teh directory servers and the // security reference domain information if ((_cachedDirectoryServers != null) || (_securityRefDomainModified)) { try { // we should already have the crossRef entries as some attribute on it has already // been modified Debug.Assert(_crossRefEntry != null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null."); _crossRefEntry.CommitChanges(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } // invalidate cached info _cachedDirectoryServers = null; _securityRefDomainModified = false; } public override DirectoryEntry GetDirectoryEntry() { CheckIfDisposed(); if (!_committed) { throw new InvalidOperationException(SR.CannotGetObject); } return DirectoryEntryManager.GetDirectoryEntry(context, Name); } #endregion public methods #region public properties public DirectoryServerCollection DirectoryServers { get { CheckIfDisposed(); if (_cachedDirectoryServers == null) { ReadOnlyDirectoryServerCollection servers = (_committed) ? FindAllDirectoryServers() : new ReadOnlyDirectoryServerCollection(); bool isADAM = (_appType == ApplicationPartitionType.ADAMApplicationPartition) ? true : false; // Get the cross ref entry if we don't already have it if (_committed) { GetCrossRefEntry(); } // // If the application partition is already committed at this point, we pass in the directory entry for teh crossRef, so any modifications // are made directly on the crossRef entry. If at this point we do not have a crossRefEntry, we pass in null, while saving, we get the information // from the collection and set it on the appropriate attribute on the crossRef directory entry. // // _cachedDirectoryServers = new DirectoryServerCollection(context, (_committed) ? _crossRefEntry : null, isADAM, servers); } return _cachedDirectoryServers; } } public string SecurityReferenceDomain { get { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); try { if (_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Count > 0) { return (string)_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value; } else { return null; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { return _securityRefDomain; } } set { CheckIfDisposed(); if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { throw new NotSupportedException(SR.PropertyInvalidForADAM); } if (_committed) { GetCrossRefEntry(); // modify the security reference domain // this will get committed when the crossRefEntry is committed if (value == null) { if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSSDReferenceDomain)) { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Clear(); _securityRefDomainModified = true; } } else { _crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = value; _securityRefDomainModified = true; } } else { if (!((_securityRefDomain == null) && (value == null))) { _securityRefDomain = value; _securityRefDomainModified = true; } } } } #endregion public properties #region private methods private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string objectClass, bool objectClassSpecified) { // validate context if (context == null) { throw new ArgumentNullException(nameof(context)); } // contexttype should be DirectoryServer if ((context.Name == null) || (!context.isServer())) { throw new ArgumentException(SR.TargetShouldBeServer, nameof(context)); } // check that the distinguished name is not null or empty if (distinguishedName == null) { throw new ArgumentNullException(nameof(distinguishedName)); } if (distinguishedName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(distinguishedName)); } // initialize private variables this.context = new DirectoryContext(context); this.directoryEntryMgr = new DirectoryEntryManager(this.context); // validate the distinguished name // Utils.GetDnsNameFromDN will throw an ArgumentException if the dn is not valid (cannot be syntactically converted to dns name) _dnsName = Utils.GetDnsNameFromDN(distinguishedName); this.partitionName = distinguishedName; // // if the partition being created is a one-level partition, we do not support it // Component[] components = Utils.GetDNComponents(distinguishedName); if (components.Length == 1) { throw new NotSupportedException(SR.OneLevelPartitionNotSupported); } // check if the object class can be specified _appType = GetApplicationPartitionType(this.context); if ((_appType == ApplicationPartitionType.ADApplicationPartition) && (objectClassSpecified)) { throw new InvalidOperationException(SR.NoObjectClassForADPartition); } else if (objectClassSpecified) { // ADAM case and objectClass is explicitly specified, so must be validated if (objectClass == null) { throw new ArgumentNullException(nameof(objectClass)); } if (objectClass.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(objectClass)); } } if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // the target in the directory context could be the netbios name of the server, so we will get the dns name // (since application partition creation will fail if dns name is not specified) // string serverDnsName = null; try { DirectoryEntry rootDSEEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); serverDnsName = (string)PropertyManager.GetPropertyValue(this.context, rootDSEEntry, PropertyManager.DnsHostName); } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(this.context, e); } this.context = Utils.GetNewDirectoryContext(serverDnsName, DirectoryContextType.DirectoryServer, context); } } private void CreateApplicationPartition(string distinguishedName, string objectClass) { if (_appType == ApplicationPartitionType.ADApplicationPartition) { // // AD // 1. Bind to the non-existent application partition using the fast bind and delegation option // 2. Get the Parent object and create a new "domainDNS" object under it // 3. Set the instanceType and the description for the application partitin object // DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind | AuthenticationTypes.Delegation; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.GetServerName() + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), PropertyManager.DomainDNS); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } else { // // ADAM // 1. Bind to the partitions container on the domain naming owner instance // 2. Create a disabled crossRef object for the new application partition // 3. Bind to the target hint and follow the same steps as for AD // try { InitializeCrossRef(distinguishedName); DirectoryEntry tempEntry = null; DirectoryEntry parent = null; try { AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind; authType |= AuthenticationTypes.ServerBind; tempEntry = new DirectoryEntry("LDAP://" + context.Name + "/" + distinguishedName, context.UserName, context.Password, authType); parent = tempEntry.Parent; _domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), objectClass); // set the instance type to 5 _domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable; // mark this as uncommitted _committed = false; } finally { // dispose all resources if (parent != null) { parent.Dispose(); } if (tempEntry != null) { tempEntry.Dispose(); } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } private void InitializeCrossRef(string distinguishedName) { if (_crossRefEntry != null) // already initialized return; DirectoryEntry partitionsEntry = null; try { string namingFsmoName = GetNamingRoleOwner(); DirectoryContext roleOwnerContext = Utils.GetNewDirectoryContext(namingFsmoName, DirectoryContextType.DirectoryServer, context); partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(roleOwnerContext, WellKnownDN.PartitionsContainer); string uniqueName = "CN={" + Guid.NewGuid() + "}"; _crossRefEntry = partitionsEntry.Children.Add(uniqueName, "crossRef"); string dnsHostName = null; if (_appType == ApplicationPartitionType.ADAMApplicationPartition) { // Bind to rootdse and get the server name DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE); string ntdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName); dnsHostName = Utils.GetAdamHostNameAndPortsFromNTDSA(context, ntdsaName); } else { // for AD the name in the context will be the dns name of the server dnsHostName = context.Name; } // create disabled cross ref object _crossRefEntry.Properties[PropertyManager.DnsRoot].Value = dnsHostName; _crossRefEntry.Properties[PropertyManager.Enabled].Value = false; _crossRefEntry.Properties[PropertyManager.NCName].Value = distinguishedName; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { if (partitionsEntry != null) { partitionsEntry.Dispose(); } } } private static ApplicationPartitionType GetApplicationPartitionType(DirectoryContext context) { ApplicationPartitionType type = ApplicationPartitionType.Unknown; DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); try { foreach (string supportedCapability in rootDSE.Properties[PropertyManager.SupportedCapabilities]) { if (string.Equals(supportedCapability, SupportedCapability.ADOid, StringComparison.OrdinalIgnoreCase)) { type = ApplicationPartitionType.ADApplicationPartition; } if (string.Equals(supportedCapability, SupportedCapability.ADAMOid, StringComparison.OrdinalIgnoreCase)) { type = ApplicationPartitionType.ADAMApplicationPartition; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } finally { rootDSE.Dispose(); } // should not happen if (type == ApplicationPartitionType.Unknown) { throw new ActiveDirectoryOperationException(SR.ApplicationPartitionTypeUnknown); } return type; } // we always get the crossEntry bound to the FSMO role // this is so that we do not encounter any replication delay related issues internal DirectoryEntry GetCrossRefEntry() { if (_crossRefEntry != null) { return _crossRefEntry; } DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { _crossRefEntry = Utils.GetCrossRefEntry(context, partitionsEntry, Name); } finally { partitionsEntry.Dispose(); } return _crossRefEntry; } internal string GetNamingRoleOwner() { string namingFsmo = null; DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer)); try { if (_appType == ApplicationPartitionType.ADApplicationPartition) { namingFsmo = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } else { namingFsmo = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner)); } } finally { partitionsEntry.Dispose(); } return namingFsmo; } private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceRediscovery) { DirectoryServer directoryServer = null; LocatorOptions flag = 0; int errorCode = 0; DomainControllerInfo domainControllerInfo; if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } // set the force rediscovery flag if required if (forceRediscovery) { flag = LocatorOptions.ForceRediscovery; } // call DsGetDcName errorCode = Locator.DsGetDcNameWrapper(null, _dnsName, siteName, (long)flag | (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo); if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN) { throw new ActiveDirectoryObjectNotFoundException(SR.ReplicaNotFound, typeof(DirectoryServer), null); } else if (errorCode != 0) { throw ExceptionHelper.GetExceptionFromErrorCode(errorCode); } Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindDirectoryServerInternal - domainControllerInfo.DomainControllerName.Length <= 2"); string dcName = domainControllerInfo.DomainControllerName.Substring(2); // create a new context object for the domain controller passing on only the // credentials from the forest context DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); directoryServer = new DomainController(dcContext, dcName); return directoryServer; } private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } ArrayList dcList = new ArrayList(); foreach (string dcName in Utils.GetReplicaList(context, Name, siteName, false /* isDefaultNC */, false /* isADAM */, false /* mustBeGC */)) { DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context); dcList.Add(new DomainController(dcContext, dcName)); } return new ReadOnlyDirectoryServerCollection(dcList); } private ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServersInternal(string siteName) { if (siteName != null && siteName.Length == 0) { throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } // Check that the application partition has been committed if (!_committed) { throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject); } long flag = (long)PrivateLocatorFlags.OnlyLDAPNeeded; return new ReadOnlyDirectoryServerCollection(Locator.EnumerateDomainControllers(context, _dnsName, siteName, flag)); } #endregion private methods } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml.Linq; namespace DocumentFormat.OpenXml.Linq { /// <summary> /// Declares XNamespace and XName fields for the xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes" namespace. /// </summary> public static class VT { /// <summary> /// Defines the XML namespace associated with the vt prefix. /// </summary> public static readonly XNamespace vt = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"; /// <summary> /// Represents the vt:array XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>has the following child XML elements: <see cref="@bool" />, <see cref="bstr" />, <see cref="cy" />, <see cref="date" />, <see cref="@decimal" />, <see cref="error" />, <see cref="i1" />, <see cref="i2" />, <see cref="i4" />, <see cref="@int" />, <see cref="r4" />, <see cref="r8" />, <see cref="ui1" />, <see cref="ui2" />, <see cref="ui4" />, <see cref="@uint" />, <see cref="variant" />.</description></item> /// <item><description>has the following XML attributes: <see cref="NoNamespace.baseType" />, <see cref="NoNamespace.lBound" />, <see cref="NoNamespace.uBound" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTArray.</description></item> /// </list> /// </remarks> public static readonly XName array = vt + "array"; /// <summary> /// Represents the vt:blob XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="AP.DigSig" />, <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTBlob.</description></item> /// </list> /// </remarks> public static readonly XName blob = vt + "blob"; /// <summary> /// Represents the vt:bool XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTBool.</description></item> /// </list> /// </remarks> public static readonly XName @bool = vt + "bool"; /// <summary> /// Represents the vt:bstr XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTBString.</description></item> /// </list> /// </remarks> public static readonly XName bstr = vt + "bstr"; /// <summary> /// Represents the vt:cf XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>has the following XML attributes: <see cref="NoNamespace.format" />, <see cref="NoNamespace.size" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTClipboardData.</description></item> /// </list> /// </remarks> public static readonly XName cf = vt + "cf"; /// <summary> /// Represents the vt:clsid XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTClassId.</description></item> /// </list> /// </remarks> public static readonly XName clsid = vt + "clsid"; /// <summary> /// Represents the vt:cy XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTCurrency.</description></item> /// </list> /// </remarks> public static readonly XName cy = vt + "cy"; /// <summary> /// Represents the vt:date XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTDate.</description></item> /// </list> /// </remarks> public static readonly XName date = vt + "date"; /// <summary> /// Represents the vt:decimal XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTDecimal.</description></item> /// </list> /// </remarks> public static readonly XName @decimal = vt + "decimal"; /// <summary> /// Represents the vt:empty XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTEmpty.</description></item> /// </list> /// </remarks> public static readonly XName empty = vt + "empty"; /// <summary> /// Represents the vt:error XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTError.</description></item> /// </list> /// </remarks> public static readonly XName error = vt + "error"; /// <summary> /// Represents the vt:filetime XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTFileTime.</description></item> /// </list> /// </remarks> public static readonly XName filetime = vt + "filetime"; /// <summary> /// Represents the vt:i1 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTByte.</description></item> /// </list> /// </remarks> public static readonly XName i1 = vt + "i1"; /// <summary> /// Represents the vt:i2 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTShort.</description></item> /// </list> /// </remarks> public static readonly XName i2 = vt + "i2"; /// <summary> /// Represents the vt:i4 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTInt32.</description></item> /// </list> /// </remarks> public static readonly XName i4 = vt + "i4"; /// <summary> /// Represents the vt:i8 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTInt64.</description></item> /// </list> /// </remarks> public static readonly XName i8 = vt + "i8"; /// <summary> /// Represents the vt:int XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTInteger.</description></item> /// </list> /// </remarks> public static readonly XName @int = vt + "int"; /// <summary> /// Represents the vt:lpstr XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTLPSTR.</description></item> /// </list> /// </remarks> public static readonly XName lpstr = vt + "lpstr"; /// <summary> /// Represents the vt:lpwstr XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTLPWSTR.</description></item> /// </list> /// </remarks> public static readonly XName lpwstr = vt + "lpwstr"; /// <summary> /// Represents the vt:null XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTNull.</description></item> /// </list> /// </remarks> public static readonly XName @null = vt + "null"; /// <summary> /// Represents the vt:oblob XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTOBlob.</description></item> /// </list> /// </remarks> public static readonly XName oblob = vt + "oblob"; /// <summary> /// Represents the vt:ostorage XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTOStorage.</description></item> /// </list> /// </remarks> public static readonly XName ostorage = vt + "ostorage"; /// <summary> /// Represents the vt:ostream XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTOStreamData.</description></item> /// </list> /// </remarks> public static readonly XName ostream = vt + "ostream"; /// <summary> /// Represents the vt:r4 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTFloat.</description></item> /// </list> /// </remarks> public static readonly XName r4 = vt + "r4"; /// <summary> /// Represents the vt:r8 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTDouble.</description></item> /// </list> /// </remarks> public static readonly XName r8 = vt + "r8"; /// <summary> /// Represents the vt:storage XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTStorage.</description></item> /// </list> /// </remarks> public static readonly XName storage = vt + "storage"; /// <summary> /// Represents the vt:stream XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTStreamData.</description></item> /// </list> /// </remarks> public static readonly XName stream = vt + "stream"; /// <summary> /// Represents the vt:ui1 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTUnsignedByte.</description></item> /// </list> /// </remarks> public static readonly XName ui1 = vt + "ui1"; /// <summary> /// Represents the vt:ui2 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTUnsignedShort.</description></item> /// </list> /// </remarks> public static readonly XName ui2 = vt + "ui2"; /// <summary> /// Represents the vt:ui4 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTUnsignedInt32.</description></item> /// </list> /// </remarks> public static readonly XName ui4 = vt + "ui4"; /// <summary> /// Represents the vt:ui8 XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTUnsignedInt64.</description></item> /// </list> /// </remarks> public static readonly XName ui8 = vt + "ui8"; /// <summary> /// Represents the vt:uint XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="array" />, <see cref="variant" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTUnsignedInteger.</description></item> /// </list> /// </remarks> public static readonly XName @uint = vt + "uint"; /// <summary> /// Represents the vt:variant XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="array" />, <see cref="variant" />, <see cref="vector" />.</description></item> /// <item><description>has the following child XML elements: <see cref="array" />, <see cref="blob" />, <see cref="@bool" />, <see cref="bstr" />, <see cref="cf" />, <see cref="clsid" />, <see cref="cy" />, <see cref="date" />, <see cref="@decimal" />, <see cref="empty" />, <see cref="error" />, <see cref="filetime" />, <see cref="i1" />, <see cref="i2" />, <see cref="i4" />, <see cref="i8" />, <see cref="@int" />, <see cref="lpstr" />, <see cref="lpwstr" />, <see cref="@null" />, <see cref="oblob" />, <see cref="ostorage" />, <see cref="ostream" />, <see cref="r4" />, <see cref="r8" />, <see cref="storage" />, <see cref="stream" />, <see cref="ui1" />, <see cref="ui2" />, <see cref="ui4" />, <see cref="ui8" />, <see cref="@uint" />, <see cref="variant" />, <see cref="vector" />, <see cref="vstream" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: Variant.</description></item> /// </list> /// </remarks> public static readonly XName variant = vt + "variant"; /// <summary> /// Represents the vt:vector XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="AP.HeadingPairs" />, <see cref="AP.HLinks" />, <see cref="AP.TitlesOfParts" />, <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>has the following child XML elements: <see cref="@bool" />, <see cref="bstr" />, <see cref="cf" />, <see cref="clsid" />, <see cref="cy" />, <see cref="date" />, <see cref="error" />, <see cref="filetime" />, <see cref="i1" />, <see cref="i2" />, <see cref="i4" />, <see cref="i8" />, <see cref="lpstr" />, <see cref="lpwstr" />, <see cref="r4" />, <see cref="r8" />, <see cref="ui1" />, <see cref="ui2" />, <see cref="ui4" />, <see cref="ui8" />, <see cref="variant" />.</description></item> /// <item><description>has the following XML attributes: <see cref="NoNamespace.baseType" />, <see cref="NoNamespace.size" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTVector.</description></item> /// </list> /// </remarks> public static readonly XName vector = vt + "vector"; /// <summary> /// Represents the vt:vstream XML element. /// </summary> /// <remarks> /// <para>As an XML element, it:</para> /// <list type="bullet"> /// <item><description>has the following parent XML elements: <see cref="OP.property" />, <see cref="variant" />.</description></item> /// <item><description>has the following XML attributes: <see cref="NoNamespace.version" />.</description></item> /// <item><description>corresponds to the following strongly-typed classes: VTVStreamData.</description></item> /// </list> /// </remarks> public static readonly XName vstream = vt + "vstream"; } }
// 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.Globalization; using Xunit; namespace Windows.Foundation.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] public class RectTests { [Fact] public void Ctor_Default() { var rect = new Rect(); Assert.Equal(0, rect.X); Assert.Equal(0, rect.Y); Assert.Equal(0, rect.Width); Assert.Equal(0, rect.Height); Assert.Equal(0, rect.Left); Assert.Equal(0, rect.Right); Assert.Equal(0, rect.Top); Assert.Equal(0, rect.Bottom); Assert.False(rect.IsEmpty); } [Theory] [InlineData(0, 0, 0, 0, 0, 0, 0, 0)] [InlineData(1, 2, 3, 4, 1, 2, 3, 4)] [InlineData(double.MaxValue, double.MaxValue, double.MaxValue, double.MaxValue, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN)] [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] public void Ctor_X_Y_Width_Height(double x, double y, double width, double height, double expectedX, double expectedY, double expectedWidth, double expectedHeight) { var rect = new Rect(x, y, width, height); Assert.Equal(expectedX, rect.X); Assert.Equal(expectedY, rect.Y); Assert.Equal(expectedWidth, rect.Width); Assert.Equal(expectedHeight, rect.Height); Assert.Equal(expectedX, rect.Left); Assert.Equal(expectedX + expectedWidth, rect.Right); Assert.Equal(expectedY, rect.Top); Assert.Equal(expectedY + expectedHeight, rect.Bottom); Assert.False(rect.IsEmpty); } [Theory] [InlineData(-1)] [InlineData(double.NegativeInfinity)] public void Ctor_NegativeWidth_ThrowsArgumentOutOfRangeException(double width) { AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => new Rect(1, 1, width, 1)); } [Theory] [InlineData(-1)] [InlineData(double.NegativeInfinity)] public void Ctor_NegativeHeight_ThrowsArgumentOutOfRangeException(double height) { AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => new Rect(1, 1, 1, height)); } public static IEnumerable<object[]> Ctor_Point_Point_TestData() { yield return new object[] { new Point(1, 2), new Point(1, 2), 1, 2, 0, 0 }; yield return new object[] { new Point(1, 2), new Point(3, 4), 1, 2, 2, 2 }; yield return new object[] { new Point(3, 4), new Point(1, 2), 1, 2, 2, 2 }; } [Theory] [MemberData(nameof(Ctor_Point_Point_TestData))] public void Ctor_Point_Point(Point point1, Point point2, double expectedX, double expectedY, double expectedWidth, double expectedHeight) { var rect = new Rect(point1, point2); Assert.Equal(expectedX, rect.X); Assert.Equal(expectedY, rect.Y); Assert.Equal(expectedWidth, rect.Width); Assert.Equal(expectedHeight, rect.Height); } public static IEnumerable<object[]> Ctor_Point_Size_TestData() { yield return new object[] { new Point(1, 2), Size.Empty, double.PositiveInfinity, double.PositiveInfinity, double.NegativeInfinity, double.NegativeInfinity }; yield return new object[] { new Point(1, 2), new Size(0, 0), 1, 2, 0, 0 }; yield return new object[] { new Point(1, 2), new Size(3, 4), 1, 2, 3, 4 }; yield return new object[] { new Point(1, 2), new Size(double.MaxValue, double.MaxValue), 1, 2, double.PositiveInfinity, double.PositiveInfinity }; } [Theory] [MemberData(nameof(Ctor_Point_Size_TestData))] public void Ctor_Point_Size(Point point, Size size, double expectedX, double expectedY, double expectedWidth, double expectedHeight) { var rect = new Rect(point, size); Assert.Equal(expectedX, rect.X); Assert.Equal(expectedY, rect.Y); Assert.Equal(expectedWidth, rect.Width); Assert.Equal(expectedHeight, rect.Height); } [Fact] public void Empty_Get_ReturnsExpected() { Rect rect = Rect.Empty; Assert.Equal(double.PositiveInfinity, rect.X); Assert.Equal(double.PositiveInfinity, rect.Y); Assert.Equal(double.NegativeInfinity, rect.Width); Assert.Equal(double.NegativeInfinity, rect.Height); Assert.Equal(double.PositiveInfinity, rect.Left); Assert.Equal(double.NegativeInfinity, rect.Right); Assert.Equal(double.PositiveInfinity, rect.Top); Assert.Equal(double.NegativeInfinity, rect.Bottom); Assert.True(rect.IsEmpty); } public static IEnumerable<object[]> Coordinate_TestData() { yield return new object[] { double.MinValue, double.NegativeInfinity }; yield return new object[] { -1, -1 }; yield return new object[] { 0, 0 }; yield return new object[] { 1, 1 }; yield return new object[] { double.MaxValue, double.PositiveInfinity }; yield return new object[] { double.NaN, double.NaN }; yield return new object[] { double.NegativeInfinity, double.NegativeInfinity }; } [Theory] [MemberData(nameof(Coordinate_TestData))] public void X_Set_GetReturnsExpected(double x, double expectedX) { var rect = new Rect { X = x }; Assert.Equal(expectedX, rect.X); } [Theory] [MemberData(nameof(Coordinate_TestData))] public void Y_Set_GetReturnsExpected(double y, double expectedY) { var rect = new Rect { Y = y }; Assert.Equal(expectedY, rect.Y); } public static IEnumerable<object[]> Size_TestData() { yield return new object[] { 0, 0 }; yield return new object[] { 1, 1 }; yield return new object[] { double.MaxValue, double.PositiveInfinity }; } [Theory] [MemberData(nameof(Size_TestData))] public void Width_SetValid_GetReturnsExpected(double width, double expectedWidth) { var rect = new Rect { Width = width }; Assert.Equal(expectedWidth, rect.Width); } [Theory] [InlineData(-1)] [InlineData(double.NegativeInfinity)] public void Width_SetNegative_ThrowsArgumentOutOfRangeException(double width) { var rect = new Rect(); AssertExtensions.Throws<ArgumentOutOfRangeException>("Width", () => rect.Width = width); } [Theory] [MemberData(nameof(Size_TestData))] public void Height_SetValid_GetReturnsExpected(double height, double expectedHeight) { var rect = new Rect { Height = height }; Assert.Equal(expectedHeight, rect.Height); } [Theory] [InlineData(-1)] [InlineData(double.NegativeInfinity)] public void Height_SetNegative_ThrowsArgumentOutOfRangeException(double height) { var rect = new Rect(); AssertExtensions.Throws<ArgumentOutOfRangeException>("Height", () => rect.Height = height); } public static IEnumerable<object[]> Contains_TestData() { yield return new object[] { new Rect(1, 2, 3, 4), new Point(1, 2), true }; yield return new object[] { new Rect(1, 2, 3, 4), new Point(3, 4), true }; yield return new object[] { new Rect(1, 2, 3, 4), new Point(4, 6), true }; yield return new object[] { new Rect(1, 2, 3, 4), new Point(5, 7), false }; yield return new object[] { Rect.Empty, new Point(1, 2), false }; } [Theory] [MemberData(nameof(Contains_TestData))] public void Contains_Point_ReturnsExpected(Rect rect, Point point, bool expected) { Assert.Equal(expected, rect.Contains(point)); } public static IEnumerable<object[]> Intersect_TestData() { yield return new object[] { Rect.Empty, Rect.Empty, Rect.Empty }; yield return new object[] { Rect.Empty, new Rect(1,2 , 3, 4), Rect.Empty }; yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, Rect.Empty }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(0, 0, 0, 0), Rect.Empty }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 6, 6), new Rect(2, 2, 2, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 2, 2), new Rect(2, 2, 2, 2) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(-2, -2, 12, 12), new Rect(1, 2, 3, 4) }; } [Theory] [MemberData(nameof(Intersect_TestData))] public void Intersect_Rect_ReturnsExpected(Rect rect, Rect other, Rect expected) { rect.Intersect(other); Assert.Equal(expected, rect); } public static IEnumerable<object[]> Union_Rect_TestData() { yield return new object[] { Rect.Empty, Rect.Empty, Rect.Empty }; yield return new object[] { Rect.Empty, new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, new Rect(1, 2, 3, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(0, 0, 0, 0), new Rect(0, 0, 4, 6) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 6, 6), new Rect(1, 2, 7, 6) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 2, 2), new Rect(1, 2, 3, 4) }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(-2, -2, 2, 2), new Rect(-2, -2, 6, 8) }; yield return new object[] { new Rect(-1, -2, 3, 4), new Rect(2, 2, 2, 2), new Rect(-1, -2, 5, 6) }; yield return new object[] { new Rect(1, 2, double.PositiveInfinity, double.PositiveInfinity), new Rect(-1, -2, 3, 4), new Rect(-1, -2, double.PositiveInfinity, double.PositiveInfinity) }; yield return new object[] { new Rect(-1, -2, 3, 4), new Rect(1, 2, double.PositiveInfinity, double.PositiveInfinity), new Rect(-1, -2, double.PositiveInfinity, double.PositiveInfinity) }; } [Theory] [MemberData(nameof(Union_Rect_TestData))] public void Union_Rect_ReturnsExpected(Rect rect, Rect other, Rect expected) { rect.Union(other); Assert.Equal(expected, rect); } public static IEnumerable<object[]> Union_Point_TestData() { yield return new object[] { Rect.Empty, new Point(1, 2), new Rect(1, 2, 0, 0) }; yield return new object[] { new Rect(2, 3, 4, 5), new Point(1, 2), new Rect(1, 2, 5, 6) }; yield return new object[] { new Rect(2, 3, 4, 5), new Point(-1, -2), new Rect(-1, -2, 7, 10) }; yield return new object[] { new Rect(2, 3, 4, 5), new Point(2, 3), new Rect(2, 3, 4, 5) }; } [Theory] [MemberData(nameof(Union_Point_TestData))] public void Union_Point_ReturnsExpected(Rect rect, Point point, Rect expected) { rect.Union(point); Assert.Equal(expected, rect); } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 3, 4), true }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(2, 2, 3, 4), false }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 3, 3, 4), false }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 2, 4, 4), false }; yield return new object[] { new Rect(1, 2, 3, 4), new Rect(1, 3, 3, 5), false }; yield return new object[] { new Rect(1, 2, 3, 4), Rect.Empty, false }; yield return new object[] { Rect.Empty, Rect.Empty, true }; yield return new object[] { Rect.Empty, new Rect(1, 2, 3, 4), false }; yield return new object[] { new Rect(1, 2, 3, 4), new object(), false }; yield return new object[] { new Rect(1, 2, 3, 4), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Other_ReturnsExpected(Rect rect, object other, bool expected) { Assert.Equal(expected, rect.Equals(other)); if (other is Rect otherRect) { Assert.Equal(expected, rect == otherRect); Assert.Equal(!expected, rect != otherRect); Assert.Equal(expected, rect.Equals(otherRect)); Assert.Equal(expected, rect.GetHashCode().Equals(other.GetHashCode())); } } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new Rect(1, 2, 3, 4), null, null, "1,2,3,4" }; yield return new object[] { new Rect(1, 2, 3, 4), null, CultureInfo.InvariantCulture, "1,2,3,4" }; yield return new object[] { new Rect(1, 2, 3, 4), "", CultureInfo.InvariantCulture, "1,2,3,4" }; yield return new object[] { new Rect(1, 2, 3, 4), "abc", null, "abc,abc,abc,abc" }; yield return new object[] { new Rect(1, 2, 3, 4), "N4", CultureInfo.InvariantCulture, "1.0000,2.0000,3.0000,4.0000" }; yield return new object[] { new Rect(1, 2, 3, 4), "", new NumberFormatInfo { NumberDecimalSeparator = "," }, "1;2;3;4" }; } [Theory] [ActiveIssue(41849)] [MemberData(nameof(ToString_TestData))] public void ToString_Invoke_ReturnsExpected(Rect rect, string format, IFormatProvider formatProvider, string expected) { if (format == null) { if (formatProvider == null) { Assert.Equal(expected, rect.ToString()); } Assert.Equal(expected, rect.ToString(formatProvider)); } Assert.Equal(expected, ((IFormattable)rect).ToString(format, formatProvider)); } } }
namespace DevExpress.MailClient.Win.Controls { partial class ExportControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExportControl)); DevExpress.XtraBars.Ribbon.GalleryItemGroup galleryItemGroup1 = new DevExpress.XtraBars.Ribbon.GalleryItemGroup(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem1 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem2 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem3 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem4 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem5 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem6 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem7 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem8 = new DevExpress.XtraBars.Ribbon.GalleryItem(); DevExpress.XtraBars.Ribbon.GalleryItem galleryItem9 = new DevExpress.XtraBars.Ribbon.GalleryItem(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.exportGallery = new DevExpress.XtraBars.Ribbon.GalleryControl(); this.galleryControlClient1 = new DevExpress.XtraBars.Ribbon.GalleryControlClient(); this.backstageViewLabel1 = new DevExpress.MailClient.Win.Controls.BackstageViewLabel(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.exportGallery)).BeginInit(); this.exportGallery.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // resources.ApplyResources(this.splitContainer1, "splitContainer1"); this.splitContainer1.BackColor = System.Drawing.Color.Transparent; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1; this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // resources.ApplyResources(this.splitContainer1.Panel1, "splitContainer1.Panel1"); this.splitContainer1.Panel1.Controls.Add(this.exportGallery); this.splitContainer1.Panel1.Controls.Add(this.backstageViewLabel1); // // splitContainer1.Panel2 // resources.ApplyResources(this.splitContainer1.Panel2, "splitContainer1.Panel2"); this.splitContainer1.Panel2.Controls.Add(this.labelControl4); // // exportGallery // resources.ApplyResources(this.exportGallery, "exportGallery"); this.exportGallery.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder; this.exportGallery.Controls.Add(this.galleryControlClient1); this.exportGallery.DesignGalleryGroupIndex = 0; this.exportGallery.DesignGalleryItemIndex = 0; // // // this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.FontStyleDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.Image"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Hovered.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.FontStyleDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.Image"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Normal.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.FontStyleDelta"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.Image"))); this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.Appearance.ItemCaptionAppearance.Pressed.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.FontStyleDelta" + ""))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.Image"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Hovered.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.FontStyleDelta"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.Image"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Normal.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.FontSizeDelta = ((int)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.FontSizeDelta"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.FontStyleDelta" + ""))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.GradientMode"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.Image = ((System.Drawing.Image)(resources.GetObject("exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.Image"))); this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.Options.UseTextOptions = true; this.exportGallery.Gallery.Appearance.ItemDescriptionAppearance.Pressed.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; this.exportGallery.Gallery.AutoFitColumns = false; this.exportGallery.Gallery.AutoSize = DevExpress.XtraBars.Ribbon.GallerySizeMode.None; this.exportGallery.Gallery.BackColor = System.Drawing.Color.Transparent; this.exportGallery.Gallery.CheckDrawMode = DevExpress.XtraBars.Ribbon.Gallery.CheckDrawMode.OnlyImage; this.exportGallery.Gallery.ColumnCount = 1; this.exportGallery.Gallery.FixedImageSize = false; resources.ApplyResources(galleryItemGroup1, "galleryItemGroup1"); resources.ApplyResources(galleryItem1, "galleryItem1"); galleryItem1.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToPDF_32x32; galleryItem1.Tag = "PDF"; resources.ApplyResources(galleryItem2, "galleryItem2"); galleryItem2.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToHTML_32x32; galleryItem2.Tag = "HTML"; resources.ApplyResources(galleryItem3, "galleryItem3"); galleryItem3.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToMHT_32x32; galleryItem3.Tag = "MHT"; resources.ApplyResources(galleryItem4, "galleryItem4"); galleryItem4.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToRTF_32x32; galleryItem4.Tag = "RTF"; resources.ApplyResources(galleryItem5, "galleryItem5"); galleryItem5.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToXLS_32x32; galleryItem5.Tag = "XLS"; resources.ApplyResources(galleryItem6, "galleryItem6"); galleryItem6.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToXLSX_32x32; galleryItem6.Tag = "XLSX"; resources.ApplyResources(galleryItem7, "galleryItem7"); galleryItem7.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToCSV_32x32; galleryItem7.Tag = "CSV"; resources.ApplyResources(galleryItem8, "galleryItem8"); galleryItem8.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToText_32x32; galleryItem8.Tag = "Text"; resources.ApplyResources(galleryItem9, "galleryItem9"); galleryItem9.Image = global::DevExpress.MailClient.Win.Properties.Resources.ExportToImage_32x32; galleryItem9.Tag = "Image"; galleryItemGroup1.Items.AddRange(new DevExpress.XtraBars.Ribbon.GalleryItem[] { galleryItem1, galleryItem2, galleryItem3, galleryItem4, galleryItem5, galleryItem6, galleryItem7, galleryItem8, galleryItem9}); this.exportGallery.Gallery.Groups.AddRange(new DevExpress.XtraBars.Ribbon.GalleryItemGroup[] { galleryItemGroup1}); this.exportGallery.Gallery.ItemImageLocation = DevExpress.Utils.Locations.Left; this.exportGallery.Gallery.ShowGroupCaption = false; this.exportGallery.Gallery.ShowItemText = true; this.exportGallery.Gallery.ShowScrollBar = DevExpress.XtraBars.Ribbon.Gallery.ShowScrollBar.Auto; this.exportGallery.Gallery.StretchItems = true; this.exportGallery.Gallery.ItemClick += new DevExpress.XtraBars.Ribbon.GalleryItemClickEventHandler(this.galleryControlGallery1_ItemClick); this.exportGallery.Name = "exportGallery"; // // galleryControlClient1 // resources.ApplyResources(this.galleryControlClient1, "galleryControlClient1"); this.galleryControlClient1.GalleryControl = this.exportGallery; // // backstageViewLabel1 // resources.ApplyResources(this.backstageViewLabel1, "backstageViewLabel1"); this.backstageViewLabel1.AppearanceDisabled.Image = ((System.Drawing.Image)(resources.GetObject("backstageViewLabel1.Appearance.DisabledImage"))); this.backstageViewLabel1.Appearance.Font = ((System.Drawing.Font)(resources.GetObject("backstageViewLabel1.Appearance.Font"))); this.backstageViewLabel1.Appearance.FontSizeDelta = ((int)(resources.GetObject("backstageViewLabel1.Appearance.FontSizeDelta"))); this.backstageViewLabel1.Appearance.FontStyleDelta = ((System.Drawing.FontStyle)(resources.GetObject("backstageViewLabel1.Appearance.FontStyleDelta"))); this.backstageViewLabel1.Appearance.GradientMode = ((System.Drawing.Drawing2D.LinearGradientMode)(resources.GetObject("backstageViewLabel1.Appearance.GradientMode"))); this.backstageViewLabel1.AppearanceHovered.Image = ((System.Drawing.Image)(resources.GetObject("backstageViewLabel1.Appearance.HoverImage"))); this.backstageViewLabel1.Appearance.Image = ((System.Drawing.Image)(resources.GetObject("backstageViewLabel1.Appearance.Image"))); this.backstageViewLabel1.AppearancePressed.Image = ((System.Drawing.Image)(resources.GetObject("backstageViewLabel1.Appearance.PressedImage"))); this.backstageViewLabel1.LineLocation = DevExpress.XtraEditors.LineLocation.Bottom; this.backstageViewLabel1.LineVisible = true; this.backstageViewLabel1.LookAndFeel.UseDefaultLookAndFeel = false; this.backstageViewLabel1.Name = "backstageViewLabel1"; this.backstageViewLabel1.ShowLineShadow = false; // // labelControl4 // resources.ApplyResources(this.labelControl4, "labelControl4"); this.labelControl4.LineOrientation = DevExpress.XtraEditors.LabelLineOrientation.Vertical; this.labelControl4.LineVisible = true; this.labelControl4.Name = "labelControl4"; // // saveFileDialog1 // resources.ApplyResources(this.saveFileDialog1, "saveFileDialog1"); // // ExportControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer1); this.Name = "ExportControl"; this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.exportGallery)).EndInit(); this.exportGallery.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private BackstageViewLabel backstageViewLabel1; private DevExpress.XtraBars.Ribbon.GalleryControl exportGallery; private DevExpress.XtraBars.Ribbon.GalleryControlClient galleryControlClient1; private System.Windows.Forms.SaveFileDialog saveFileDialog1; private DevExpress.XtraEditors.LabelControl labelControl4; } }
// *********************************************************************** // Copyright (c) 2009-2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Builders; namespace NUnit.Framework { /// <summary> /// TestFixtureAttribute is used to mark a class that represents a TestFixture. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] public class TestFixtureAttribute : NUnitAttribute, IFixtureBuilder2, ITestFixtureData { private readonly NUnitTestFixtureBuilder _builder = new NUnitTestFixtureBuilder(); #region Constructors /// <summary> /// Default constructor /// </summary> public TestFixtureAttribute() : this( new object[0] ) { } /// <summary> /// Construct with a object[] representing a set of arguments. /// In .NET 2.0, the arguments may later be separated into /// type arguments and constructor arguments. /// </summary> /// <param name="arguments"></param> public TestFixtureAttribute(params object[] arguments) { RunState = RunState.Runnable; Arguments = arguments ?? new object[] { null }; TypeArgs = new Type[0]; Properties = new PropertyBag(); } #endregion #region ITestData Members /// <summary> /// Gets or sets the name of the test. /// </summary> /// <value>The name of the test.</value> public string TestName { get; set; } /// <summary> /// Gets or sets the RunState of this test fixture. /// </summary> public RunState RunState { get; private set; } /// <summary> /// The arguments originally provided to the attribute /// </summary> public object[] Arguments { get; } /// <summary> /// Properties pertaining to this fixture /// </summary> public IPropertyBag Properties { get; } #endregion #region ITestFixtureData Members /// <summary> /// Get or set the type arguments. If not set /// explicitly, any leading arguments that are /// Types are taken as type arguments. /// </summary> public Type[] TypeArgs { get; set; } #endregion #region Other Properties /// <summary> /// Descriptive text for this fixture /// </summary> public string Description { get { return Properties.Get(PropertyNames.Description) as string; } set { Properties.Set(PropertyNames.Description, value); } } /// <summary> /// The author of this fixture /// </summary> public string Author { get { return Properties.Get(PropertyNames.Author) as string; } set { Properties.Set(PropertyNames.Author, value); } } /// <summary> /// The type that this fixture is testing /// </summary> public Type TestOf { get { return _testOf; } set { _testOf = value; Properties.Set(PropertyNames.TestOf, value.FullName); } } private Type _testOf; /// <summary> /// Gets or sets the ignore reason. May set RunState as a side effect. /// </summary> /// <value>The ignore reason.</value> public string Ignore { get { return IgnoreReason; } set { IgnoreReason = value; } } /// <summary> /// Gets or sets the reason for not running the fixture. /// </summary> /// <value>The reason.</value> public string Reason { get { return this.Properties.Get(PropertyNames.SkipReason) as string; } set { this.Properties.Set(PropertyNames.SkipReason, value); } } /// <summary> /// Gets or sets the ignore reason. When set to a non-null /// non-empty value, the test is marked as ignored. /// </summary> /// <value>The ignore reason.</value> public string IgnoreReason { get { return Reason; } set { RunState = RunState.Ignored; Reason = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="NUnit.Framework.TestFixtureAttribute"/> is explicit. /// </summary> /// <value> /// <c>true</c> if explicit; otherwise, <c>false</c>. /// </value> public bool Explicit { get { return RunState == RunState.Explicit; } set { RunState = value ? RunState.Explicit : RunState.Runnable; } } /// <summary> /// Gets and sets the category for this fixture. /// May be a comma-separated list of categories. /// </summary> public string Category { get { //return Properties.Get(PropertyNames.Category) as string; var catList = Properties[PropertyNames.Category]; if (catList == null) return null; switch (catList.Count) { case 0: return null; case 1: return catList[0] as string; default: var cats = new string[catList.Count]; int index = 0; foreach (string cat in catList) cats[index++] = cat; return string.Join(",", cats); } } set { foreach (string cat in value.Split(new char[] { ',' })) Properties.Add(PropertyNames.Category, cat); } } #endregion #region IFixtureBuilder Members /// <summary> /// Builds a single test fixture from the specified type. /// </summary> /// <param name="type">The type to be used as a fixture.</param> public IEnumerable<TestSuite> BuildFrom(Type type) { yield return _builder.BuildFrom(type, PreFilter.Empty, this); } #endregion #region IFixtureBuilder2 Members /// <summary> /// Builds a single test fixture from the specified type. /// </summary> /// <param name="type">The type to be used as a fixture.</param> /// <param name="filter">Filter used to select methods as tests.</param> public IEnumerable<TestSuite> BuildFrom(Type type, IPreFilter filter) { yield return _builder.BuildFrom(type, filter, this); } #endregion } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.IntegrationTests.Policies.Util; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.Tests; using NUnit.Framework; #pragma warning disable 618 namespace Cassandra.IntegrationTests.Policies.Tests { [TestFixture, Category(TestCategory.Long), Ignore("tests that are not marked with 'short' need to be refactored/deleted")] public class ConsistencyTests : TestGlobals { private PolicyTestTools _policyTestTools = null; [SetUp] public void SetupTest() { _policyTestTools = new PolicyTestTools(); } /// <summary> /// Verify that replication factor one consistency is enforced, /// with load balancing policy TokenAware, RoundRobin /// /// @test_category consistency /// @test_category connection:outage /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorOne_TokenAware() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); testCluster.InitClient(); _policyTestTools.CreateSchema(testCluster.Session, 1); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.One); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.One); string coordinatorHostQueried = _policyTestTools.Coordinators.First().Key.Split(':').First(); int awareCoord = int.Parse(coordinatorHostQueried.Split('.').Last()); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + awareCoord + ":" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord + ":" + DefaultCassandraPort, testCluster.Cluster, 30); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any }; var failList = new List<ConsistencyLevel> { ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Three, ConsistencyLevel.Quorum, ConsistencyLevel.All }; // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("It must not pass at consistency level {0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Verify that replication factor two is enforced, /// with load balancing policy TokenAware, RoundRobin /// /// @test_category consistency /// @test_category connection:outage /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorTwo_TokenAware() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); testCluster.InitClient(); _policyTestTools.CreateSchema(testCluster.Session, 2); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Two); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.Two); string coordinatorHostQueried = _policyTestTools.Coordinators.First().Key.Split(':').First(); int awareCoord = int.Parse(coordinatorHostQueried.Split('.').Last()); int coordinatorsWithMoreThanZeroQueries = 0; foreach (var coordinator in _policyTestTools.Coordinators) { coordinatorsWithMoreThanZeroQueries++; _policyTestTools.AssertQueried(coordinator.Key, 6); } Assert.AreEqual(2, coordinatorsWithMoreThanZeroQueries); _policyTestTools.ResetCoordinators(); testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One }; var failList = new List<ConsistencyLevel> { ConsistencyLevel.Two, ConsistencyLevel.Quorum, ConsistencyLevel.Three, ConsistencyLevel.All }; // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Verify that replication factor three is enforced, /// with load balancing policy TokenAware, RoundRobin /// /// @test_category consistency /// @test_category connection:outage /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorThree_TokenAware() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder().WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())); testCluster.InitClient(); _policyTestTools.CreateSchema(testCluster.Session, 3); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Two); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.Two); string coordinatorUsedIp = _policyTestTools.Coordinators.First().Key.Split(':').First(); int awareCoord = int.Parse(coordinatorUsedIp.Split('.').Last()); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 4); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 4); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 4); _policyTestTools.ResetCoordinators(); testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Quorum }; var failList = new List<ConsistencyLevel> { ConsistencyLevel.Three, ConsistencyLevel.All }; // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Validate client behavior with replication one, three nodes /// load balancing policy TokenAware, RoundRobin, after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorOne_DowngradingConsistencyRetryPolicy() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder() .WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); _policyTestTools.CreateSchema(testCluster.Session, 1); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.One); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.One); string coordinatorHostQueried = _policyTestTools.Coordinators.First().Key.Split(':').First(); int awareCoord = int.Parse(coordinatorHostQueried.Split('.').Last()); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + awareCoord + ":" + DefaultCassandraPort, 12); _policyTestTools.ResetCoordinators(); testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30); var acceptedList = new List<ConsistencyLevel> {ConsistencyLevel.Any}; var failList = new List<ConsistencyLevel> { ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Three, ConsistencyLevel.Quorum, ConsistencyLevel.All }; // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Validate client behavior with replication two, three nodes /// load balancing policy TokenAware, RoundRobin, after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorTwo_DowngradingConsistencyRetryPolicy() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder() .WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); _policyTestTools.CreateSchema(testCluster.Session, 2); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Two); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.Two); string coordinatorHostQueried = _policyTestTools.Coordinators.First().Key.Split(':').First(); ; int awareCoord = int.Parse(coordinatorHostQueried.Split('.').Last()); int coordinatorsWithMoreThanZeroQueries = 0; foreach (var coordinator in _policyTestTools.Coordinators) { coordinatorsWithMoreThanZeroQueries++; _policyTestTools.AssertQueried(coordinator.Key.ToString(), 6); } Assert.AreEqual(2, coordinatorsWithMoreThanZeroQueries); _policyTestTools.ResetCoordinators(); testCluster.StopForce(awareCoord); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + awareCoord, testCluster.Cluster, 30); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Quorum, ConsistencyLevel.Three, ConsistencyLevel.All }; var failList = new List<ConsistencyLevel>(); // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Validate client behavior with replication three, multiple DCs /// load balancing policy TokenAware, RoundRobin, after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin,token_aware /// </summary> [Test] public void ReplicationFactorThree_TwoDCs_DowngradingConsistencyRetryPolicy() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3, 3, DefaultMaxClusterCreateRetries, true); testCluster.Builder = ClusterBuilder() .WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); _policyTestTools.CreateMultiDcSchema(testCluster.Session, 3, 3); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Two); // a maximum of 4 IPs should have returned values for the query -- two copies per each of the two DCs int queriesPerIteration = 4; int queriesCompleted = 0; int actualTries = 0; int maxTries = 20; while (_policyTestTools.Coordinators.Count() < 4 && actualTries < maxTries) { _policyTestTools.Query(testCluster, queriesPerIteration, ConsistencyLevel.Two); queriesCompleted += queriesPerIteration; } Assert.IsTrue(_policyTestTools.Coordinators.Count() >= 4, "The minimum number of hosts queried was not met!"); int totalQueriesForAllHosts = _policyTestTools.Coordinators.Sum(c => c.Value); Assert.AreEqual(queriesCompleted, totalQueriesForAllHosts, "The sum of queries for all hosts should equal the number of queries recorded by the calling test!"); _policyTestTools.ResetCoordinators(); testCluster.StopForce(2); // FIXME: This sleep is needed to allow the waitFor() to work TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 5); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Quorum, ConsistencyLevel.Three, ConsistencyLevel.All, ConsistencyLevel.LocalQuorum, ConsistencyLevel.EachQuorum }; var failList = new List<ConsistencyLevel>(); // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "EACH_QUORUM ConsistencyLevel is only supported for writes", "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail("Expected Exception was not thrown for ConsistencyLevel :" + consistencyLevel); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Validate client behavior with replication three, multiple DCs /// with load balancing policy TokenAware, DCAwareRoundRobin, /// with retry policy DowngradingConsistencyRetryPolicy /// after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin,token_aware,dc_aware /// </summary> public void ReplicationFactorThree_TwoDcs_DcAware_DowngradingConsistencyRetryPolicy() { // Seetup ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3, 3, DefaultMaxClusterCreateRetries, true); testCluster.Builder = ClusterBuilder() .WithLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"))) .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "1", DefaultCassandraPort, 30); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "2", DefaultCassandraPort, 30); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "3", DefaultCassandraPort, 30); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "4", DefaultCassandraPort, 30); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "5", DefaultCassandraPort, 30); TestUtils.WaitForUp(testCluster.ClusterIpPrefix + "6", DefaultCassandraPort, 30); // Test _policyTestTools.CreateMultiDcSchema(testCluster.Session, 3, 3); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Two); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.Two); // Validate expected number of host / query counts _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "1:" + DefaultCassandraPort, 0); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "2:" + DefaultCassandraPort, 0); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "3:" + DefaultCassandraPort, 0); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "4:" + DefaultCassandraPort, 4); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "5:" + DefaultCassandraPort, 4); _policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + "6:" + DefaultCassandraPort, 4); _policyTestTools.ResetCoordinators(); testCluster.StopForce(2); // FIXME: This sleep is needed to allow the waitFor() to work TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 5); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Quorum, ConsistencyLevel.Three, ConsistencyLevel.All, ConsistencyLevel.LocalQuorum, ConsistencyLevel.EachQuorum }; var failList = new List<ConsistencyLevel>(); // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "EACH_QUORUM ConsistencyLevel is only supported for writes", "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } /// <summary> /// Validate client behavior with replication three, only one DC /// with load balancing policy TokenAware, DCAwareRoundRobin, /// with retry policy DowngradingConsistencyRetryPolicy /// after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin /// </summary> public void ReplicationFactorThree_RoundRobin_DowngradingConsistencyRetryPolicy() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder().WithLoadBalancingPolicy(new RoundRobinPolicy()).WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); TestReplicationFactorThree(testCluster); } /// <summary> /// Validate client behavior with replication three, only one DC /// with load balancing policy TokenAware, RoundRobin, /// with retry policy DowngradingConsistencyRetryPolicy /// after a node is taken down /// /// @test_category consistency /// @test_category connection:outage,retry_policy /// @test_category load_balancing:round_robin /// </summary> public void ReplicationFactorThree_TokenAware_DowngradingConsistencyRetryPolicy() { ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3); testCluster.Builder = ClusterBuilder() .WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy())) .WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance); testCluster.InitClient(); TestReplicationFactorThree(testCluster); } ////////////////////////////// /// Test Helpers ////////////////////////////// public void TestReplicationFactorThree(ITestCluster testCluster) { _policyTestTools.CreateSchema(testCluster.Session, 3); _policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.Three); _policyTestTools.Query(testCluster, 12, ConsistencyLevel.Three); _policyTestTools.ResetCoordinators(); testCluster.StopForce(2); TestUtils.WaitForDownWithWait(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 5); var acceptedList = new List<ConsistencyLevel> { ConsistencyLevel.Any, ConsistencyLevel.One, ConsistencyLevel.Two, ConsistencyLevel.Quorum, ConsistencyLevel.Three, ConsistencyLevel.All }; var failList = new List<ConsistencyLevel>(); // Test successful writes foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); } catch (Exception e) { Assert.Fail(string.Format("Test failed at CL.{0} with message: {1}", consistencyLevel, e.Message)); } } // Test successful reads foreach (ConsistencyLevel consistencyLevel in acceptedList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "ANY ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message)); } } // Test writes which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.InitPreparedStatement(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "consistency level EACH_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } catch (WriteTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } } // Test reads which should fail foreach (ConsistencyLevel consistencyLevel in failList) { try { _policyTestTools.Query(testCluster, 12, consistencyLevel); Assert.Fail(string.Format("Test passed at CL.{0}.", consistencyLevel)); } catch (InvalidQueryException e) { var acceptableErrorMessages = new List<string> { "consistency level LOCAL_QUORUM not compatible with replication strategy (org.apache.cassandra.locator.SimpleStrategy)", "EACH_QUORUM ConsistencyLevel is only supported for writes" }; Assert.True(acceptableErrorMessages.Contains(e.Message), string.Format("Received: {0}", e.Message)); } catch (ReadTimeoutException) { // expected to fail when the client hasn't marked the' // node as DOWN yet } catch (UnavailableException) { // expected to fail when the client has already marked the // node as DOWN } } } } }
//--------------------------------------------------------------------------- // // <copyright file="GroupStyle.cs" company="Microsoft"> // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Description of UI for grouping. // // See spec at http://avalon/connecteddata/Specs/Grouping.mht // //--------------------------------------------------------------------------- using System.ComponentModel; // [DefaultValue] using System.Windows.Data; // CollectionViewGroup namespace System.Windows.Controls { /// <summary> /// The GroupStyle describes how to display the items in a GroupCollection, /// such as the collection obtained from CollectionViewGroup.Items. /// </summary> [Localizability(LocalizationCategory.None, Readability = Readability.Unreadable)] // cannot be read & localized as string public class GroupStyle : INotifyPropertyChanged { #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Initializes a new instance of GroupStyle. /// </summary> public GroupStyle() { } static GroupStyle() { ItemsPanelTemplate template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(StackPanel))); template.Seal(); DefaultGroupPanel = template; DefaultStackPanel = template; template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(VirtualizingStackPanel))); template.Seal(); DefaultVirtualizingStackPanel = template; s_DefaultGroupStyle = new GroupStyle(); } #endregion Constructors #region INotifyPropertyChanged /// <summary> /// This event is raised when a property of the group style has changed. /// </summary> event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged { add { PropertyChanged += value; } remove { PropertyChanged -= value; } } /// <summary> /// PropertyChanged event (per <see cref="INotifyPropertyChanged" />). /// </summary> protected virtual event PropertyChangedEventHandler PropertyChanged; /// <summary> /// A subclass can call this method to raise the PropertyChanged event. /// </summary> protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, e); } } #endregion INotifyPropertyChanged #region Public Properties //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// A template that creates the panel used to layout the items. /// </summary> public ItemsPanelTemplate Panel { get { return _panel; } set { _panel = value; OnPropertyChanged("Panel"); } } /// <summary> /// ContainerStyle is the style that is applied to the GroupItem generated /// for each item. /// </summary> [DefaultValue(null)] public Style ContainerStyle { get { return _containerStyle; } set { _containerStyle = value; OnPropertyChanged("ContainerStyle"); } } /// <summary> /// ContainerStyleSelector allows the app writer to provide custom style selection logic /// for a style to apply to each generated GroupItem. /// </summary> [DefaultValue(null)] public StyleSelector ContainerStyleSelector { get { return _containerStyleSelector; } set { _containerStyleSelector = value; OnPropertyChanged("ContainerStyleSelector"); } } /// <summary> /// HeaderTemplate is the template used to display the group header. /// </summary> [DefaultValue(null)] public DataTemplate HeaderTemplate { get { return _headerTemplate; } set { _headerTemplate = value; OnPropertyChanged("HeaderTemplate"); } } /// <summary> /// HeaderTemplateSelector allows the app writer to provide custom selection logic /// for a template used to display the group header. /// </summary> [DefaultValue(null)] public DataTemplateSelector HeaderTemplateSelector { get { return _headerTemplateSelector; } set { _headerTemplateSelector = value; OnPropertyChanged("HeaderTemplateSelector"); } } /// <summary> /// HeaderStringFormat is the format used to display the header content as a string. /// This arises only when no template is available. /// </summary> [DefaultValue(null)] public String HeaderStringFormat { get { return _headerStringFormat; } set { _headerStringFormat = value; OnPropertyChanged("HeaderStringFormat"); } } /// <summary> /// HidesIfEmpty allows the app writer to indicate whether items corresponding /// to empty groups should be displayed. /// </summary> [DefaultValue(false)] public bool HidesIfEmpty { get { return _hidesIfEmpty; } set { _hidesIfEmpty = value; OnPropertyChanged("HidesIfEmpty"); } } /// <summary> /// AlternationCount controls the range of values assigned to the /// ItemsControl.AlternationIndex property on containers generated /// for this level of grouping. [DefaultValue(0)] public int AlternationCount { get { return _alternationCount; } set { _alternationCount = value; _isAlternationCountSet = true; OnPropertyChanged("AlternationCount"); } } /// <summary>The default panel template.</summary> public static readonly ItemsPanelTemplate DefaultGroupPanel; /// <summary>The default GroupStyle.</summary> public static GroupStyle Default { get { return s_DefaultGroupStyle; } } #endregion Public Properties #region Private Properties private void OnPropertyChanged(string propertyName) { OnPropertyChanged(new PropertyChangedEventArgs(propertyName)); } internal bool IsAlternationCountSet { get { return _isAlternationCountSet; } } #endregion Private Properties #region Private Fields //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ ItemsPanelTemplate _panel; Style _containerStyle; StyleSelector _containerStyleSelector; DataTemplate _headerTemplate; DataTemplateSelector _headerTemplateSelector; string _headerStringFormat; bool _hidesIfEmpty; bool _isAlternationCountSet; int _alternationCount; static GroupStyle s_DefaultGroupStyle; /// <summary>The default panel template.</summary> internal static ItemsPanelTemplate DefaultStackPanel; internal static ItemsPanelTemplate DefaultVirtualizingStackPanel; #endregion Private Fields } /// <summary> /// A delegate to select the group style as a function of the /// parent group and its level. /// </summary> public delegate GroupStyle GroupStyleSelector(CollectionViewGroup group, int level); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/rpc/room_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Operations.RPC { public static partial class RoomSvc { static readonly string __ServiceName = "holms.types.operations.rpc.RoomSvc"; static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse> __Marshaller_RoomSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.Rooms.Room> __Marshaller_Room = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.Rooms.Room.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> __Marshaller_RoomSvcCRUDResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.Rooms.RoomIndicator> __Marshaller_RoomIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.Rooms.RoomIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Booking.Indicators.ReservationIndicator> __Marshaller_ReservationIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Booking.Indicators.ReservationIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse> __Marshaller_RoomSvcGetByOccupyingReservationResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest> __Marshaller_RoomSvcOccupancyRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse> __Marshaller_RoomSvcClaimOccupancyResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse> __Marshaller_RoomSvcReleaseOccupancyResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest> __Marshaller_RoomSvcIssueRoomKeyRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse> __Marshaller_RoomSvcIssueRoomKeyResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator> __Marshaller_PropertyIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse> __Marshaller_RoomSvcGetHousekeepingRoomStatusResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse>( grpc::MethodType.Unary, __ServiceName, "All", __Marshaller_Empty, __Marshaller_RoomSvcAllResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> __Method_Create = new grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse>( grpc::MethodType.Unary, __ServiceName, "Create", __Marshaller_Room, __Marshaller_RoomSvcCRUDResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> __Method_Update = new grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse>( grpc::MethodType.Unary, __ServiceName, "Update", __Marshaller_Room, __Marshaller_RoomSvcCRUDResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.Operations.Rooms.Room, global::HOLMS.Types.Primitive.ServerActionConfirmation>( grpc::MethodType.Unary, __ServiceName, "Delete", __Marshaller_Room, __Marshaller_ServerActionConfirmation); static readonly grpc::Method<global::HOLMS.Types.Operations.Rooms.RoomIndicator, global::HOLMS.Types.Operations.Rooms.Room> __Method_GetById = new grpc::Method<global::HOLMS.Types.Operations.Rooms.RoomIndicator, global::HOLMS.Types.Operations.Rooms.Room>( grpc::MethodType.Unary, __ServiceName, "GetById", __Marshaller_RoomIndicator, __Marshaller_Room); static readonly grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse> __Method_GetByOccupyingReservation = new grpc::Method<global::HOLMS.Types.Booking.Indicators.ReservationIndicator, global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse>( grpc::MethodType.Unary, __ServiceName, "GetByOccupyingReservation", __Marshaller_ReservationIndicator, __Marshaller_RoomSvcGetByOccupyingReservationResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse> __Method_ClaimRoomOccupancy = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse>( grpc::MethodType.Unary, __ServiceName, "ClaimRoomOccupancy", __Marshaller_RoomSvcOccupancyRequest, __Marshaller_RoomSvcClaimOccupancyResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse> __Method_ReleaseRoomOccupancy = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse>( grpc::MethodType.Unary, __ServiceName, "ReleaseRoomOccupancy", __Marshaller_RoomSvcOccupancyRequest, __Marshaller_RoomSvcReleaseOccupancyResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse> __Method_IssueRoomKey = new grpc::Method<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest, global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse>( grpc::MethodType.Unary, __ServiceName, "IssueRoomKey", __Marshaller_RoomSvcIssueRoomKeyRequest, __Marshaller_RoomSvcIssueRoomKeyResponse); static readonly grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator, global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse> __Method_GetHousekeepingRoomStatus = new grpc::Method<global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator, global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse>( grpc::MethodType.Unary, __ServiceName, "GetHousekeepingRoomStatus", __Marshaller_PropertyIndicator, __Marshaller_RoomSvcGetHousekeepingRoomStatusResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.RoomSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of RoomSvc</summary> public abstract partial class RoomSvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> Create(global::HOLMS.Types.Operations.Rooms.Room request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> Update(global::HOLMS.Types.Operations.Rooms.Room request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.Operations.Rooms.Room request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.Rooms.Room> GetById(global::HOLMS.Types.Operations.Rooms.RoomIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse> GetByOccupyingReservation(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse> ClaimRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse> ReleaseRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse> IssueRoomKey(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse> GetHousekeepingRoomStatus(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for RoomSvc</summary> public partial class RoomSvcClient : grpc::ClientBase<RoomSvcClient> { /// <summary>Creates a new client for RoomSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public RoomSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for RoomSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public RoomSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected RoomSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected RoomSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return All(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse Create(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse Create(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> CreateAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> CreateAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse Update(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse Update(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> UpdateAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcCRUDResponse> UpdateAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Operations.Rooms.Room request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request); } public virtual global::HOLMS.Types.Operations.Rooms.Room GetById(global::HOLMS.Types.Operations.Rooms.RoomIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.Rooms.Room GetById(global::HOLMS.Types.Operations.Rooms.RoomIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.Rooms.Room> GetByIdAsync(global::HOLMS.Types.Operations.Rooms.RoomIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.Rooms.Room> GetByIdAsync(global::HOLMS.Types.Operations.Rooms.RoomIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse GetByOccupyingReservation(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetByOccupyingReservation(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse GetByOccupyingReservation(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetByOccupyingReservation, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse> GetByOccupyingReservationAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetByOccupyingReservationAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcGetByOccupyingReservationResponse> GetByOccupyingReservationAsync(global::HOLMS.Types.Booking.Indicators.ReservationIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetByOccupyingReservation, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse ClaimRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ClaimRoomOccupancy(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse ClaimRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ClaimRoomOccupancy, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse> ClaimRoomOccupancyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ClaimRoomOccupancyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcClaimOccupancyResponse> ClaimRoomOccupancyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ClaimRoomOccupancy, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse ReleaseRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReleaseRoomOccupancy(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse ReleaseRoomOccupancy(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ReleaseRoomOccupancy, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse> ReleaseRoomOccupancyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ReleaseRoomOccupancyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcReleaseOccupancyResponse> ReleaseRoomOccupancyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcOccupancyRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ReleaseRoomOccupancy, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse IssueRoomKey(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return IssueRoomKey(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse IssueRoomKey(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_IssueRoomKey, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse> IssueRoomKeyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return IssueRoomKeyAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyResponse> IssueRoomKeyAsync(global::HOLMS.Types.Operations.RPC.RoomSvcIssueRoomKeyRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_IssueRoomKey, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse GetHousekeepingRoomStatus(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetHousekeepingRoomStatus(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse GetHousekeepingRoomStatus(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetHousekeepingRoomStatus, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse> GetHousekeepingRoomStatusAsync(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetHousekeepingRoomStatusAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.RoomSvcGetHousekeepingRoomStatusResponse> GetHousekeepingRoomStatusAsync(global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetHousekeepingRoomStatus, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override RoomSvcClient NewInstance(ClientBaseConfiguration configuration) { return new RoomSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(RoomSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_All, serviceImpl.All) .AddMethod(__Method_Create, serviceImpl.Create) .AddMethod(__Method_Update, serviceImpl.Update) .AddMethod(__Method_Delete, serviceImpl.Delete) .AddMethod(__Method_GetById, serviceImpl.GetById) .AddMethod(__Method_GetByOccupyingReservation, serviceImpl.GetByOccupyingReservation) .AddMethod(__Method_ClaimRoomOccupancy, serviceImpl.ClaimRoomOccupancy) .AddMethod(__Method_ReleaseRoomOccupancy, serviceImpl.ReleaseRoomOccupancy) .AddMethod(__Method_IssueRoomKey, serviceImpl.IssueRoomKey) .AddMethod(__Method_GetHousekeepingRoomStatus, serviceImpl.GetHousekeepingRoomStatus).Build(); } } } #endregion
// Copyright (C) 2014 dot42 // // Original filename: Javax.Security.Auth.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Security.Auth { /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/SubjectDomainCombiner /// </java-name> [Dot42.DexImport("javax/security/auth/SubjectDomainCombiner", AccessFlags = 33)] public partial class SubjectDomainCombiner : global::Java.Security.IDomainCombiner /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljavax/security/auth/Subject;)V", AccessFlags = 1)] public SubjectDomainCombiner(global::Javax.Security.Auth.Subject subject) /* MethodBuilder.Create */ { } /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] public virtual global::Javax.Security.Auth.Subject GetSubject() /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns a combination of the two provided <c> ProtectionDomain </c> arrays. Implementers can simply merge the two arrays into one, remove duplicates and perform other optimizations.</para><para></para> /// </summary> /// <returns> /// <para>a single <c> ProtectionDomain </c> array computed from the two provided arrays. </para> /// </returns> /// <java-name> /// combine /// </java-name> [Dot42.DexImport("combine", "([Ljava/security/ProtectionDomain;[Ljava/security/ProtectionDomain;)[Ljava/securi" + "ty/ProtectionDomain;", AccessFlags = 1)] public virtual global::Java.Security.ProtectionDomain[] Combine(global::Java.Security.ProtectionDomain[] current, global::Java.Security.ProtectionDomain[] assigned) /* MethodBuilder.Create */ { return default(global::Java.Security.ProtectionDomain[]); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal SubjectDomainCombiner() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getSubject /// </java-name> public global::Javax.Security.Auth.Subject Subject { [Dot42.DexImport("getSubject", "()Ljavax/security/auth/Subject;", AccessFlags = 1)] get{ return GetSubject(); } } } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/PrivateCredentialPermission /// </java-name> [Dot42.DexImport("javax/security/auth/PrivateCredentialPermission", AccessFlags = 49)] public sealed partial class PrivateCredentialPermission : global::Java.Security.Permission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public PrivateCredentialPermission(string name, string action) /* MethodBuilder.Create */ { } /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] public string[][] GetPrincipals() /* MethodBuilder.Create */ { return default(string[][]); } /// <java-name> /// getCredentialClass /// </java-name> [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] public string GetCredentialClass() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// getActions /// </java-name> [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetActions() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// implies /// </java-name> [Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)] public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PrivateCredentialPermission() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getPrincipals /// </java-name> public string[][] Principals { [Dot42.DexImport("getPrincipals", "()[[Ljava/lang/String;", AccessFlags = 1)] get{ return GetPrincipals(); } } /// <java-name> /// getCredentialClass /// </java-name> public string CredentialClass { [Dot42.DexImport("getCredentialClass", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetCredentialClass(); } } /// <java-name> /// getActions /// </java-name> public string Actions { [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActions(); } } } /// <summary> /// <para>The central class of the <c> javax.security.auth </c> package representing an authenticated user or entity (both referred to as "subject"). IT defines also the static methods that allow code to be run, and do modifications according to the subject's permissions. </para><para>A subject has the following features: <ul><li><para>A set of <c> Principal </c> objects specifying the identities bound to a <c> Subject </c> that distinguish it. </para></li><li><para>Credentials (public and private) such as certificates, keys, or authentication proofs such as tickets </para></li></ul></para> /// </summary> /// <java-name> /// javax/security/auth/Subject /// </java-name> [Dot42.DexImport("javax/security/auth/Subject", AccessFlags = 49)] public sealed partial class Subject : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>The default constructor initializing the sets of public and private credentials and principals with the empty set. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public Subject() /* MethodBuilder.Create */ { } /// <summary> /// <para>The constructor for the subject, setting its public and private credentials and principals according to the arguments.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(ZLjava/util/Set;Ljava/util/Set;Ljava/util/Set;)V", AccessFlags = 1, Signature = "(ZLjava/util/Set<+Ljava/security/Principal;>;Ljava/util/Set<*>;Ljava/util/Set<*>;" + ")V")] public Subject(bool readOnly, global::Java.Util.ISet<global::Java.Security.IPrincipal> subjPrincipals, global::Java.Util.ISet<object> pubCredentials, global::Java.Util.ISet<object> privCredentials) /* MethodBuilder.Create */ { } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;)Ljava/lang/Object;" + "", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedAction;Ljava/security/Acce" + "ssControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedActi" + "on<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedAction<T> privilegedAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAs /// </java-name> [Dot42.DexImport("doAs", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;)Ljava/lan" + "g/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;)TT;")] public static T DoAs<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction) /* MethodBuilder.Create */ { return default(T); } /// <java-name> /// doAsPrivileged /// </java-name> [Dot42.DexImport("doAsPrivileged", "(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExceptionAction;Ljava/secu" + "rity/AccessControlContext;)Ljava/lang/Object;", AccessFlags = 9, Signature = "<T:Ljava/lang/Object;>(Ljavax/security/auth/Subject;Ljava/security/PrivilegedExce" + "ptionAction<TT;>;Ljava/security/AccessControlContext;)TT;")] public static T DoAsPrivileged<T>(global::Javax.Security.Auth.Subject subject, global::Java.Security.IPrivilegedExceptionAction<T> privilegedExceptionAction, global::Java.Security.AccessControlContext accessControlContext) /* MethodBuilder.Create */ { return default(T); } /// <summary> /// <para>Checks two Subjects for equality. More specifically if the principals, public and private credentials are equal, equality for two <c> Subjects </c> is implied.</para><para></para> /// </summary> /// <returns> /// <para><c> true </c> if the specified <c> Subject </c> is equal to this one. </para> /// </returns> /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object obj) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] public global::Java.Util.ISet<global::Java.Security.IPrincipal> GetPrincipals() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<global::Java.Security.IPrincipal>); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal which is a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. Modifications to the returned set of <c> Principal </c> s do not affect this <c> Subject </c> 's set. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> [Dot42.DexImport("getPrincipals", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T::Ljava/security/Principal;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrincipals<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPrivateCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's private credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's private credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> [Dot42.DexImport("getPrivateCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPrivateCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] public global::Java.Util.ISet<object> GetPublicCredentials() /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<object>); } /// <summary> /// <para>Returns this <c> Subject </c> 's public credentials which are a subclass of the <c> Class </c> provided.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's public credentials. Modifications to the returned set of credentials do not affect this <c> Subject </c> 's credentials. </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> [Dot42.DexImport("getPublicCredentials", "(Ljava/lang/Class;)Ljava/util/Set;", AccessFlags = 1, Signature = "<T:Ljava/lang/Object;>(Ljava/lang/Class<TT;>;)Ljava/util/Set<TT;>;")] public global::Java.Util.ISet<T> GetPublicCredentials<T>(global::System.Type c) /* MethodBuilder.Create */ { return default(global::Java.Util.ISet<T>); } /// <summary> /// <para>Returns a hash code of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a hash code of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Prevents from modifications being done to the credentials and Principal sets. After setting it to read-only this <c> Subject </c> can not be made writable again. The destroy method on the credentials still works though. </para> /// </summary> /// <java-name> /// setReadOnly /// </java-name> [Dot42.DexImport("setReadOnly", "()V", AccessFlags = 1)] public void SetReadOnly() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns whether this <c> Subject </c> is read-only or not.</para><para></para> /// </summary> /// <returns> /// <para>whether this <c> Subject </c> is read-only or not. </para> /// </returns> /// <java-name> /// isReadOnly /// </java-name> [Dot42.DexImport("isReadOnly", "()Z", AccessFlags = 1)] public bool IsReadOnly() /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Returns a <c> String </c> representation of this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>a <c> String </c> representation of this <c> Subject </c> . </para> /// </returns> /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Returns the <c> Subject </c> that was last associated with the <c> context </c> provided as argument.</para><para></para> /// </summary> /// <returns> /// <para>the <c> Subject </c> that was last associated with the <c> context </c> provided as argument. </para> /// </returns> /// <java-name> /// getSubject /// </java-name> [Dot42.DexImport("getSubject", "(Ljava/security/AccessControlContext;)Ljavax/security/auth/Subject;", AccessFlags = 9)] public static global::Javax.Security.Auth.Subject GetSubject(global::Java.Security.AccessControlContext context) /* MethodBuilder.Create */ { return default(global::Javax.Security.Auth.Subject); } /// <summary> /// <para>Returns this <c> Subject </c> 's Principal.</para><para></para> /// </summary> /// <returns> /// <para>this <c> Subject </c> 's Principal. </para> /// </returns> /// <java-name> /// getPrincipals /// </java-name> public global::Java.Util.ISet<global::Java.Security.IPrincipal> Principals { [Dot42.DexImport("getPrincipals", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/security/Principal;>;")] get{ return GetPrincipals(); } } /// <summary> /// <para>Returns the private credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPrivateCredentials /// </java-name> public global::Java.Util.ISet<object> PrivateCredentials { [Dot42.DexImport("getPrivateCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPrivateCredentials(); } } /// <summary> /// <para>Returns the public credentials associated with this <c> Subject </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public credentials associated with this <c> Subject </c> . </para> /// </returns> /// <java-name> /// getPublicCredentials /// </java-name> public global::Java.Util.ISet<object> PublicCredentials { [Dot42.DexImport("getPublicCredentials", "()Ljava/util/Set;", AccessFlags = 1, Signature = "()Ljava/util/Set<Ljava/lang/Object;>;")] get{ return GetPublicCredentials(); } } } /// <summary> /// <para>Allows for special treatment of sensitive information, when it comes to destroying or clearing of the data. </para> /// </summary> /// <java-name> /// javax/security/auth/Destroyable /// </java-name> [Dot42.DexImport("javax/security/auth/Destroyable", AccessFlags = 1537)] public partial interface IDestroyable /* scope: __dot42__ */ { /// <summary> /// <para>Erases the sensitive information. Once an object is destroyed any calls to its methods will throw an <c> IllegalStateException </c> . If it does not succeed a DestroyFailedException is thrown.</para><para></para> /// </summary> /// <java-name> /// destroy /// </java-name> [Dot42.DexImport("destroy", "()V", AccessFlags = 1025)] void Destroy() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns <c> true </c> once an object has been safely destroyed.</para><para></para> /// </summary> /// <returns> /// <para>whether the object has been safely destroyed. </para> /// </returns> /// <java-name> /// isDestroyed /// </java-name> [Dot42.DexImport("isDestroyed", "()Z", AccessFlags = 1025)] bool IsDestroyed() /* MethodBuilder.Create */ ; } /// <summary> /// <para>Legacy security code; do not use. </para> /// </summary> /// <java-name> /// javax/security/auth/AuthPermission /// </java-name> [Dot42.DexImport("javax/security/auth/AuthPermission", AccessFlags = 49)] public sealed partial class AuthPermission : global::Java.Security.BasicPermission /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1)] public AuthPermission(string name, string actions) /* MethodBuilder.Create */ { } /// <java-name> /// getActions /// </java-name> [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] public override string GetActions() /* MethodBuilder.Create */ { return default(string); } /// <java-name> /// implies /// </java-name> [Dot42.DexImport("implies", "(Ljava/security/Permission;)Z", AccessFlags = 1)] public override bool Implies(global::Java.Security.Permission permission) /* MethodBuilder.Create */ { return default(bool); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal AuthPermission() /* TypeBuilder.AddDefaultConstructor */ { } /// <java-name> /// getActions /// </java-name> public string Actions { [Dot42.DexImport("getActions", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetActions(); } } } /// <summary> /// <para>Signals that the Destroyable#destroy() method failed. </para> /// </summary> /// <java-name> /// javax/security/auth/DestroyFailedException /// </java-name> [Dot42.DexImport("javax/security/auth/DestroyFailedException", AccessFlags = 33)] public partial class DestroyFailedException : global::System.Exception /* scope: __dot42__ */ { /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> . </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public DestroyFailedException() /* MethodBuilder.Create */ { } /// <summary> /// <para>Creates an exception of type <c> DestroyFailedException </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)] public DestroyFailedException(string message) /* MethodBuilder.Create */ { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Globalization { // // Property Default Description // PositiveSign '+' Character used to indicate positive values. // NegativeSign '-' Character used to indicate negative values. // NumberDecimalSeparator '.' The character used as the decimal separator. // NumberGroupSeparator ',' The character used to separate groups of // digits to the left of the decimal point. // NumberDecimalDigits 2 The default number of decimal places. // NumberGroupSizes 3 The number of digits in each group to the // left of the decimal point. // NaNSymbol "NaN" The string used to represent NaN values. // PositiveInfinitySymbol"Infinity" The string used to represent positive // infinities. // NegativeInfinitySymbol"-Infinity" The string used to represent negative // infinities. // // // // Property Default Description // CurrencyDecimalSeparator '.' The character used as the decimal // separator. // CurrencyGroupSeparator ',' The character used to separate groups // of digits to the left of the decimal // point. // CurrencyDecimalDigits 2 The default number of decimal places. // CurrencyGroupSizes 3 The number of digits in each group to // the left of the decimal point. // CurrencyPositivePattern 0 The format of positive values. // CurrencyNegativePattern 0 The format of negative values. // CurrencySymbol "$" String used as local monetary symbol. // [System.Runtime.InteropServices.ComVisible(true)] sealed public class NumberFormatInfo : IFormatProvider { // invariantInfo is constant irrespective of your current culture. private static volatile NumberFormatInfo invariantInfo; // READTHIS READTHIS READTHIS // This class has an exact mapping onto a native structure defined in COMNumber.cpp // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END. // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets. // READTHIS READTHIS READTHIS internal int[] numberGroupSizes = new int[] { 3 }; internal int[] currencyGroupSizes = new int[] { 3 }; internal int[] percentGroupSizes = new int[] { 3 }; internal String positiveSign = "+"; internal String negativeSign = "-"; internal String numberDecimalSeparator = "."; internal String numberGroupSeparator = ","; internal String currencyGroupSeparator = ","; internal String currencyDecimalSeparator = "."; internal String currencySymbol = "$"; // TODO: CoreFX #846 Restore to the original value "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. internal String nanSymbol = "NaN"; internal String positiveInfinitySymbol = "Infinity"; internal String negativeInfinitySymbol = "-Infinity"; internal String percentDecimalSeparator = "."; internal String percentGroupSeparator = ","; internal String percentSymbol = "%"; internal String perMilleSymbol = "\u2030"; internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; internal int currencyPositivePattern = 0; internal int currencyNegativePattern = 0; internal int numberNegativePattern = 1; internal int percentPositivePattern = 0; internal int percentNegativePattern = 0; internal int percentDecimalDigits = 2; internal bool isReadOnly = false; // Is this NumberFormatInfo for invariant culture? internal bool m_isInvariant = false; public NumberFormatInfo() : this(null) { } static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_String); } if (decSep.Length == 0) { throw new ArgumentException(SR.Argument_EmptyDecString); } Contract.EndContractBlock(); } static private void VerifyGroupSeparator(String groupSep, String propertyName) { if (groupSep == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_String); } Contract.EndContractBlock(); } [System.Security.SecuritySafeCritical] // auto-generated internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). cultureData.GetNFIValues(this); if (cultureData.IsInvariantCulture) { // For invariant culture this.m_isInvariant = true; } } } [Pure] private void VerifyWritable() { if (isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } Contract.EndContractBlock(); } // Returns a default NumberFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static NumberFormatInfo InvariantInfo { get { if (invariantInfo == null) { // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. NumberFormatInfo nfi = new NumberFormatInfo(); nfi.m_isInvariant = true; invariantInfo = ReadOnly(nfi); } return invariantInfo; } } public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) { // Fast case for a regular CultureInfo NumberFormatInfo info; CultureInfo cultureProvider = formatProvider as CultureInfo; if (cultureProvider != null && !cultureProvider.m_isInherited) { info = cultureProvider.numInfo; if (info != null) { return info; } else { return cultureProvider.NumberFormat; } } // Fast case for an NFI; info = formatProvider as NumberFormatInfo; if (info != null) { return info; } if (formatProvider != null) { info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo; if (info != null) { return info; } } return CurrentInfo; } public Object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; return n; } public int CurrencyDecimalDigits { get { return currencyDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "CurrencyDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); currencyDecimalDigits = value; } } public String CurrencyDecimalSeparator { get { return currencyDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "CurrencyDecimalSeparator"); currencyDecimalSeparator = value; } } public bool IsReadOnly { get { return isReadOnly; } } // // Check the values of the groupSize array. // // Every element in the groupSize array should be between 1 and 9 // excpet the last element could be zero. // static internal void CheckGroupSize(String propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) return; throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } else if (groupSize[i] > 9) { throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } } } public int[] CurrencyGroupSizes { get { return ((int[])currencyGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("CurrencyGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("CurrencyGroupSizes", inputSizes); currencyGroupSizes = inputSizes; } } public int[] NumberGroupSizes { get { return ((int[])numberGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("NumberGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("NumberGroupSizes", inputSizes); numberGroupSizes = inputSizes; } } public int[] PercentGroupSizes { get { return ((int[])percentGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("PercentGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("PercentGroupSizes", inputSizes); percentGroupSizes = inputSizes; } } public String CurrencyGroupSeparator { get { return currencyGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "CurrencyGroupSeparator"); currencyGroupSeparator = value; } } public String CurrencySymbol { get { return currencySymbol; } set { if (value == null) { throw new ArgumentNullException("CurrencySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); currencySymbol = value; } } // Returns the current culture's NumberFormatInfo. Used by Parse methods. // public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.m_isInherited) { NumberFormatInfo info = culture.numInfo; if (info != null) { return info; } } return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo))); } } public String NaNSymbol { get { return nanSymbol; } set { if (value == null) { throw new ArgumentNullException("NaNSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); nanSymbol = value; } } public int CurrencyNegativePattern { get { return currencyNegativePattern; } set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( "CurrencyNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 15)); } Contract.EndContractBlock(); VerifyWritable(); currencyNegativePattern = value; } } public int NumberNegativePattern { get { return numberNegativePattern; } set { // // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( "NumberNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 4)); } Contract.EndContractBlock(); VerifyWritable(); numberNegativePattern = value; } } public int PercentPositivePattern { get { return percentPositivePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "PercentPositivePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); percentPositivePattern = value; } } public int PercentNegativePattern { get { return percentNegativePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( "PercentNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 11)); } Contract.EndContractBlock(); VerifyWritable(); percentNegativePattern = value; } } public String NegativeInfinitySymbol { get { return negativeInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("NegativeInfinitySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); negativeInfinitySymbol = value; } } public String NegativeSign { get { return negativeSign; } set { if (value == null) { throw new ArgumentNullException("NegativeSign", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); negativeSign = value; } } public int NumberDecimalDigits { get { return numberDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "NumberDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); numberDecimalDigits = value; } } public String NumberDecimalSeparator { get { return numberDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "NumberDecimalSeparator"); numberDecimalSeparator = value; } } public String NumberGroupSeparator { get { return numberGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "NumberGroupSeparator"); numberGroupSeparator = value; } } public int CurrencyPositivePattern { get { return currencyPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "CurrencyPositivePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); currencyPositivePattern = value; } } public String PositiveInfinitySymbol { get { return positiveInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("PositiveInfinitySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); positiveInfinitySymbol = value; } } public String PositiveSign { get { return positiveSign; } set { if (value == null) { throw new ArgumentNullException("PositiveSign", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); positiveSign = value; } } public int PercentDecimalDigits { get { return percentDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "PercentDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); percentDecimalDigits = value; } } public String PercentDecimalSeparator { get { return percentDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "PercentDecimalSeparator"); percentDecimalSeparator = value; } } public String PercentGroupSeparator { get { return percentGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "PercentGroupSeparator"); percentGroupSeparator = value; } } public String PercentSymbol { get { return percentSymbol; } set { if (value == null) { throw new ArgumentNullException("PercentSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); percentSymbol = value; } } public String PerMilleSymbol { get { return perMilleSymbol; } set { if (value == null) { throw new ArgumentNullException("PerMilleSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); perMilleSymbol = value; } } public Object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo) ? this : null; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException("nfi"); } Contract.EndContractBlock(); if (nfi.IsReadOnly) { return (nfi); } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info.isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { throw new ArgumentException(SR.Arg_InvalidHexStyle); } } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number throw new ArgumentException(SR.Arg_HexStyleNotSupported); } } } // NumberFormatInfo }
// Generated by UblXml2CSharp using System.Xml; using UblLarsen.Ubl2; using UblLarsen.Ubl2.Cac; using UblLarsen.Ubl2.Ext; using UblLarsen.Ubl2.Udt; namespace UblLarsen.Test.UblClass { internal class UBLInventoryReport21Example { public static InventoryReportType Create() { var doc = new InventoryReportType { UBLVersionID = "2.1", ID = "CC2679", CopyIndicator = false, IssueDate = "2010-04-12", Note = new TextType[] { new TextType { Value = "Report about the quantities on stock." } }, DocumentCurrencyCode = new CodeType { listID = "ISO 4217 Alpha", Value = "EUR" }, InventoryPeriod = new PeriodType { StartDate = "2010-04-11", StartTime = "14:00:00", EndDate = "2010-04-11" }, RetailerCustomerParty = new CustomerPartyType { Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Beta Shop" } }, PostalAddress = new AddressType { StreetName = "Via Emilia", BuildingNumber = "1", CityName = "Modena", PostalZone = "41121", Country = new CountryType { IdentificationCode = "IT", Name = "Italy" } }, Contact = new ContactType { Name = "Mr Delta", Telephone = "0039 059 33000000", Telefax = "0039 059 33000055", ElectronicMail = "delta@betashop.it" } } }, InventoryReportingParty = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Arancio Forniture spa" } }, PostalAddress = new AddressType { StreetName = "Via Dell'Arcoveggio", BuildingNumber = "405", Department = "Sales and Planning Department", CityName = "Bologna", PostalZone = "40129", Country = new CountryType { IdentificationCode = "IT", Name = "Italy" } }, Contact = new ContactType { Name = "Mr Bianchi", Telephone = "0039 051 23000008", Telefax = "0039 051 23000025", ElectronicMail = "bianchi@arancioforniture.it" } }, SellerSupplierParty = new SupplierPartyType { Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Arancio Forniture spa" } }, PostalAddress = new AddressType { StreetName = "Via Dell'Arcoveggio", BuildingNumber = "403", CityName = "Bologna", PostalZone = "40129", Country = new CountryType { IdentificationCode = "IT", Name = "Italy" } }, Contact = new ContactType { Name = "Mr Rossi", Telephone = "0039 051 23000000", Telefax = "0039 051 23000023", ElectronicMail = "rossi@arancioforniture.it" } } }, InventoryReportLine = new InventoryReportLineType[] { new InventoryReportLineType { ID = "1", Quantity = new QuantityType { unitCode = "NAR", Value = 10M }, InventoryValueAmount = new AmountType { currencyID = "EUR", Value = 200M }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "shirt" } }, BuyersItemIdentification = new ItemIdentificationType { ID = "SH009" }, SellersItemIdentification = new ItemIdentificationType { ID = "DD88" } } }, new InventoryReportLineType { ID = "2", Quantity = new QuantityType { unitCode = "NAR", Value = 15M }, InventoryValueAmount = new AmountType { currencyID = "EUR", Value = 750M }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "trousers" } }, BuyersItemIdentification = new ItemIdentificationType { ID = "TH009" }, SellersItemIdentification = new ItemIdentificationType { ID = "DA008" } } }, new InventoryReportLineType { ID = "3", Quantity = new QuantityType { unitCode = "NAR", Value = 5M }, InventoryValueAmount = new AmountType { currencyID = "EUR", Value = 300M }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "woman's dress" } }, BuyersItemIdentification = new ItemIdentificationType { ID = "DH019" }, SellersItemIdentification = new ItemIdentificationType { ID = "BA058" } } } } }; doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[] { new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"), new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"), }); return doc; } } }
// Copyright 2012 Jacob Trimble // // 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.IO; using System.Text; #nullable enable namespace ModMaker.Lua { /// <summary> /// Defines which libraries the Lua code will have access to. Use Bitwise-Or to use multiple. /// </summary> [Flags] public enum LuaLibraries : byte { /// <summary> /// Use none of the libraries. /// </summary> None = 0, /// <summary> /// Register the standard library to Lua. /// </summary> Standard = 1 << 0, /// <summary> /// Register the string library to Lua. /// </summary> String = 1 << 1, /// <summary> /// Register the table library to Lua. /// </summary> Table = 1 << 2, /// <summary> /// Register the math library to Lua. /// </summary> Math = 1 << 3, /// <summary> /// Register the io library to Lua. /// </summary> IO = 1 << 4, /// <summary> /// Register the os library to Lua. /// </summary> OS = 1 << 5, /// <summary> /// Register the coroutine library to Lua. /// </summary> Coroutine = 1 << 6, /// <summary> /// Register the module library to Lua. /// </summary> Modules = 1 << 7, /// <summary> /// Register all the libraries to Lua. /// </summary> All = 255, } /// <summary> /// Defines what types Lua has access to when defining a new type. /// </summary> public enum LuaClassAccess { /// <summary> /// Lua can only derive from types that are registered. /// </summary> Registered, /// <summary> /// Lua can derive from types that are registered and defined in the /// .NET framework. /// </summary> System, /// <summary> /// Lua can derive from any type that is defined in /// CurrentDomain.GetAssemblies(). /// </summary> All, } /// <summary> /// The event args for an exit event. /// </summary> public sealed class ExitEventArgs : EventArgs { /// <summary> /// Gets the exit code given to os.exit(code[, close]). /// </summary> public int Code { get; private set; } internal ExitEventArgs(object code) { if (code != null) { if (code as bool? == true) { Code = 0; } else if (code is double d) { Code = (int)Math.Round(d); } else { Code = 1; } } else { Code = 0; } } } /// <summary> /// Defines the settings for a Lua object. /// </summary> public sealed class LuaSettings { EventHandler<ExitEventArgs>? _onquit; LuaClassAccess _access; LuaLibraries _libs; Encoding? _enc; Stream? _in; Stream? _out; bool _native_symbols; readonly bool _readonly; /// <summary> /// Creates a new instance of LuaSettings with the default values. Note this doesn't set /// standard in/out, this may cause problems with print and io libraries. See /// Console.OpenStandard*. /// </summary> public LuaSettings() : this(null, null) { } /// <summary> /// Creates a new instance of LuaSettings with the default values that uses the given streams /// for input. /// </summary> /// <param name="stdin">The standard input stream.</param> /// <param name="stdout">The standard output stream.</param> public LuaSettings(Stream? stdin, Stream? stdout) { _readonly = false; _onquit = null; _libs = LuaLibraries.All; _access = LuaClassAccess.Registered; _in = stdin; _out = stdout; #if DEBUG _native_symbols = true; #else _native_symbols = false; #endif } /// <summary> /// Creates a read-only copy of the given settings. /// </summary> /// <param name="copy">The settings to copy.</param> LuaSettings(LuaSettings copy) { _readonly = true; _onquit = copy._onquit; _libs = copy._libs; _access = _checkAccess(copy._access); _enc = copy._enc; _in = copy._in; _out = copy._out; _native_symbols = copy._native_symbols; } /// <summary> /// Creates a new copy of the current settings as a read-only version. /// </summary> /// <returns>A new copy of the current LuaSettings.</returns> public LuaSettings AsReadOnly() { return new LuaSettings(this); } /// <summary> /// Gets or sets the libraries that the Lua code has access too. The library must have /// Permission to access these and will throw PermissionExceptions if it does not, when the code /// is run. If null, use the defaults, which is all of them. /// </summary> public LuaLibraries Libraries { get { return _libs; } set { _checkReadonly(); _libs = value; } } /// <summary> /// Gets or sets which types Lua defined classes can derive from. /// </summary> public LuaClassAccess ClassAccess { get { return _access; } set { _checkReadonly(); _access = value; } } /// <summary> /// Gets or sets the encoding to use for reading/writing to a file. If null, will use UTF8. /// When reading, will try to read using the file encoding. /// </summary> public Encoding? Encoding { get { return _enc; } set { _checkReadonly(); _enc = value; } } /// <summary> /// If true, the generated code will include native debugging symbols. This can allow debugging /// Lua code in Visual Studio. This does NOT affect the Lua "debug" library. /// </summary> public bool AddNativeDebugSymbols { get { return _native_symbols; } set { _checkReadonly(); _native_symbols = value; } } /// <summary> /// Raised when the Lua code calls os.close. The sender is the Environment that the code is in. /// If e.Close is true after raising, it will call Environment.Exit. /// </summary> public event EventHandler<ExitEventArgs> Quit { add { _checkReadonly(); _onquit += value; } remove { _checkReadonly(); _onquit -= value; } } /// <summary> /// Gets or sets the stream to get stdin from. /// </summary> public Stream? Stdin { get { return _in; } set { _checkReadonly(); _in = value; } } /// <summary> /// Gets or sets the stream to send stdout to. /// </summary> public Stream? Stdout { get { return _out; } set { _checkReadonly(); _out = value; } } /// <summary> /// Raises the Quit event. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="code">The value to use for the code.</param> /// <param name="close">Whether to call Environment.Exit.</param> internal void _callQuit(object sender, object code, object close) { ExitEventArgs e = new ExitEventArgs(code); if (sender != null && _onquit != null) { _onquit(sender, e); //if (e.Close) { // Environment.Exit(e.Code); //} } } /// <summary> /// Checks whether the settings is read-only and throws an exception if it is. /// </summary> void _checkReadonly() { if (_readonly) { throw new InvalidOperationException(Resources.ReadonlySettings); } } /// <summary> /// Ensures that the LuaClassAccess is really one of the enumerated values. If it is invalid, it /// will use the default (Registered). /// </summary> /// <param name="access">The value to check.</param> /// <returns>A valid LuaClassAccess choice.</returns> static LuaClassAccess _checkAccess(LuaClassAccess access) { switch (access) { case LuaClassAccess.System: return LuaClassAccess.System; case LuaClassAccess.All: return LuaClassAccess.All; default: return LuaClassAccess.Registered; } } } }
#region License /* Copyright 2012 James F. Bellinger <http://www.zer7.com/software/hidsharp> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; using System.Text; namespace HidSharp.Platform.Libusb { static class NativeMethods { const string Libusb = "libusb-1.0.so.0"; public struct DeviceDescriptor { public byte bLength, bDescriptorType; public ushort bcdUSB; public byte bDeviceClass, bDeviceSubClass, bDeviceProtocol, bMaxPacketSize0; public ushort idVendor, idProduct, bcdDevice; public byte iManufacturer, iProduct, iSerialNumber, bNumConfigurations; } public enum DeviceClass : byte { HID = 0x03, MassStorage = 0x08, VendorSpecific = 0xff } public enum DescriptorType : byte { Device = 0x01, Configuration = 0x02, String = 0x03, Interface = 0x04, Endpoint = 0x05, HID = 0x21, Report = 0x22, Physical = 0x23, Hub = 0x29 } public enum EndpointDirection : byte { In = 0x80, Out = 0, } public enum Request : byte { GetDescriptor = 0x06 } public enum RequestRecipient : byte { Device = 0, Interface = 1, Endpoint = 2, Other = 3 } public enum RequestType : byte { Standard = 0x00, Class = 0x20, Vendor = 0x40 } public enum TransferType : byte { Control = 0, Isochronous, Bulk, Interrupt } public struct Version { public ushort Major, Minor, Micro, Nano; } public enum Error { None = 0, IO = -1, InvalidParameter = -2, AccessDenied = -3, NoDevice = -4, NotFound = -5, Busy = -6, Timeout = -7, Overflow = -8, Pipe = -9, Interrupted = -10, OutOfMemory = -11, NotSupported = -12 } [DllImport(Libusb)] public static extern Error libusb_init(out IntPtr context); [DllImport(Libusb)] public static extern void libusb_set_debug(IntPtr context, int level); [DllImport(Libusb)] public static extern void libusb_exit(IntPtr context); [DllImport(Libusb)] public static extern IntPtr libusb_get_device_list(IntPtr context, out IntPtr list); [DllImport(Libusb)] public static extern void libusb_free_device_list(IntPtr context, IntPtr list); [DllImport(Libusb)] public static extern IntPtr libusb_ref_device(IntPtr device); [DllImport(Libusb)] public static extern void libusb_unref_device(IntPtr device); [DllImport(Libusb)] public static extern int libusb_get_max_packet_size(IntPtr device, byte endpoint); [DllImport(Libusb)] public static extern Error libusb_open(IntPtr device, out IntPtr deviceHandle); [DllImport(Libusb)] public static extern void libusb_close(IntPtr deviceHandle); [DllImport(Libusb)] public static extern Error libusb_get_configuration(IntPtr deviceHandle, out int configuration); [DllImport(Libusb)] public static extern Error libusb_set_configuration(IntPtr deviceHandle, int configuration); [DllImport(Libusb)] public static extern Error libusb_claim_interface(IntPtr deviceHandle, int @interface); [DllImport(Libusb)] public static extern Error libusb_release_interface(IntPtr deviceHandle, int @interface); [DllImport(Libusb)] public static extern Error libusb_set_interface_alt_setting(IntPtr deviceHandle, int @interface, int altSetting); [DllImport(Libusb)] public static extern Error libusb_clear_halt(IntPtr deviceHandle, byte endpoint); [DllImport(Libusb)] public static extern Error libusb_reset_device(IntPtr deviceHandle); [DllImport(Libusb)] public static extern Error libusb_kernel_driver_active(IntPtr deviceHandle, int @interface); [DllImport(Libusb)] public static extern Error libusb_detach_kernel_driver(IntPtr deviceHandle, int @interface); [DllImport(Libusb)] public static extern Error libusb_attach_kernel_driver(IntPtr deviceHandle, int @interface); [DllImport(Libusb)] public static extern IntPtr libusb_get_version(); [DllImport(Libusb)] public static extern Error libusb_get_device_descriptor(IntPtr device, out DeviceDescriptor descriptor); [DllImport(Libusb)] public static extern Error libusb_get_active_config_descriptor(IntPtr device, out IntPtr configuration); [DllImport(Libusb)] public static extern Error libusb_get_config_descriptor_by_value(IntPtr device, byte index, out IntPtr configuration); [DllImport(Libusb)] public static extern void libusb_free_config_descriptor(IntPtr configuration); static Error libusb_get_descriptor_core(IntPtr deviceHandle, DescriptorType type, byte index, byte[] data, ushort wLength, ushort wIndex) { return libusb_control_transfer(deviceHandle, (byte)EndpointDirection.In, (byte)Request.GetDescriptor, (ushort)((byte)DescriptorType.String << 8 | index), wIndex, data, wLength, 1000); } public static Error libusb_get_descriptor(IntPtr deviceHandle, DescriptorType type, byte index, byte[] data, ushort wLength) { return libusb_get_descriptor_core(deviceHandle, type, index, data, wLength, 0); } public static Error libusb_get_string_descriptor(IntPtr deviceHandle, DescriptorType type, byte index, ushort languageID, byte[] data, ushort wLength) { return libusb_get_descriptor_core(deviceHandle, DescriptorType.String, index, data, wLength, languageID); } [DllImport(Libusb)] public static extern Error libusb_control_transfer(IntPtr deviceHandle, byte bmRequestType, byte bRequest, ushort wValue, ushort wIndex, byte[] data, ushort wLength, uint timeout); [DllImport(Libusb)] public static extern Error libusb_bulk_transfer(IntPtr deviceHandle, byte endpoint, byte[] data, int length, out int transferred, uint timeout); [DllImport(Libusb)] public static extern Error libusb_interrupt_transfer(IntPtr deviceHandle, byte endpoint, byte[] data, int length, out int transferred, uint timeout); } }
//--------------------------------------------------------------------------- // // <copyright file="ByteAnimationUsingKeyFrames.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Markup; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; namespace System.Windows.Media.Animation { /// <summary> /// This class is used to animate a Byte property value along a set /// of key frames. /// </summary> [ContentProperty("KeyFrames")] public class ByteAnimationUsingKeyFrames : ByteAnimationBase, IKeyFrameAnimation, IAddChild { #region Data private ByteKeyFrameCollection _keyFrames; private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames; private bool _areKeyTimesValid; #endregion #region Constructors /// <Summary> /// Creates a new KeyFrameByteAnimation. /// </Summary> public ByteAnimationUsingKeyFrames() : base() { _areKeyTimesValid = true; } #endregion #region Freezable /// <summary> /// Creates a copy of this KeyFrameByteAnimation. /// </summary> /// <returns>The copy</returns> public new ByteAnimationUsingKeyFrames Clone() { return (ByteAnimationUsingKeyFrames)base.Clone(); } /// <summary> /// Returns a version of this class with all its base property values /// set to the current animated values and removes the animations. /// </summary> /// <returns> /// Since this class isn't animated, this method will always just return /// this instance of the class. /// </returns> public new ByteAnimationUsingKeyFrames CloneCurrentValue() { return (ByteAnimationUsingKeyFrames)base.CloneCurrentValue(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); canFreeze &= Freezable.Freeze(_keyFrames, isChecking); if (canFreeze & !_areKeyTimesValid) { ResolveKeyTimes(); } return canFreeze; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>. /// </summary> protected override void OnChanged() { _areKeyTimesValid = false; base.OnChanged(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new ByteAnimationUsingKeyFrames(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable source) { ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source; base.GetAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source; base.GetCurrentValueAsFrozenCore(source); CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true); } /// <summary> /// Helper used by the four Freezable clone methods to copy the resolved key times and /// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core /// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here. /// </summary> /// <param name="sourceAnimation"></param> /// <param name="isCurrentValueClone"></param> private void CopyCommon(ByteAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone) { _areKeyTimesValid = sourceAnimation._areKeyTimesValid; if ( _areKeyTimesValid && sourceAnimation._sortedResolvedKeyFrames != null) { // _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply _sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone(); } if (sourceAnimation._keyFrames != null) { if (isCurrentValueClone) { _keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue(); } else { _keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.Clone(); } OnFreezablePropertyChanged(null, _keyFrames); } } #endregion // Freezable #region IAddChild interface /// <summary> /// Adds a child object to this KeyFrameAnimation. /// </summary> /// <param name="child"> /// The child object to add. /// </param> /// <remarks> /// A KeyFrameAnimation only accepts a KeyFrame of the proper type as /// a child. /// </remarks> void IAddChild.AddChild(object child) { WritePreamble(); if (child == null) { throw new ArgumentNullException("child"); } AddChild(child); WritePostscript(); } /// <summary> /// Implemented to allow KeyFrames to be direct children /// of KeyFrameAnimations in markup. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddChild(object child) { ByteKeyFrame keyFrame = child as ByteKeyFrame; if (keyFrame != null) { KeyFrames.Add(keyFrame); } else { throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child"); } } /// <summary> /// Adds a text string as a child of this KeyFrameAnimation. /// </summary> /// <param name="childText"> /// The text to add. /// </param> /// <remarks> /// A KeyFrameAnimation does not accept text as a child, so this method will /// raise an InvalididOperationException unless a derived class has /// overridden the behavior to add text. /// </remarks> /// <exception cref="ArgumentNullException">The childText parameter is /// null.</exception> void IAddChild.AddText(string childText) { if (childText == null) { throw new ArgumentNullException("childText"); } AddText(childText); } /// <summary> /// This method performs the core functionality of the AddText() /// method on the IAddChild interface. For a KeyFrameAnimation this means /// throwing and InvalidOperationException because it doesn't /// support adding text. /// </summary> /// <remarks> /// This method is the only core implementation. It does not call /// WritePreamble() or WritePostscript(). It also doesn't throw an /// ArgumentNullException if the childText parameter is null. These tasks /// are performed by the interface implementation. Therefore, it's OK /// for a derived class to override this method and call the base /// class implementation only if they determine that it's the right /// course of action. The derived class can rely on KeyFrameAnimation's /// implementation of IAddChild.AddChild or implement their own /// following the Freezable pattern since that would be a public /// method. /// </remarks> /// <param name="childText">A string representing the child text that /// should be added. If this is a KeyFrameAnimation an exception will be /// thrown.</param> /// <exception cref="InvalidOperationException">Timelines have no way /// of adding text.</exception> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void AddText(string childText) { throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren)); } #endregion #region ByteAnimationBase /// <summary> /// Calculates the value this animation believes should be the current value for the property. /// </summary> /// <param name="defaultOriginValue"> /// This value is the suggested origin value provided to the animation /// to be used if the animation does not have its own concept of a /// start value. If this animation is the first in a composition chain /// this value will be the snapshot value if one is available or the /// base property value if it is not; otherise this value will be the /// value returned by the previous animation in the chain with an /// animationClock that is not Stopped. /// </param> /// <param name="defaultDestinationValue"> /// This value is the suggested destination value provided to the animation /// to be used if the animation does not have its own concept of an /// end value. This value will be the base value if the animation is /// in the first composition layer of animations on a property; /// otherwise this value will be the output value from the previous /// composition layer of animations for the property. /// </param> /// <param name="animationClock"> /// This is the animationClock which can generate the CurrentTime or /// CurrentProgress value to be used by the animation to generate its /// output value. /// </param> /// <returns> /// The value this animation believes should be the current value for the property. /// </returns> protected sealed override Byte GetCurrentValueCore( Byte defaultOriginValue, Byte defaultDestinationValue, AnimationClock animationClock) { Debug.Assert(animationClock.CurrentState != ClockState.Stopped); if (_keyFrames == null) { return defaultDestinationValue; } // We resolved our KeyTimes when we froze, but also got notified // of the frozen state and therefore invalidated ourselves. if (!_areKeyTimesValid) { ResolveKeyTimes(); } if (_sortedResolvedKeyFrames == null) { return defaultDestinationValue; } TimeSpan currentTime = animationClock.CurrentTime.Value; Int32 keyFrameCount = _sortedResolvedKeyFrames.Length; Int32 maxKeyFrameIndex = keyFrameCount - 1; Byte currentIterationValue; Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames."); Int32 currentResolvedKeyFrameIndex = 0; // Skip all the key frames with key times lower than the current time. // currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex // if we are past the last key frame. while ( currentResolvedKeyFrameIndex < keyFrameCount && currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } // If there are multiple key frames at the same key time, be sure to go to the last one. while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex && currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime) { currentResolvedKeyFrameIndex++; } if (currentResolvedKeyFrameIndex == keyFrameCount) { // Past the last key frame. currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex); } else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime) { // Exactly on a key frame. currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex); } else { // Between two key frames. Double currentSegmentProgress = 0.0; Byte fromValue; if (currentResolvedKeyFrameIndex == 0) { // The current key frame is the first key frame so we have // some special rules for determining the fromValue and an // optimized method of calculating the currentSegmentProgress. // If we're additive we want the base value to be a zero value // so that if there isn't a key frame at time 0.0, we'll use // the zero value for the time 0.0 value and then add that // later to the base value. if (IsAdditive) { fromValue = AnimatedTypeHelpers.GetZeroValueByte(defaultOriginValue); } else { fromValue = defaultOriginValue; } // Current segment time divided by the segment duration. // Note: the reason this works is that we know that we're in // the first segment, so we can assume: // // currentTime.TotalMilliseconds = current segment time // _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration currentSegmentProgress = currentTime.TotalMilliseconds / _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds; } else { Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1; TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime; fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex); TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime; TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime; currentSegmentProgress = segmentCurrentTime.TotalMilliseconds / segmentDuration.TotalMilliseconds; } currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress); } // If we're cumulative, we need to multiply the final key frame // value by the current repeat count and add this to the return // value. if (IsCumulative) { Double currentRepeat = (Double)(animationClock.CurrentIteration - 1); if (currentRepeat > 0.0) { currentIterationValue = AnimatedTypeHelpers.AddByte( currentIterationValue, AnimatedTypeHelpers.ScaleByte(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat)); } } // If we're additive we need to add the base value to the return value. if (IsAdditive) { return AnimatedTypeHelpers.AddByte(defaultOriginValue, currentIterationValue); } return currentIterationValue; } /// <summary> /// Provide a custom natural Duration when the Duration property is set to Automatic. /// </summary> /// <param name="clock"> /// The Clock whose natural duration is desired. /// </param> /// <returns> /// If the last KeyFrame of this animation is a KeyTime, then this will /// be used as the NaturalDuration; otherwise it will be one second. /// </returns> protected override sealed Duration GetNaturalDurationCore(Clock clock) { return new Duration(LargestTimeSpanKeyTime); } #endregion #region IKeyFrameAnimation /// <summary> /// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation. /// </summary> IList IKeyFrameAnimation.KeyFrames { get { return KeyFrames; } set { KeyFrames = (ByteKeyFrameCollection)value; } } /// <summary> /// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation. /// </summary> public ByteKeyFrameCollection KeyFrames { get { ReadPreamble(); // The reason we don't just set _keyFrames to the empty collection // in the first place is that null tells us that the user has not // asked for the collection yet. The first time they ask for the // collection and we're unfrozen, policy dictates that we give // them a new unfrozen collection. All subsequent times they will // get whatever collection is present, whether frozen or unfrozen. if (_keyFrames == null) { if (this.IsFrozen) { _keyFrames = ByteKeyFrameCollection.Empty; } else { WritePreamble(); _keyFrames = new ByteKeyFrameCollection(); OnFreezablePropertyChanged(null, _keyFrames); WritePostscript(); } } return _keyFrames; } set { if (value == null) { throw new ArgumentNullException("value"); } WritePreamble(); if (value != _keyFrames) { OnFreezablePropertyChanged(_keyFrames, value); _keyFrames = value; WritePostscript(); } } } /// <summary> /// Returns true if we should serialize the KeyFrames, property for this Animation. /// </summary> /// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns> [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeKeyFrames() { ReadPreamble(); return _keyFrames != null && _keyFrames.Count > 0; } #endregion #region Public Properties /// <summary> /// If this property is set to true, this animation will add its value /// to the base value or the value of the previous animation in the /// composition chain. Another way of saying this is that the units /// specified in the animation are relative to the base value rather /// than absolute units. /// </summary> /// <remarks> /// In the case where the first key frame's resolved key time is not /// 0.0 there is slightly different behavior between KeyFrameByteAnimations /// with IsAdditive set and without. Animations with the property set to false /// will behave as if there is a key frame at time 0.0 with the value of the /// base value. Animations with the property set to true will behave as if /// there is a key frame at time 0.0 with a zero value appropriate to the type /// of the animation. These behaviors provide the results most commonly expected /// and can be overridden by simply adding a key frame at time 0.0 with the preferred value. /// </remarks> public bool IsAdditive { get { return (bool)GetValue(IsAdditiveProperty); } set { SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value)); } } /// <summary> /// If this property is set to true, the value of this animation will /// accumulate over repeat cycles. For example, if this is a point /// animation and your key frames describe something approximating and /// arc, setting this property to true will result in an animation that /// would appear to bounce the point across the screen. /// </summary> /// <remarks> /// This property works along with the IsAdditive property. Setting /// this value to true has no effect unless IsAdditive is also set /// to true. /// </remarks> public bool IsCumulative { get { return (bool)GetValue(IsCumulativeProperty); } set { SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value)); } } #endregion #region Private Methods private struct KeyTimeBlock { public int BeginIndex; public int EndIndex; } private Byte GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue"); return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value; } private ByteKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex) { Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame"); return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex]; } /// <summary> /// Returns the largest time span specified key time from all of the key frames. /// If there are not time span key times a time span of one second is returned /// to match the default natural duration of the From/To/By animations. /// </summary> private TimeSpan LargestTimeSpanKeyTime { get { bool hasTimeSpanKeyTime = false; TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero; if (_keyFrames != null) { Int32 keyFrameCount = _keyFrames.Count; for (int index = 0; index < keyFrameCount; index++) { KeyTime keyTime = _keyFrames[index].KeyTime; if (keyTime.Type == KeyTimeType.TimeSpan) { hasTimeSpanKeyTime = true; if (keyTime.TimeSpan > largestTimeSpanKeyTime) { largestTimeSpanKeyTime = keyTime.TimeSpan; } } } } if (hasTimeSpanKeyTime) { return largestTimeSpanKeyTime; } else { return TimeSpan.FromSeconds(1.0); } } } private void ResolveKeyTimes() { Debug.Assert(!_areKeyTimesValid, "KeyFrameByteAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid."); int keyFrameCount = 0; if (_keyFrames != null) { keyFrameCount = _keyFrames.Count; } if (keyFrameCount == 0) { _sortedResolvedKeyFrames = null; _areKeyTimesValid = true; return; } _sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount]; int index = 0; // Initialize the _originalKeyFrameIndex. for ( ; index < keyFrameCount; index++) { _sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index; } // calculationDuration represents the time span we will use to resolve // percent key times. This is defined as the value in the following // precedence order: // 1. The animation's duration, but only if it is a time span, not auto or forever. // 2. The largest time span specified key time of all the key frames. // 3. 1 second, to match the From/To/By animations. TimeSpan calculationDuration = TimeSpan.Zero; Duration duration = Duration; if (duration.HasTimeSpan) { calculationDuration = duration.TimeSpan; } else { calculationDuration = LargestTimeSpanKeyTime; } int maxKeyFrameIndex = keyFrameCount - 1; ArrayList unspecifiedBlocks = new ArrayList(); bool hasPacedKeyTimes = false; // // Pass 1: Resolve Percent and Time key times. // index = 0; while (index < keyFrameCount) { KeyTime keyTime = _keyFrames[index].KeyTime; switch (keyTime.Type) { case KeyTimeType.Percent: _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds( keyTime.Percent * calculationDuration.TotalMilliseconds); index++; break; case KeyTimeType.TimeSpan: _sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan; index++; break; case KeyTimeType.Paced: case KeyTimeType.Uniform: if (index == maxKeyFrameIndex) { // If the last key frame doesn't have a specific time // associated with it its resolved key time will be // set to the calculationDuration, which is the // defined in the comments above where it is set. // Reason: We only want extra time at the end of the // key frames if the user specifically states that // the last key frame ends before the animation ends. _sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration; index++; } else if ( index == 0 && keyTime.Type == KeyTimeType.Paced) { // Note: It's important that this block come after // the previous if block because of rule precendence. // If the first key frame in a multi-frame key frame // collection is paced, we set its resolved key time // to 0.0 for performance reasons. If we didn't, the // resolved key time list would be dependent on the // base value which can change every animation frame // in many cases. _sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero; index++; } else { if (keyTime.Type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } KeyTimeBlock block = new KeyTimeBlock(); block.BeginIndex = index; // NOTE: We don't want to go all the way up to the // last frame because if it is Uniform or Paced its // resolved key time will be set to the calculation // duration using the logic above. // // This is why the logic is: // ((++index) < maxKeyFrameIndex) // instead of: // ((++index) < keyFrameCount) while ((++index) < maxKeyFrameIndex) { KeyTimeType type = _keyFrames[index].KeyTime.Type; if ( type == KeyTimeType.Percent || type == KeyTimeType.TimeSpan) { break; } else if (type == KeyTimeType.Paced) { hasPacedKeyTimes = true; } } Debug.Assert(index < keyFrameCount, "The end index for a block of unspecified key frames is out of bounds."); block.EndIndex = index; unspecifiedBlocks.Add(block); } break; } } // // Pass 2: Resolve Uniform key times. // for (int j = 0; j < unspecifiedBlocks.Count; j++) { KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j]; TimeSpan blockBeginTime = TimeSpan.Zero; if (block.BeginIndex > 0) { blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime; } // The number of segments is equal to the number of key // frames we're working on plus 1. Think about the case // where we're working on a single key frame. There's a // segment before it and a segment after it. // // Time known Uniform Time known // ^ ^ ^ // | | | // | (segment 1) | (segment 2) | Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1; TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount); index = block.BeginIndex; TimeSpan resolvedTime = blockBeginTime + uniformTimeStep; while (index < block.EndIndex) { _sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime; resolvedTime += uniformTimeStep; index++; } } // // Pass 3: Resolve Paced key times. // if (hasPacedKeyTimes) { ResolvePacedKeyTimes(); } // // Sort resolved key frame entries. // Array.Sort(_sortedResolvedKeyFrames); _areKeyTimesValid = true; return; } /// <summary> /// This should only be called from ResolveKeyTimes and only at the /// appropriate time. /// </summary> private void ResolvePacedKeyTimes() { Debug.Assert(_keyFrames != null && _keyFrames.Count > 2, "Caller must guard against calling this method when there are insufficient keyframes."); // If the first key frame is paced its key time has already // been resolved, so we start at index 1. int index = 1; int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1; do { if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced) { // // We've found a paced key frame so this is the // beginning of a paced block. // // The first paced key frame in this block. int firstPacedBlockKeyFrameIndex = index; // List of segment lengths for this paced block. List<Double> segmentLengths = new List<Double>(); // The resolved key time for the key frame before this // block which we'll use as our starting point. TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime; // The total of the segment lengths of the paced key // frames in this block. Double totalLength = 0.0; // The key value of the previous key frame which will be // used to determine the segment length of this key frame. Byte prevKeyValue = _keyFrames[index - 1].Value; do { Byte currentKeyValue = _keyFrames[index].Value; // Determine the segment length for this key frame and // add to the total length. totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, currentKeyValue); // Temporarily store the distance into the total length // that this key frame represents in the resolved // key times array to be converted to a resolved key // time outside of this loop. segmentLengths.Add(totalLength); // Prepare for the next iteration. prevKeyValue = currentKeyValue; index++; } while ( index < maxKeyFrameIndex && _keyFrames[index].KeyTime.Type == KeyTimeType.Paced); // index is currently set to the index of the key frame // after the last paced key frame. This will always // be a valid index because we limit ourselves with // maxKeyFrameIndex. // We need to add the distance between the last paced key // frame and the next key frame to get the total distance // inside the key frame block. totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, _keyFrames[index].Value); // Calculate the time available in the resolved key time space. TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime; // Convert lengths in segmentLengths list to resolved // key times for the paced key frames in this block. for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++) { // The resolved key time for each key frame is: // // The key time of the key frame before this paced block // + ((the percentage of the way through the total length) // * the resolved key time space available for the block) _sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds( (segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds); } } else { index++; } } while (index < maxKeyFrameIndex); } #endregion } }
using System.Drawing; using FoxTrader.UI.ControlInternal; using static FoxTrader.Constants; namespace FoxTrader.UI.Control { /// <summary>HSV color picker with "before" and "after" color boxes</summary> internal class HSVColorPicker : GameControl, IColorPicker { private readonly ColorDisplay m_after; private readonly ColorDisplay m_before; private readonly ColorSlider m_colorSlider; private readonly ColorLerpBox m_lerpBox; /// <summary>Initializes a new instance of the <see cref="HSVColorPicker" /> class</summary> /// <param name="c_parentControl">Parent control</param> public HSVColorPicker(GameControl c_parentControl) : base(c_parentControl) { MouseInputEnabled = true; SetSize(256, 128); //ShouldCacheToTexture = true; m_lerpBox = new ColorLerpBox(this); m_lerpBox.ColorChanged += ColorBoxChanged; m_lerpBox.Dock = Pos.Left; m_colorSlider = new ColorSlider(this); m_colorSlider.SetPosition(m_lerpBox.Width + 15, 5); m_colorSlider.ColorChanged += ColorSliderChanged; m_colorSlider.Dock = Pos.Left; m_after = new ColorDisplay(this); m_after.SetSize(48, 24); m_after.SetPosition(m_colorSlider.X + m_colorSlider.Width + 15, 5); m_before = new ColorDisplay(this); m_before.SetSize(48, 24); m_before.SetPosition(m_after.X, 28); var a_x = m_before.X; var a_y = m_before.Y + 30; { var a_label = new Label(this); a_label.SetText("R:"); a_label.SizeToContents(); a_label.SetPosition(a_x, a_y); var a_numericTextBox = new TextBoxNumeric(this); a_numericTextBox.Name = "RedBox"; a_numericTextBox.SetPosition(a_x + 15, a_y - 1); a_numericTextBox.SetSize(26, 16); a_numericTextBox.SelectAllOnFocus = true; a_numericTextBox.TextChanged += NumericTyped; } a_y += 20; { var a_label = new Label(this); a_label.SetText("G:"); a_label.SizeToContents(); a_label.SetPosition(a_x, a_y); var a_numericTextBox = new TextBoxNumeric(this); a_numericTextBox.Name = "GreenBox"; a_numericTextBox.SetPosition(a_x + 15, a_y - 1); a_numericTextBox.SetSize(26, 16); a_numericTextBox.SelectAllOnFocus = true; a_numericTextBox.TextChanged += NumericTyped; } a_y += 20; { var a_label = new Label(this); a_label.SetText("B:"); a_label.SizeToContents(); a_label.SetPosition(a_x, a_y); var a_numericTextBox = new TextBoxNumeric(this); a_numericTextBox.Name = "BlueBox"; a_numericTextBox.SetPosition(a_x + 15, a_y - 1); a_numericTextBox.SetSize(26, 16); a_numericTextBox.SelectAllOnFocus = true; a_numericTextBox.TextChanged += NumericTyped; } SetColor(DefaultColor); } /// <summary>The "before" color</summary> public Color DefaultColor { get { return m_before.Color; } set { m_before.Color = value; } } /// <summary>Selected color</summary> public Color SelectedColor => m_lerpBox.SelectedColor; /// <summary>Invoked when the selected color has changed</summary> public event ColorEventHandler ColorChanged; private void NumericTyped(GameControl c_control) { var a_numericTextBox = c_control as TextBoxNumeric; if (a_numericTextBox == null || a_numericTextBox.Text == string.Empty) { return; } var a_textValue = (int)a_numericTextBox.Value; if (a_textValue < 0) { a_textValue = 0; } if (a_textValue > 255) { a_textValue = 255; } var a_newColor = SelectedColor; if (a_numericTextBox.Name.Contains("Red")) { a_newColor = Color.FromArgb(SelectedColor.A, a_textValue, SelectedColor.G, SelectedColor.B); } else if (a_numericTextBox.Name.Contains("Green")) { a_newColor = Color.FromArgb(SelectedColor.A, SelectedColor.R, a_textValue, SelectedColor.B); } else if (a_numericTextBox.Name.Contains("Blue")) { a_newColor = Color.FromArgb(SelectedColor.A, SelectedColor.R, SelectedColor.G, a_textValue); } else if (a_numericTextBox.Name.Contains("Alpha")) { a_newColor = Color.FromArgb(a_textValue, SelectedColor.R, SelectedColor.G, SelectedColor.B); } SetColor(a_newColor); } private void UpdateControls(Color c_color) { var a_redBox = FindChildByName("RedBox", false) as TextBoxNumeric; if (a_redBox != null) { a_redBox.SetText(c_color.R.ToString(), false); } var a_greenBox = FindChildByName("GreenBox", false) as TextBoxNumeric; if (a_greenBox != null) { a_greenBox.SetText(c_color.G.ToString(), false); } var a_blueBox = FindChildByName("BlueBox", false) as TextBoxNumeric; if (a_blueBox != null) { a_blueBox.SetText(c_color.B.ToString(), false); } m_after.Color = c_color; if (ColorChanged != null) { ColorChanged.Invoke(this); } } /// <summary>Sets the selected color</summary> /// <param name="c_color">Color to set</param> /// <param name="c_onlyHue">Determines whether only the hue should be set</param> /// <param name="c_reset">Determines whether the "before" color should be set as well</param> public void SetColor(Color c_color, bool c_onlyHue = false, bool c_reset = false) { UpdateControls(c_color); if (c_reset) { m_before.Color = c_color; } m_colorSlider.SelectedColor = c_color; m_lerpBox.SetColor(c_color, c_onlyHue); m_after.Color = c_color; } private void ColorBoxChanged(GameControl c_control) { UpdateControls(SelectedColor); Invalidate(); } private void ColorSliderChanged(GameControl c_control) { if (m_lerpBox != null) { m_lerpBox.SetColor(m_colorSlider.SelectedColor, true); } Invalidate(); } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; namespace AmplifyShaderEditor { public enum PropertyType { Constant, Property, InstancedProperty, Global } [Serializable] public class PropertyAttributes { public string Name; public string Attribute; public PropertyAttributes( string name, string attribute ) { Name = name; Attribute = attribute; } } [Serializable] public class PropertyNode : ParentNode { private const float NodeButtonSizeX = 16; private const float NodeButtonSizeY = 16; private const float NodeButtonDeltaX = 5; private const float NodeButtonDeltaY = 11; private const string IsPropertyStr = "Is Property"; private const string PropertyNameStr = "Property Name"; private const string PropertyInspectorStr = "Name"; private const string ParameterTypeStr = "Type"; private const string PropertyTextfieldControlName = "PropertyName"; private const string PropertyInspTextfieldControlName = "PropertyInspectorName"; private const string OrderIndexStr = "Order Index"; private const double MaxTimestamp = 2; private const double MaxPropertyTimestamp = 2; private readonly string[] LabelToolbarTitle = { "Material", "Default" }; [SerializeField] protected PropertyType m_currentParameterType; [SerializeField] private PropertyType m_lastParameterType; [SerializeField] protected string m_propertyName; [SerializeField] protected string m_propertyInspectorName; [SerializeField] protected string m_precisionString; protected bool m_drawPrecisionUI = true; [SerializeField] private int m_orderIndex = -1; protected bool m_freeName; protected bool m_freeType; protected bool m_propertyNameIsDirty; protected bool m_propertyFromInspector; protected double m_propertyFromInspectorTimestamp; protected bool m_delayedDirtyProperty; protected double m_delayedDirtyPropertyTimestamp; protected string m_defaultPropertyName; protected string m_oldName = string.Empty; private bool m_reRegisterName = false; //protected bool m_useCustomPrefix = false; protected string m_customPrefix = null; private int m_propertyTab = 0; private bool m_editPropertyNameMode = false; public PropertyNode() : base() { } public PropertyNode( int uniqueId, float x, float y, float width, float height ) : base( uniqueId, x, y, width, height ) { } [SerializeField] private string m_uniqueName; // Property Attributes private const float ButtonLayoutWidth = 15; private bool m_visibleAttribsFoldout; protected List<PropertyAttributes> m_availableAttribs = new List<PropertyAttributes>(); private string[] m_availableAttribsArr; [SerializeField] private List<int> m_selectedAttribs = new List<int>(); protected override void CommonInit( int uniqueId ) { base.CommonInit( uniqueId ); m_textLabelWidth = 105; m_orderIndex = UIUtils.GetPropertyNodeAmount(); m_currentParameterType = PropertyType.Constant; m_freeType = true; m_freeName = true; m_propertyNameIsDirty = true; m_availableAttribs.Add( new PropertyAttributes( "Hide in Inspector", "[HideInInspector]" ) ); m_availableAttribs.Add( new PropertyAttributes( "HDR", "[HDR]" ) ); m_availableAttribs.Add( new PropertyAttributes( "Gamma", "[Gamma]" ) ); } public override void AfterCommit() { base.AfterCommit(); if ( PaddingTitleLeft == 0 && m_freeType ) { PaddingTitleLeft = Constants.PropertyPickerWidth + Constants.IconsLeftRightMargin; if ( PaddingTitleRight == 0 ) PaddingTitleRight = Constants.PropertyPickerWidth + Constants.IconsLeftRightMargin; } } protected void BeginDelayedDirtyProperty() { m_delayedDirtyProperty = true; m_delayedDirtyPropertyTimestamp = EditorApplication.timeSinceStartup; } public void CheckDelayedDirtyProperty() { if ( m_delayedDirtyProperty ) { if ( ( EditorApplication.timeSinceStartup - m_delayedDirtyPropertyTimestamp ) > MaxPropertyTimestamp ) { m_delayedDirtyProperty = false; m_propertyNameIsDirty = true; m_sizeIsDirty = true; } } } public void BeginPropertyFromInspectorCheck() { m_propertyFromInspector = true; m_propertyFromInspectorTimestamp = EditorApplication.timeSinceStartup; } public void CheckPropertyFromInspector( bool forceUpdate = false ) { if ( m_propertyFromInspector ) { if ( forceUpdate || ( EditorApplication.timeSinceStartup - m_propertyFromInspectorTimestamp ) > MaxTimestamp ) { m_propertyFromInspector = false; RegisterPropertyName( true, m_propertyInspectorName ); m_propertyNameIsDirty = true; } } } public override void ReleaseUniqueIdData() { UIUtils.ReleaseUniformName( m_uniqueId, m_oldName ); RegisterFirstAvailablePropertyName( false ); } protected override void OnUniqueIDAssigned() { RegisterFirstAvailablePropertyName( false ); if ( m_nodeAttribs != null ) m_uniqueName = m_nodeAttribs.Name + m_uniqueId; } public bool CheckLocalVariable( ref MasterNodeDataCollector dataCollector ) { bool addToLocalValue = false; int count = 0; for ( int i = 0; i < m_outputPorts.Count; i++ ) { if ( m_outputPorts[ i ].IsConnected ) { if ( m_outputPorts[ i ].ConnectionCount > 1 ) { addToLocalValue = true; break; } count += 1; if ( count > 1 ) { addToLocalValue = true; break; } } } if ( addToLocalValue ) { ConfigureLocalVariable( ref dataCollector ); } return addToLocalValue; } public virtual void ConfigureLocalVariable( ref MasterNodeDataCollector dataCollector ) { } public virtual void CopyDefaultsToMaterial() { } public override void SetupFromCastObject( UnityEngine.Object obj ) { RegisterPropertyName( true, obj.name ); } public void ChangeParameterType( PropertyType parameterType ) { if ( m_currentParameterType == PropertyType.Constant ) { CopyDefaultsToMaterial(); } if ( parameterType == PropertyType.InstancedProperty ) { UIUtils.AddInstancePropertyCount(); } else if ( m_currentParameterType == PropertyType.InstancedProperty ) { UIUtils.RemoveInstancePropertyCount(); } if ( ( parameterType == PropertyType.Property || parameterType == PropertyType.InstancedProperty ) && m_currentParameterType != PropertyType.Property && m_currentParameterType != PropertyType.InstancedProperty ) { UIUtils.RegisterPropertyNode( this ); } if ( ( parameterType != PropertyType.Property && parameterType != PropertyType.InstancedProperty ) && ( m_currentParameterType == PropertyType.Property || m_currentParameterType == PropertyType.InstancedProperty ) ) { UIUtils.UnregisterPropertyNode( this ); } m_currentParameterType = parameterType; } void InitializeAttribsArray() { m_availableAttribsArr = new string[ m_availableAttribs.Count ]; for ( int i = 0; i < m_availableAttribsArr.Length; i++ ) { m_availableAttribsArr[ i ] = m_availableAttribs[ i ].Name; } } void DrawAttributesAddRemoveButtons() { if ( m_availableAttribsArr == null ) { InitializeAttribsArray(); } EditorGUILayout.Separator(); int attribCount = m_selectedAttribs.Count; if ( attribCount == 0 ) m_visibleAttribsFoldout = false; // Add new port if ( GUILayout.Button( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ButtonLayoutWidth ) ) ) { m_selectedAttribs.Add( 0 ); m_visibleAttribsFoldout = true; } //Remove port if ( GUILayout.Button( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ButtonLayoutWidth ) ) ) { if ( attribCount > 0 ) { m_selectedAttribs.RemoveAt( attribCount - 1 ); } } } void DrawAttributes() { int attribCount = m_selectedAttribs.Count; bool actionAllowed = true; int deleteItem = -1; if ( m_visibleAttribsFoldout ) { for ( int i = 0; i < attribCount; i++ ) { m_selectedAttribs[ i ] = EditorGUILayoutPopup( m_selectedAttribs[ i ], m_availableAttribsArr ); EditorGUILayout.BeginHorizontal(); GUILayout.Label( " " ); // Add After if ( GUILayout.Button( string.Empty, UIUtils.PlusStyle, GUILayout.Width( ButtonLayoutWidth ) ) ) { if ( actionAllowed ) { m_selectedAttribs.Insert( i, m_selectedAttribs[ i ] ); actionAllowed = false; } } // Remove Current if ( GUILayout.Button( string.Empty, UIUtils.MinusStyle, GUILayout.Width( ButtonLayoutWidth ) ) ) { if ( actionAllowed ) { actionAllowed = false; deleteItem = i; } } EditorGUILayout.EndHorizontal(); } if ( deleteItem > -1 ) { m_selectedAttribs.RemoveAt( deleteItem ); } } } public virtual void DrawMainPropertyBlock() { EditorGUILayout.BeginVertical(); { if ( m_freeType ) { PropertyType parameterType = ( PropertyType ) EditorGUILayoutEnumPopup( ParameterTypeStr, m_currentParameterType ); if ( parameterType != m_currentParameterType ) { ChangeParameterType( parameterType ); } } if ( m_freeName ) { switch ( m_currentParameterType ) { case PropertyType.Property: case PropertyType.InstancedProperty: { ShowPropertyInspectorNameGUI(); ShowPropertyNameGUI( true ); ShowPrecision(); ShowToolbar(); } break; case PropertyType.Global: { ShowPropertyInspectorNameGUI(); ShowPropertyNameGUI( false ); ShowPrecision(); ShowDefaults(); } break; case PropertyType.Constant: { ShowPropertyInspectorNameGUI(); ShowPrecision(); ShowDefaults(); } break; } } } EditorGUILayout.EndVertical(); } public override void DrawProperties() { base.DrawProperties(); if ( m_freeType || m_freeName ) { NodeUtils.DrawPropertyGroup( ref m_propertiesFoldout, Constants.ParameterLabelStr, DrawMainPropertyBlock ); NodeUtils.DrawPropertyGroup( ref m_visibleAttribsFoldout, Constants.AttributesLaberStr, DrawAttributes, DrawAttributesAddRemoveButtons ); CheckPropertyFromInspector(); } } public void ShowPrecision() { if ( m_drawPrecisionUI ) { EditorGUI.BeginChangeCheck(); DrawPrecisionProperty(); if ( EditorGUI.EndChangeCheck() ) m_precisionString = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); } } public void ShowToolbar() { //if ( !CanDrawMaterial ) //{ // ShowDefaults(); // return; //} m_propertyTab = GUILayout.Toolbar( m_propertyTab, LabelToolbarTitle ); switch ( m_propertyTab ) { default: case 0: EditorGUI.BeginChangeCheck(); DrawMaterialProperties(); if ( EditorGUI.EndChangeCheck() ) { BeginDelayedDirtyProperty(); } break; case 1: ShowDefaults(); break; } } public void ShowDefaults() { EditorGUI.BeginChangeCheck(); DrawSubProperties(); if ( EditorGUI.EndChangeCheck() ) { BeginDelayedDirtyProperty(); } } public void ShowPropertyInspectorNameGUI() { EditorGUI.BeginChangeCheck(); m_propertyInspectorName = EditorGUILayoutTextField( PropertyInspectorStr, m_propertyInspectorName ); if ( EditorGUI.EndChangeCheck() ) { if ( m_propertyInspectorName.Length > 0 ) { BeginPropertyFromInspectorCheck(); } } } public void ShowPropertyNameGUI( bool isProperty ) { bool guiEnabledBuffer = GUI.enabled; GUI.enabled = false; m_propertyName = EditorGUILayoutTextField( PropertyNameStr, m_propertyName ); GUI.enabled = guiEnabledBuffer; } public virtual string GetPropertyValStr() { return string.Empty; } public override bool OnClick( Vector2 currentMousePos2D ) { bool singleClick = base.OnClick( currentMousePos2D ); m_propertyTab = 0; return singleClick; } public override void OnNodeDoubleClicked( Vector2 currentMousePos2D ) { if ( currentMousePos2D.y - m_globalPosition.y > Constants.NODE_HEADER_HEIGHT + Constants.NODE_HEADER_EXTRA_HEIGHT ) { UIUtils.CurrentWindow.ParametersWindow.IsMaximized = !UIUtils.CurrentWindow.ParametersWindow.IsMaximized; } else { m_editPropertyNameMode = true; GUI.FocusControl( m_uniqueName ); TextEditor te = ( TextEditor ) GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl ); if ( te != null ) { te.SelectAll(); } } } public override void OnNodeSelected( bool value ) { base.OnNodeSelected( value ); if ( !value ) m_editPropertyNameMode = false; } public override void DrawTitle( Rect titlePos ) { if ( m_editPropertyNameMode ) { titlePos.height = Constants.NODE_HEADER_HEIGHT; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName( m_uniqueName ); m_propertyInspectorName = GUITextField( titlePos, m_propertyInspectorName, UIUtils.GetCustomStyle( CustomStyle.NodeTitle ) ); if ( EditorGUI.EndChangeCheck() ) { SetTitleText( m_propertyInspectorName ); m_sizeIsDirty = true; m_isDirty = true; if ( m_propertyInspectorName.Length > 0 ) { BeginPropertyFromInspectorCheck(); } } if ( Event.current.isKey && ( Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter ) ) { m_editPropertyNameMode = false; GUIUtility.keyboardControl = 0; } } else { base.DrawTitle( titlePos ); } } public override void Draw( DrawInfo drawInfo ) { if ( m_reRegisterName ) { m_reRegisterName = false; UIUtils.RegisterUniformName( m_uniqueId, m_propertyName ); } CheckDelayedDirtyProperty(); if ( m_currentParameterType != m_lastParameterType || m_propertyNameIsDirty ) { m_lastParameterType = m_currentParameterType; m_propertyNameIsDirty = false; if ( m_currentParameterType != PropertyType.Constant ) { SetTitleText( m_propertyInspectorName ); SetAdditonalTitleText( string.Format( Constants.PropertyValueLabel, GetPropertyValStr() ) ); } else { SetTitleText( m_propertyInspectorName ); SetAdditonalTitleText( string.Format( Constants.ConstantsValueLabel, GetPropertyValStr() ) ); } m_sizeIsDirty = true; } CheckPropertyFromInspector(); base.Draw( drawInfo ); if ( m_freeType ) { 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; PropertyType parameterType = ( PropertyType ) EditorGUIEnumPopup( rect, m_currentParameterType, UIUtils.PropertyPopUp ); if ( parameterType != m_currentParameterType ) { ChangeParameterType( parameterType ); } } } public void RegisterFirstAvailablePropertyName( bool releaseOldOne ) { if ( releaseOldOne ) UIUtils.ReleaseUniformName( m_uniqueId, m_oldName ); UIUtils.GetFirstAvailableName( m_uniqueId, m_outputPorts[ 0 ].DataType, out m_propertyName, out m_propertyInspectorName, !string.IsNullOrEmpty( m_customPrefix ), m_customPrefix ); m_oldName = m_propertyName; m_propertyNameIsDirty = true; m_reRegisterName = false; OnPropertyNameChanged(); } public void RegisterPropertyName( bool releaseOldOne, string newName ) { string propertyName = UIUtils.GeneratePropertyName( newName, m_currentParameterType ); if ( m_propertyName.Equals( propertyName ) ) return; if ( UIUtils.IsUniformNameAvailable( propertyName ) ) { if ( releaseOldOne ) UIUtils.ReleaseUniformName( m_uniqueId, m_oldName ); m_oldName = propertyName; m_propertyName = propertyName; m_propertyInspectorName = newName; m_propertyNameIsDirty = true; m_reRegisterName = false; UIUtils.RegisterUniformName( m_uniqueId, propertyName ); OnPropertyNameChanged(); } else { GUI.FocusControl( string.Empty ); RegisterFirstAvailablePropertyName( releaseOldOne ); UIUtils.ShowMessage( string.Format( "Duplicate name found on edited node.\nAssigning first valid one {0}", m_propertyInspectorName ) ); } } protected string CreateLocalVarDec( string value ) { return string.Format( Constants.PropertyLocalVarDec, UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ), m_propertyName, value ); } public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar ) { CheckPropertyFromInspector( true ); if ( m_propertyName.Length == 0 ) { RegisterFirstAvailablePropertyName( false ); } switch ( CurrentParameterType ) { case PropertyType.Property: { dataCollector.AddToProperties( m_uniqueId, GetPropertyValue(), m_orderIndex ); string dataType = string.Empty; string dataName = string.Empty; GetUniformData( out dataType, out dataName ); dataCollector.AddToUniforms( m_uniqueId, dataType, dataName ); //dataCollector.AddToUniforms( m_uniqueId, GetUniformValue() ); } break; case PropertyType.InstancedProperty: { dataCollector.AddToProperties( m_uniqueId, GetPropertyValue(), m_orderIndex ); dataCollector.AddToInstancedProperties( m_uniqueId, GetInstancedPropertyValue(), m_orderIndex ); } break; case PropertyType.Global: { string dataType = string.Empty; string dataName = string.Empty; GetUniformData( out dataType, out dataName ); dataCollector.AddToUniforms( m_uniqueId, dataType, dataName ); //dataCollector.AddToUniforms( m_uniqueId, GetUniformValue() ); } break; case PropertyType.Constant: break; } dataCollector.AddPropertyNode( this ); return string.Empty; } public override void Destroy() { base.Destroy(); UIUtils.ReleaseUniformName( m_uniqueId, m_propertyName ); if ( m_currentParameterType == PropertyType.InstancedProperty ) { UIUtils.RemoveInstancePropertyCount(); UIUtils.UnregisterPropertyNode( this ); } if ( m_currentParameterType == PropertyType.Property ) { UIUtils.UnregisterPropertyNode( this ); } m_availableAttribs.Clear(); m_availableAttribs = null; } public string PropertyAttributes { get { int attribCount = m_selectedAttribs.Count; if ( m_selectedAttribs.Count == 0 ) return string.Empty; string attribs = string.Empty; for ( int i = 0; i < attribCount; i++ ) { attribs += m_availableAttribs[ m_selectedAttribs[ i ] ].Attribute; } return attribs; } } public virtual void OnPropertyNameChanged() { } public virtual void DrawSubProperties() { } public virtual void DrawMaterialProperties() { } public virtual string GetPropertyValue() { return string.Empty; } public virtual string GetInstancedPropertyValue() { return string.Format( IOUtils.InstancedPropertiesElement, UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ), m_propertyName ); } public virtual string GetUniformValue() { return string.Format( Constants.UniformDec, UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ), m_propertyName ); } public virtual void GetUniformData( out string dataType, out string dataName ) { dataType = UIUtils.FinalPrecisionWirePortToCgType( m_currentPrecisionType, m_outputPorts[ 0 ].DataType ); dataName = m_propertyName; } public PropertyType CurrentParameterType { get { return m_currentParameterType; } set { m_currentParameterType = value; } } public override void WriteToString( ref string nodeInfo, ref string connectionsInfo ) { base.WriteToString( ref nodeInfo, ref connectionsInfo ); IOUtils.AddFieldValueToString( ref nodeInfo, m_currentParameterType ); IOUtils.AddFieldValueToString( ref nodeInfo, m_propertyName ); IOUtils.AddFieldValueToString( ref nodeInfo, m_propertyInspectorName ); IOUtils.AddFieldValueToString( ref nodeInfo, m_orderIndex ); int attribCount = m_selectedAttribs.Count; IOUtils.AddFieldValueToString( ref nodeInfo, attribCount ); if ( attribCount > 0 ) { for ( int i = 0; i < attribCount; i++ ) { IOUtils.AddFieldValueToString( ref nodeInfo, m_availableAttribs[ m_selectedAttribs[ i ] ].Attribute ); } } } int IdForAttrib( string name ) { int attribCount = m_availableAttribs.Count; for ( int i = 0; i < attribCount; i++ ) { if ( m_availableAttribs[ i ].Attribute.Equals( name ) ) return i; } return 0; } public override void ReadFromString( ref string[] nodeParams ) { base.ReadFromString( ref nodeParams ); if ( UIUtils.CurrentShaderVersion() < 2505 ) { string property = GetCurrentParam( ref nodeParams ); m_currentParameterType = property.Equals( "Uniform" ) ? PropertyType.Global : ( PropertyType ) Enum.Parse( typeof( PropertyType ), property ); } else { m_currentParameterType = ( PropertyType ) Enum.Parse( typeof( PropertyType ), GetCurrentParam( ref nodeParams ) ); } if ( m_currentParameterType == PropertyType.InstancedProperty ) { UIUtils.AddInstancePropertyCount(); UIUtils.RegisterPropertyNode( this ); } if ( m_currentParameterType == PropertyType.Property ) { UIUtils.RegisterPropertyNode( this ); } m_propertyName = GetCurrentParam( ref nodeParams ); m_propertyInspectorName = GetCurrentParam( ref nodeParams ); if ( UIUtils.CurrentShaderVersion() > 13 ) { m_orderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); } if ( UIUtils.CurrentShaderVersion() > 4102 ) { int attribAmount = Convert.ToInt32( GetCurrentParam( ref nodeParams ) ); if ( attribAmount > 0 ) { for ( int i = 0; i < attribAmount; i++ ) { m_selectedAttribs.Add( IdForAttrib( GetCurrentParam( ref nodeParams ) ) ); } } InitializeAttribsArray(); } m_propertyNameIsDirty = true; m_reRegisterName = false; UIUtils.ReleaseUniformName( m_uniqueId, m_oldName ); UIUtils.RegisterUniformName( m_uniqueId, m_propertyName ); m_oldName = m_propertyName; } public override void OnEnable() { base.OnEnable(); m_reRegisterName = true; } public bool CanDrawMaterial { get { return m_materialMode && m_currentParameterType != PropertyType.Constant; } } public int OrderIndex { get { return m_orderIndex; } set { m_orderIndex = value; } } public string PropertyData { get { return ( m_currentParameterType == PropertyType.InstancedProperty ) ? string.Format( IOUtils.InstancedPropertiesData, m_propertyName ) : m_propertyName; } } public virtual string PropertyName { get { return m_propertyName; } } public string PropertyInspectorName { get { return m_propertyInspectorName; } } public bool FreeType { get { return m_freeType; } set { m_freeType = value; } } public bool ReRegisterName { get { return m_reRegisterName; } set { m_reRegisterName = value; } } public string CustomPrefix { get { return m_customPrefix; } set { m_customPrefix = value; } } public override void RefreshOnUndo() { base.RefreshOnUndo(); BeginPropertyFromInspectorCheck(); } } }
/** * FileCache.cs * * @project MonoCache * @author Dmitry Ponomarev <demdxx@gmail.com> * @license MIT Copyright (c) 2013 demdxx. All rights reserved. * * * Copyright (C) <2013> Dmitry Ponomarev <demdxx@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; #if !IO_INTERFACE using System.IO; using System.Runtime.Serialization.Formatters.Binary; #endif namespace MonoCache { /** * Stores data in the file system in a special directory. * Accessing data is on a key that can be of any unique * string that is converted into a hash key and possibly * trying to get the file extension from the passed name. * * Example: * * // Get file cache manager * var fc = new FileCache (cacheDir, 1000 * 60 * 60 * 24); * * // Store data * fc.Add (url, data); * * // ... * * // Restore data * object data = fc.Get (url); * * // ... * * // Remove data from cache * fc.Remove (url); * * // OR * * fc.Clear (); * * // OR * * fc.ClearExpired (); */ public sealed class FileCache : CacheBase { #if IO_INTERFACE private IOInterface IO; #endif /** * Directory for store caches */ public string BaseDir { get; private set; } /** * Constructor * @param baseDir * @param liveTime default 3 days */ #if IO_INTERFACE public FileCache (string baseDir, IOInterface io, long lifeTime = 1000 * 60 * 60 * 24 * 3) : base (lifeTime) #else // IO_INTERFACE public FileCache (string baseDir, long lifeTime = 1000 * 60 * 60 * 24 * 3) : base (lifeTime) #endif // END IO_INTERFACE { if (null == baseDir || baseDir.Length<1) { throw new ArgumentNullException ("baseDir", "It is file cache root directory. Can`t be null!"); } #if IO_INTERFACE IO = io; if (null == IO) { throw new ArgumentNullException("io", "IO interface. Can`t be null!"); } if (!IO.DirectoryExists(baseDir)) { if (!IO.DirectoryCreate(baseDir)) { #else // IO_INTERFACE if (!Directory.Exists (baseDir)) { if (null == Directory.CreateDirectory (baseDir)) { #endif // END IO_INTERFACE throw new Exception("Can`t create cache root directory."); } } BaseDir = baseDir; } #region Implementation /** * Set value to cache * @param key * @param value * @param rewrite * @param checkExpired Check the end of the lifetime of * @return success state */ public override bool Set(string key, object value, bool rewrite = false, bool checkExpired = true) { string filePath = FilePath (key); #if IO_INTERFACE if (checkExpired && !rewrite && IO.FileExists(filePath)) { if (!IsExpired(IO.FileGetLastWriteTimeUtc(filePath))) { return false; } } IO.FileSerialize(filePath, value); #else // IO_INTERFACE if (checkExpired && !rewrite && File.Exists (filePath)) { if (!IsExpired (File.GetLastWriteTimeUtc (filePath))) { return false; } } using (FileStream fs = File.OpenWrite (filePath)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize (fs, value); } #endif // END IO_INTERFACE return true; } private bool CheckFile(string filePath, bool checkExpired = true) { #if IO_INTERFACE if (!IO.FileExists(filePath)) { return false; } if (checkExpired && IsExpired(IO.FileGetLastWriteTimeUtc(filePath))) { IO.FileDelete(filePath); return false; } #else // IO_INTERFACE if (!File.Exists (filePath)) { return false; } if (checkExpired && IsExpired (File.GetLastWriteTimeUtc (filePath))) { File.Delete (filePath); return false; } #endif // END IO_INTERFACE return true; } /** * If object cached * @param key * @param checkExpired Check the end of the lifetime of * @return success status */ public override bool Check(string key, bool checkExpired = true) { return CheckFile(FilePath(key), checkExpired); } /** * Get object by key * @param key * @param checkExpired Check the end of the lifetime of * @return object */ public override object Get(string key, bool checkExpired = true) { string filePath = FilePath (key); if (!CheckFile(filePath, checkExpired)) { return null; } // Read file bynary #if IO_INTERFACE return IO.FileDeserialize(filePath); #else // IO_INTERFACE using (FileStream fs = File.OpenRead (filePath)) { BinaryFormatter bf = new BinaryFormatter (); return bf.Deserialize (fs); } #endif // END IO_INTERFACE } /** * Get address by key * @param key * @param checkExpired Check the end of the lifetime of * @return object */ public override string GetAddress(string key, bool checkExpired = true) { string filePath = FilePath (key); if (!CheckFile(filePath, checkExpired)) { return null; } return filePath; } private void RemoveFile(string filePath) { #if IO_INTERFACE if (IO.FileExists(filePath)) { IO.FileDelete(filePath); } #else // IO_INTERFACE if (File.Exists (filePath)) { File.Delete (filePath); } #endif // END IO_INTERFACE } /** * Remove value by key * @[aram key */ public override void Remove(string key) { RemoveFile(FilePath(key)); } /** * Remove value by id * @param id */ protected override void RemoveFromId(string id) { RemoveFile(FilePathByID(id)); } /** * List of expired keys * @return string [] */ protected override string [] ExpiredListOfKeys () { #if IO_INTERFACE string[] files = IO.DirectoryGetFiles(BaseDir, "*"); #else // IO_INTERFACE string [] files = Directory.GetFiles (BaseDir, "*"); #endif // END IO_INTERFACE List<string> result = new List<string> (); if (null != files) { foreach (string file in files) { #if IO_INTERFACE if (IsExpired(IO.FileGetLastWriteTimeUtc(file))) { result.Add(IO.PathGetFileNameWithoutExtension(file)); } #else // IO_INTERFACE if (IsExpired (File.GetLastWriteTimeUtc (file))) { result.Add (Path.GetFileNameWithoutExtension (file)); } #endif // END IO_INTERFACE } } return result.ToArray (); } /** * Full list of keys * @return string [] */ protected override string [] ListOfKeys () { #if IO_INTERFACE string[] files = IO.DirectoryGetFiles(BaseDir, "*"); #else // IO_INTERFACE string [] files = Directory.GetFiles (BaseDir, "*"); #endif // END IO_INTERFACE if (null != files) { for (int i = 0; i < files.Length; i++) { #if IO_INTERFACE files[i] = IO.PathGetFileNameWithoutExtension(files[i]); #else // IO_INTERFACE files [i] = Path.GetFileNameWithoutExtension (files [i]); #endif // END IO_INTERFACE } } return files; } #endregion // Implementation #region Helpers private string FilePath (string key) { #if IO_INTERFACE return IO.PathCombine(BaseDir, PrepareName(key)); #else // IO_INTERFACE return Path.Combine (BaseDir, PrepareName (key)); #endif // END IO_INTERFACE } private string FilePathByID (string id) { #if IO_INTERFACE string[] files = IO.DirectoryGetFiles(BaseDir, id + "*"); if (null == files && files.Length > 0) { return IO.PathCombine(BaseDir, files[0]); } #else // IO_INTERFACE string[] files = Directory.GetFiles (BaseDir, id+"*"); if (null == files && files.Length > 0) { return Path.Combine (BaseDir, files [0]); } #endif // END IO_INTERFACE return null; } private string PrepareName (string key) { #if IO_INTERFACE string ext = IO.PathGetExtension(key); #else // IO_INTERFACE string ext = Path.GetExtension (key); #endif // END IO_INTERFACE string name = StringToMD5 (key); return string.IsNullOrEmpty (ext) ? name : ('.' == ext[0] ? name + ext : name + "." + ext); } #endregion } }
/* Copyright 2019 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 System; using System.IO; using ESRI.ArcGIS; using ESRI.ArcGIS.DataSourcesGDB; using ESRI.ArcGIS.DataSourcesRaster; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using CustomFunction; /* This is an optional test program which allows the user to use the Custom Raster Function in a variety of ways: 1.) Create a function raster dataset by applying the custom function on top of a raster dataset. 2.) Add the custom function on top of a mosaic dataset. 3.) Create a RasterFunctionTemplate from the function. 4.) Serialize the function in the form of a RasterFunctionTemplate object to an xml. 5.) Get a RasterFunctionTemplate object back from a serialized xml. Note: Successsful serialization to xml involves changes to the XmlSupport.dat file in the "<Program Files>\ArcGIS\Desktop10.2\bin" folder. */ namespace SampleTest { public class TestWatermarkFunction { [STAThread] public static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); // To make changes to a Mosaic Dataset, a Standard or Advanced license is required. esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Flags to specify the operation to perform bool addToRD = true; // Create Watermark Function Raster Dataset bool addToMD = false; // Add Watermark Function to MD bool writeTemplateToXml = false; // Serialize a template form of the NDVI Custom Funtion to Xml. bool getfromXml = false; // Get a template object back from its serialized xml. #region Specify inputs. // Raster Dataset parameters string workspaceFolder = @"f:\data\RasterDataset\LACounty\"; string rasterDatasetName = "6466_1741c.tif"; // Output parameters for Function Raster Dataset string outputFolder = @"c:\temp\CustomFunction"; string outputName = "WatermarkSample.afr"; // Mosaic Dataset parameters // GDB containing the Mosaic Dataset string mdWorkspaceFolder = @"c:\temp\CustomFunction\SampleGdb.gdb"; // Name of the Mosaic Dataset string mdName = "SampleMD"; // Watermark Parameters string watermarkImagePath = @"e:\Dev\SDK\Raster\NET\Samples\CustomRasterFunction\CSharp\TestWatermarkFunction\Sample.png"; double blendPercentage = 80.00; esriWatermarkLocation wmLocation = esriWatermarkLocation.esriWatermarkCenter; // Xml file path to save to or read from xml. string xmlFilePath = @"c:\temp\CustomFunction\Xml\Watermark.RFT.xml"; #endregion if (addToRD) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(workspaceFolder, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(rasterDatasetName); AddWatermarkToRD(rasterDataset, outputFolder, outputName, watermarkImagePath, blendPercentage, wmLocation); // Cleanup workspaceFactory = null; rasterWorkspace = null; rasterDataset = null; } if (addToMD) AddWatermarkDataToMD(mdWorkspaceFolder, mdName, watermarkImagePath, blendPercentage, wmLocation, true); if (writeTemplateToXml && xmlFilePath != "") { // Create a template with the Watermark Function. IRasterFunctionTemplate watermarkFunctionTemplate = CreateWatermarkTemplate(watermarkImagePath, blendPercentage, wmLocation); // Serialize the template to an xml file. bool status = WriteToXml(watermarkFunctionTemplate, xmlFilePath); } if (getfromXml && xmlFilePath != "") { // Create a RasterFunctionTemplate object from the serialized xml. object serializedObj = ReadFromXml(xmlFilePath); if (serializedObj is IRasterFunctionTemplate) Console.WriteLine("Success."); else Console.WriteLine("Failed."); } Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } catch (Exception exc) { Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } } public static bool AddWatermarkToRD(IRasterDataset RasterDataset, string OutputFolder, string OutputName, string watermarkImagePath, double blendPercentage, esriWatermarkLocation watermarklocation) { try { // Create Watermark Function IRasterFunction rasterFunction = new CustomFunction.WatermarkFunction(); // Create the Watermark Function Arguments object IWatermarkFunctionArguments rasterFunctionArguments = new WatermarkFunctionArguments(); // Set the WatermarkImagePath rasterFunctionArguments.WatermarkImagePath = watermarkImagePath; // the blending percentage, rasterFunctionArguments.BlendPercentage = blendPercentage; // and the watermark location. rasterFunctionArguments.WatermarkLocation = watermarklocation; // Set the Raster Dataset as the input raster rasterFunctionArguments.Raster = RasterDataset; // Create Function Dataset IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); // Create a Function Raster Dataset Name object IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName)new FunctionRasterDatasetName(); // Set the path for the output Function Raster Dataset functionRasterDatasetName.FullName = System.IO.Path.Combine(OutputFolder, OutputName); functionRasterDataset.FullName = (IName)functionRasterDatasetName; // Initialize the Function Raster Dataset with the function and // its arguments object functionRasterDataset.Init(rasterFunction, rasterFunctionArguments); // Save as Function Raster Dataset as an .afr file ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset; myTempDset.MakePermanent(); Console.WriteLine("Generated " + OutputName + "."); Console.WriteLine("Success."); return true; } catch (Exception exc) { Console.WriteLine("Exception Caught while adding watermark to Raster Dataset: " + exc.Message); Console.WriteLine("Failed."); return false; } } public static bool AddWatermarkDataToMD(string MDWorkspaceFolder, string MDName, string watermarkImagePath, double blendPercentage, esriWatermarkLocation watermarklocation, bool clearFunctions) { try { // Open MD Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); IWorkspaceFactory mdWorkspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace mdWorkspace = mdWorkspaceFactory.OpenFromFile(MDWorkspaceFolder, 0); IRasterWorkspaceEx workspaceEx = (IRasterWorkspaceEx)(mdWorkspace); IMosaicDataset mosaicDataset = (IMosaicDataset)workspaceEx.OpenRasterDataset( MDName); if (clearFunctions) // Clear functions already added to MD. mosaicDataset.ClearFunction(); // Create Watermark Function IRasterFunction rasterFunction = new CustomFunction.WatermarkFunction(); // Create the Watermark Function Arguments object IWatermarkFunctionArguments rasterFunctionArguments = new WatermarkFunctionArguments(); // Set the WatermarkImagePath rasterFunctionArguments.WatermarkImagePath = watermarkImagePath; // the blending percentage, rasterFunctionArguments.BlendPercentage = blendPercentage; // and the watermark location. rasterFunctionArguments.WatermarkLocation = watermarklocation; // Add function to MD. // This function takes the name of the property corresponding to the Raster // property of the Arguments object (in this case is it called Raster itself: // rasterFunctionArguments.Raster) as its third argument. mosaicDataset.ApplyFunction(rasterFunction, rasterFunctionArguments, "Raster"); Console.WriteLine("Added Watermark to MD: " + MDName + "."); Console.WriteLine("Success."); return true; } catch (Exception exc) { Console.WriteLine("Exception Caught while adding watermark to MD: " + exc.Message); Console.WriteLine("Failed."); return false; } } public static IRasterFunctionTemplate CreateWatermarkTemplate(string watermarkImagePath, double blendPercentage, esriWatermarkLocation watermarklocation) { #region Setup Raster Function Vars IRasterFunctionVariable watermarkRasterRFV = new RasterFunctionVariableClass(); watermarkRasterRFV.Name = "Raster"; watermarkRasterRFV.IsDataset = true; IRasterFunctionVariable watermarkImagePathRFV = new RasterFunctionVariableClass(); watermarkImagePathRFV.Name = "WatermarkImagePath"; watermarkImagePathRFV.Value = watermarkImagePath; watermarkImagePathRFV.IsDataset = false; IRasterFunctionVariable watermarkBlendPercRFV = new RasterFunctionVariableClass(); watermarkBlendPercRFV.Name = "BlendPercentage"; watermarkBlendPercRFV.Value = blendPercentage; IRasterFunctionVariable watermarkLocationRFV = new RasterFunctionVariableClass(); watermarkLocationRFV.Name = "Watermarklocation"; watermarkLocationRFV.Value = watermarklocation; #endregion #region Setup Raster Function Template // Create the Watermark Function Arguments object IRasterFunctionArguments rasterFunctionArguments = new CustomFunction.WatermarkFunctionArguments(); // Set the WatermarkImagePath rasterFunctionArguments.PutValue("WatermarkImagePath", watermarkImagePathRFV); // the blending percentage, rasterFunctionArguments.PutValue("BlendPercentage", watermarkBlendPercRFV); // and the watermark location. rasterFunctionArguments.PutValue("WatermarkLocation", watermarkLocationRFV); // Set the Raster Dataset as the input raster rasterFunctionArguments.PutValue("Raster", watermarkRasterRFV); IRasterFunction watermarkFunction = new CustomFunction.WatermarkFunction(); IRasterFunctionTemplate watermarkFunctionTemplate = new RasterFunctionTemplateClass(); watermarkFunctionTemplate.Function = watermarkFunction; watermarkFunctionTemplate.Arguments = rasterFunctionArguments; #endregion return watermarkFunctionTemplate; } public static bool WriteToXml(object inputDataset, string xmlFilePath) { try { // Check if file exists if (File.Exists(xmlFilePath)) { Console.WriteLine("File already exists."); return false; } // Create new file. IFile xmlFile = new FileStreamClass(); xmlFile.Open(xmlFilePath, esriFilePermission.esriReadWrite); // See if the input dataset can be Xml serialized. IXMLSerialize mySerializeData = (IXMLSerialize)inputDataset; // Create new XmlWriter object. IXMLWriter myXmlWriter = new XMLWriterClass(); myXmlWriter.WriteTo((IStream)xmlFile); myXmlWriter.WriteXMLDeclaration(); IXMLSerializer myXmlSerializer = new XMLSerializerClass(); // Write to XML File myXmlSerializer.WriteObject(myXmlWriter, null, null, null, null, mySerializeData); Console.WriteLine("Success."); return true; } catch (Exception exc) { Console.WriteLine("Exception caught in WriteToXml: " + exc.Message); Console.WriteLine("Failed."); return false; } } public static object ReadFromXml(string xmlFilePath) { try { IFile inputXmlFile = new FileStreamClass(); inputXmlFile.Open(xmlFilePath, esriFilePermission.esriReadWrite); IXMLReader myXmlReader = new XMLReaderClass(); myXmlReader.ReadFrom((IStream)inputXmlFile); IXMLSerializer myInputXmlSerializer = new XMLSerializerClass(); object myFunctionObject = myInputXmlSerializer.ReadObject(myXmlReader, null, null); return myFunctionObject; } catch (Exception exc) { Console.WriteLine("Exception caught in ReadFromXml: " + exc.Message); return null; } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudOSLogin.v1alpha { /// <summary>The CloudOSLogin Service.</summary> public class CloudOSLoginService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1alpha"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudOSLoginService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudOSLoginService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Users = new UsersResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "oslogin"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://oslogin.googleapis.com/"; #else "https://oslogin.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://oslogin.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Cloud OS Login API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary> /// View your data across Google Cloud services and see the email address of your Google Account /// </summary> public static string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only"; /// <summary>View and manage your Google Compute Engine resources</summary> public static string Compute = "https://www.googleapis.com/auth/compute"; /// <summary>View your Google Compute Engine resources</summary> public static string ComputeReadonly = "https://www.googleapis.com/auth/compute.readonly"; } /// <summary>Available OAuth 2.0 scope constants for use with the Cloud OS Login API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary> /// View your data across Google Cloud services and see the email address of your Google Account /// </summary> public const string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only"; /// <summary>View and manage your Google Compute Engine resources</summary> public const string Compute = "https://www.googleapis.com/auth/compute"; /// <summary>View your Google Compute Engine resources</summary> public const string ComputeReadonly = "https://www.googleapis.com/auth/compute.readonly"; } /// <summary>Gets the Users resource.</summary> public virtual UsersResource Users { get; } } /// <summary>A base abstract class for CloudOSLogin requests.</summary> public abstract class CloudOSLoginBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudOSLoginBaseServiceRequest instance.</summary> protected CloudOSLoginBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudOSLogin parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "users" collection of methods.</summary> public class UsersResource { private const string Resource = "users"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public UsersResource(Google.Apis.Services.IClientService service) { this.service = service; Projects = new ProjectsResource(service); SshPublicKeys = new SshPublicKeysResource(service); } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Deletes a POSIX account.</summary> /// <param name="name"> /// Required. A reference to the POSIX account to update. POSIX accounts are identified by the project ID /// they are associated with. A reference to the POSIX account is in format /// `users/{user}/projects/{project}`. /// </param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a POSIX account.</summary> public class DeleteRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. A reference to the POSIX account to update. POSIX accounts are identified by the project /// ID they are associated with. A reference to the POSIX account is in format /// `users/{user}/projects/{project}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The type of operating system associated with the account.</summary> [Google.Apis.Util.RequestParameterAttribute("operatingSystemType", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<OperatingSystemTypeEnum> OperatingSystemType { get; set; } /// <summary>The type of operating system associated with the account.</summary> public enum OperatingSystemTypeEnum { /// <summary> /// The operating system type associated with the user account information is unspecified. /// </summary> [Google.Apis.Util.StringValueAttribute("OPERATING_SYSTEM_TYPE_UNSPECIFIED")] OPERATINGSYSTEMTYPEUNSPECIFIED = 0, /// <summary>Linux user account information.</summary> [Google.Apis.Util.StringValueAttribute("LINUX")] LINUX = 1, /// <summary>Windows user account information.</summary> [Google.Apis.Util.StringValueAttribute("WINDOWS")] WINDOWS = 2, } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/projects/[^/]+$", }); RequestParameters.Add("operatingSystemType", new Google.Apis.Discovery.Parameter { Name = "operatingSystemType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>Gets the SshPublicKeys resource.</summary> public virtual SshPublicKeysResource SshPublicKeys { get; } /// <summary>The "sshPublicKeys" collection of methods.</summary> public class SshPublicKeysResource { private const string Resource = "sshPublicKeys"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SshPublicKeysResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Create an SSH public key</summary> /// <param name="body">The body of the request.</param> /// <param name="parent">Required. The unique ID for the user in format `users/{user}`.</param> public virtual CreateRequest Create(Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string parent) { return new CreateRequest(service, body, parent); } /// <summary>Create an SSH public key</summary> public class CreateRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary>Required. The unique ID for the user in format `users/{user}`.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+parent}/sshPublicKeys"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+$", }); } } /// <summary>Deletes an SSH public key.</summary> /// <param name="name"> /// Required. The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`. /// </param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes an SSH public key.</summary> public class DeleteRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); } } /// <summary>Retrieves an SSH public key.</summary> /// <param name="name"> /// Required. The fingerprint of the public key to retrieve. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`. /// </param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Retrieves an SSH public key.</summary> public class GetRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary> /// Required. The fingerprint of the public key to retrieve. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); } } /// <summary> /// Updates an SSH public key and returns the profile information. This method supports patch semantics. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="name"> /// Required. The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format `users/{user}/sshPublicKeys/{fingerprint}`. /// </param> public virtual PatchRequest Patch(Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string name) { return new PatchRequest(service, body, name); } /// <summary> /// Updates an SSH public key and returns the profile information. This method supports patch semantics. /// </summary> public class PatchRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary> /// Required. The fingerprint of the public key to update. Public keys are identified by their SHA-256 /// fingerprint. The fingerprint of the public key is in format /// `users/{user}/sshPublicKeys/{fingerprint}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Mask to control which fields get updated. Updates all if not present.</summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patch"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+name}"; /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+/sshPublicKeys/[^/]+$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary> /// Retrieves the profile information used for logging in to a virtual machine on Google Compute Engine. /// </summary> /// <param name="name">Required. The unique ID for the user in format `users/{user}`.</param> public virtual GetLoginProfileRequest GetLoginProfile(string name) { return new GetLoginProfileRequest(service, name); } /// <summary> /// Retrieves the profile information used for logging in to a virtual machine on Google Compute Engine. /// </summary> public class GetLoginProfileRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.LoginProfile> { /// <summary>Constructs a new GetLoginProfile request.</summary> public GetLoginProfileRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The unique ID for the user in format `users/{user}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>The type of operating system associated with the account.</summary> [Google.Apis.Util.RequestParameterAttribute("operatingSystemType", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<OperatingSystemTypeEnum> OperatingSystemType { get; set; } /// <summary>The type of operating system associated with the account.</summary> public enum OperatingSystemTypeEnum { /// <summary> /// The operating system type associated with the user account information is unspecified. /// </summary> [Google.Apis.Util.StringValueAttribute("OPERATING_SYSTEM_TYPE_UNSPECIFIED")] OPERATINGSYSTEMTYPEUNSPECIFIED = 0, /// <summary>Linux user account information.</summary> [Google.Apis.Util.StringValueAttribute("LINUX")] LINUX = 1, /// <summary>Windows user account information.</summary> [Google.Apis.Util.StringValueAttribute("WINDOWS")] WINDOWS = 2, } /// <summary>The project ID of the Google Cloud Platform project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Query)] public virtual string ProjectId { get; set; } /// <summary>A system ID for filtering the results of the request.</summary> [Google.Apis.Util.RequestParameterAttribute("systemId", Google.Apis.Util.RequestParameterType.Query)] public virtual string SystemId { get; set; } /// <summary>The view configures whether to retrieve security keys information.</summary> [Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<ViewEnum> View { get; set; } /// <summary>The view configures whether to retrieve security keys information.</summary> public enum ViewEnum { /// <summary>The default login profile view. The API defaults to the BASIC view.</summary> [Google.Apis.Util.StringValueAttribute("LOGIN_PROFILE_VIEW_UNSPECIFIED")] LOGINPROFILEVIEWUNSPECIFIED = 3, /// <summary>Includes POSIX and SSH key information.</summary> [Google.Apis.Util.StringValueAttribute("BASIC")] BASIC = 1, /// <summary>Include security key information for the user.</summary> [Google.Apis.Util.StringValueAttribute("SECURITY_KEY")] SECURITYKEY = 2, } /// <summary>Gets the method name.</summary> public override string MethodName => "getLoginProfile"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+name}/loginProfile"; /// <summary>Initializes GetLoginProfile parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+$", }); RequestParameters.Add("operatingSystemType", new Google.Apis.Discovery.Parameter { Name = "operatingSystemType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("systemId", new Google.Apis.Discovery.Parameter { Name = "systemId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("view", new Google.Apis.Discovery.Parameter { Name = "view", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Adds an SSH public key and returns the profile information. Default POSIX account information is set when no /// username and UID exist as part of the login profile. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent">The unique ID for the user in format `users/{user}`.</param> public virtual ImportSshPublicKeyRequest ImportSshPublicKey(Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string parent) { return new ImportSshPublicKeyRequest(service, body, parent); } /// <summary> /// Adds an SSH public key and returns the profile information. Default POSIX account information is set when no /// username and UID exist as part of the login profile. /// </summary> public class ImportSshPublicKeyRequest : CloudOSLoginBaseServiceRequest<Google.Apis.CloudOSLogin.v1alpha.Data.ImportSshPublicKeyResponse> { /// <summary>Constructs a new ImportSshPublicKey request.</summary> public ImportSshPublicKeyRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary>The unique ID for the user in format `users/{user}`.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>The project ID of the Google Cloud Platform project.</summary> [Google.Apis.Util.RequestParameterAttribute("projectId", Google.Apis.Util.RequestParameterType.Query)] public virtual string ProjectId { get; set; } /// <summary>The view configures whether to retrieve security keys information.</summary> [Google.Apis.Util.RequestParameterAttribute("view", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<ViewEnum> View { get; set; } /// <summary>The view configures whether to retrieve security keys information.</summary> public enum ViewEnum { /// <summary>The default login profile view. The API defaults to the BASIC view.</summary> [Google.Apis.Util.StringValueAttribute("LOGIN_PROFILE_VIEW_UNSPECIFIED")] LOGINPROFILEVIEWUNSPECIFIED = 3, /// <summary>Includes POSIX and SSH key information.</summary> [Google.Apis.Util.StringValueAttribute("BASIC")] BASIC = 1, /// <summary>Include security key information for the user.</summary> [Google.Apis.Util.StringValueAttribute("SECURITY_KEY")] SECURITYKEY = 2, } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudOSLogin.v1alpha.Data.SshPublicKey Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "importSshPublicKey"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1alpha/{+parent}:importSshPublicKey"; /// <summary>Initializes ImportSshPublicKey parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^users/[^/]+$", }); RequestParameters.Add("projectId", new Google.Apis.Discovery.Parameter { Name = "projectId", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("view", new Google.Apis.Discovery.Parameter { Name = "view", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.CloudOSLogin.v1alpha.Data { /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A response message for importing an SSH public key.</summary> public class ImportSshPublicKeyResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Detailed information about import results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual string Details { get; set; } /// <summary>The login profile information for the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("loginProfile")] public virtual LoginProfile LoginProfile { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// The user profile information used for logging in to a virtual machine on Google Compute Engine. /// </summary> public class LoginProfile : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. A unique user ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The list of POSIX accounts associated with the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("posixAccounts")] public virtual System.Collections.Generic.IList<PosixAccount> PosixAccounts { get; set; } /// <summary>The registered security key credentials for a user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("securityKeys")] public virtual System.Collections.Generic.IList<SecurityKey> SecurityKeys { get; set; } /// <summary>A map from SSH public key fingerprint to the associated key object.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sshPublicKeys")] public virtual System.Collections.Generic.IDictionary<string, SshPublicKey> SshPublicKeys { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The POSIX account information associated with a Google account.</summary> public class PosixAccount : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. A POSIX account identifier.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accountId")] public virtual string AccountId { get; set; } /// <summary>The GECOS (user information) entry for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gecos")] public virtual string Gecos { get; set; } /// <summary>The default group ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("gid")] public virtual System.Nullable<long> Gid { get; set; } /// <summary>The path to the home directory for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("homeDirectory")] public virtual string HomeDirectory { get; set; } /// <summary>Output only. The canonical resource name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The operating system type where this account applies.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operatingSystemType")] public virtual string OperatingSystemType { get; set; } /// <summary>Only one POSIX account can be marked as primary.</summary> [Newtonsoft.Json.JsonPropertyAttribute("primary")] public virtual System.Nullable<bool> Primary { get; set; } /// <summary>The path to the logic shell for this account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shell")] public virtual string Shell { get; set; } /// <summary> /// System identifier for which account the username or uid applies to. By default, the empty value is used. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("systemId")] public virtual string SystemId { get; set; } /// <summary>The user ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("uid")] public virtual System.Nullable<long> Uid { get; set; } /// <summary>The username of the POSIX account.</summary> [Newtonsoft.Json.JsonPropertyAttribute("username")] public virtual string Username { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The credential information for a Google registered security key.</summary> public class SecurityKey : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Hardware-backed private key text in SSH format.</summary> [Newtonsoft.Json.JsonPropertyAttribute("privateKey")] public virtual string PrivateKey { get; set; } /// <summary> /// Public key text in SSH format, defined by [RFC4253]("https://www.ietf.org/rfc/rfc4253.txt") section 6.6. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("publicKey")] public virtual string PublicKey { get; set; } /// <summary>The U2F protocol type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("universalTwoFactor")] public virtual UniversalTwoFactor UniversalTwoFactor { get; set; } /// <summary>The Web Authentication protocol type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("webAuthn")] public virtual WebAuthn WebAuthn { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The SSH public key information associated with a Google account.</summary> public class SshPublicKey : Google.Apis.Requests.IDirectResponseSchema { /// <summary>An expiration time in microseconds since epoch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expirationTimeUsec")] public virtual System.Nullable<long> ExpirationTimeUsec { get; set; } /// <summary>Output only. The SHA-256 fingerprint of the SSH public key.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fingerprint")] public virtual string Fingerprint { get; set; } /// <summary>Public key text in SSH format, defined by RFC4253 section 6.6.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual string Key { get; set; } /// <summary>Output only. The canonical resource name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Security key information specific to the U2F protocol.</summary> public class UniversalTwoFactor : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Application ID for the U2F protocol.</summary> [Newtonsoft.Json.JsonPropertyAttribute("appId")] public virtual string AppId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Security key information specific to the Web Authentication protocol.</summary> public class WebAuthn : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Relying party ID for Web Authentication.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rpId")] public virtual string RpId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPagingOperations. /// </summary> public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestPagingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestPagingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Paging = new PagingOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using IndexReader = Lucene.Net.Index.IndexReader; using ToStringUtils = Lucene.Net.Util.ToStringUtils; using Occur = Lucene.Net.Search.BooleanClause.Occur; namespace Lucene.Net.Search { /// <summary>A Query that matches documents matching boolean combinations of other /// queries, e.g. {@link TermQuery}s, {@link PhraseQuery}s or other /// BooleanQuerys. /// </summary> [Serializable] public class BooleanQuery:Query, System.ICloneable { [Serializable] private class AnonymousClassSimilarityDelegator:SimilarityDelegator { private void InitBlock(BooleanQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanQuery enclosingInstance; public BooleanQuery Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassSimilarityDelegator(BooleanQuery enclosingInstance, Lucene.Net.Search.Similarity Param1):base(Param1) { InitBlock(enclosingInstance); } public override float Coord(int overlap, int maxOverlap) { return 1.0f; } } private static int maxClauseCount = 1024; /// <summary>Thrown when an attempt is made to add more than {@link /// #GetMaxClauseCount()} clauses. This typically happens if /// a PrefixQuery, FuzzyQuery, WildcardQuery, or TermRangeQuery /// is expanded to many terms during search. /// </summary> [Serializable] public class TooManyClauses:System.SystemException { public override System.String Message { get { return "maxClauseCount is set to " + Lucene.Net.Search.BooleanQuery.maxClauseCount; } } public TooManyClauses() { } } /// <summary>Return the maximum number of clauses permitted, 1024 by default. /// Attempts to add more than the permitted number of clauses cause {@link /// TooManyClauses} to be thrown. /// </summary> /// <seealso cref="SetMaxClauseCount(int)"> /// </seealso> public static int GetMaxClauseCount() { return maxClauseCount; } /// <summary> Set the maximum number of clauses permitted per BooleanQuery. /// Default value is 1024. /// </summary> public static void SetMaxClauseCount(int maxClauseCount) { if (maxClauseCount < 1) throw new System.ArgumentException("maxClauseCount must be >= 1"); BooleanQuery.maxClauseCount = maxClauseCount; } private SupportClass.EquatableList<BooleanClause> clauses = new SupportClass.EquatableList<BooleanClause>(); private bool disableCoord; /// <summary>Constructs an empty boolean query. </summary> public BooleanQuery() { } /// <summary>Constructs an empty boolean query. /// /// {@link Similarity#Coord(int,int)} may be disabled in scoring, as /// appropriate. For example, this score factor does not make sense for most /// automatically generated queries, like {@link WildcardQuery} and {@link /// FuzzyQuery}. /// /// </summary> /// <param name="disableCoord">disables {@link Similarity#Coord(int,int)} in scoring. /// </param> public BooleanQuery(bool disableCoord) { this.disableCoord = disableCoord; } /// <summary>Returns true iff {@link Similarity#Coord(int,int)} is disabled in /// scoring for this query instance. /// </summary> /// <seealso cref="BooleanQuery(boolean)"> /// </seealso> public virtual bool IsCoordDisabled() { return disableCoord; } // Implement coord disabling. // Inherit javadoc. public override Similarity GetSimilarity(Searcher searcher) { Similarity result = base.GetSimilarity(searcher); if (disableCoord) { // disable coord as requested result = new AnonymousClassSimilarityDelegator(this, result); } return result; } /// <summary> Specifies a minimum number of the optional BooleanClauses /// which must be satisfied. /// /// <p/> /// By default no optional clauses are necessary for a match /// (unless there are no required clauses). If this method is used, /// then the specified number of clauses is required. /// <p/> /// <p/> /// Use of this method is totally independent of specifying that /// any specific clauses are required (or prohibited). This number will /// only be compared against the number of matching optional clauses. /// <p/> /// <p/> /// EXPERT NOTE: Using this method may force collecting docs in order, /// regardless of whether setAllowDocsOutOfOrder(true) has been called. /// <p/> /// /// </summary> /// <param name="min">the number of optional clauses that must match /// </param> /// <seealso cref="setAllowDocsOutOfOrder"> /// </seealso> public virtual void SetMinimumNumberShouldMatch(int min) { this.minNrShouldMatch = min; } protected internal int minNrShouldMatch = 0; /// <summary> Gets the minimum number of the optional BooleanClauses /// which must be satisifed. /// </summary> public virtual int GetMinimumNumberShouldMatch() { return minNrShouldMatch; } /// <summary>Adds a clause to a boolean query. /// /// </summary> /// <throws> TooManyClauses if the new number of clauses exceeds the maximum clause number </throws> /// <seealso cref="GetMaxClauseCount()"> /// </seealso> public virtual void Add(Query query, BooleanClause.Occur occur) { Add(new BooleanClause(query, occur)); } /// <summary>Adds a clause to a boolean query.</summary> /// <throws> TooManyClauses if the new number of clauses exceeds the maximum clause number </throws> /// <seealso cref="GetMaxClauseCount()"> /// </seealso> public virtual void Add(BooleanClause clause) { if (clauses.Count >= maxClauseCount) throw new TooManyClauses(); clauses.Add(clause); } /// <summary>Returns the set of clauses in this query. </summary> public virtual BooleanClause[] GetClauses() { return (BooleanClause[]) clauses.ToArray(); } /// <summary>Returns the list of clauses in this query. </summary> public virtual System.Collections.IList Clauses() { return clauses; } /// <summary> Expert: the Weight for BooleanQuery, used to /// normalize, score and explain these queries. /// /// <p/>NOTE: this API and implementation is subject to /// change suddenly in the next release.<p/> /// </summary> [Serializable] protected internal class BooleanWeight:Weight { private void InitBlock(BooleanQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanQuery enclosingInstance; public BooleanQuery Enclosing_Instance { get { return enclosingInstance; } } /// <summary>The Similarity implementation. </summary> protected internal Similarity similarity; protected internal System.Collections.ArrayList weights; public BooleanWeight(BooleanQuery enclosingInstance, Searcher searcher) { InitBlock(enclosingInstance); this.similarity = Enclosing_Instance.GetSimilarity(searcher); weights = new System.Collections.ArrayList(Enclosing_Instance.clauses.Count); for (int i = 0; i < Enclosing_Instance.clauses.Count; i++) { BooleanClause c = (BooleanClause) Enclosing_Instance.clauses[i]; weights.Add(c.GetQuery().CreateWeight(searcher)); } } public override Query GetQuery() { return Enclosing_Instance; } public override float GetValue() { return Enclosing_Instance.GetBoost(); } public override float SumOfSquaredWeights() { float sum = 0.0f; for (int i = 0; i < weights.Count; i++) { BooleanClause c = (BooleanClause) Enclosing_Instance.clauses[i]; Weight w = (Weight) weights[i]; // call sumOfSquaredWeights for all clauses in case of side effects float s = w.SumOfSquaredWeights(); // sum sub weights if (!c.IsProhibited()) // only add to sum for non-prohibited clauses sum += s; } sum *= Enclosing_Instance.GetBoost() * Enclosing_Instance.GetBoost(); // boost each sub-weight return sum; } public override void Normalize(float norm) { norm *= Enclosing_Instance.GetBoost(); // incorporate boost for (System.Collections.IEnumerator iter = weights.GetEnumerator(); iter.MoveNext(); ) { Weight w = (Weight) iter.Current; // normalize all clauses, (even if prohibited in case of side affects) w.Normalize(norm); } } public override Explanation Explain(IndexReader reader, int doc) { int minShouldMatch = Enclosing_Instance.GetMinimumNumberShouldMatch(); ComplexExplanation sumExpl = new ComplexExplanation(); sumExpl.SetDescription("sum of:"); int coord = 0; int maxCoord = 0; float sum = 0.0f; bool fail = false; int shouldMatchCount = 0; for (System.Collections.IEnumerator wIter = weights.GetEnumerator(), cIter = Enclosing_Instance.clauses.GetEnumerator(); wIter.MoveNext(); ) { cIter.MoveNext(); Weight w = (Weight)wIter.Current; BooleanClause c = (BooleanClause) cIter.Current; if (w.Scorer(reader, true, true) == null) { continue; } Explanation e = w.Explain(reader, doc); if (!c.IsProhibited()) maxCoord++; if (e.IsMatch()) { if (!c.IsProhibited()) { sumExpl.AddDetail(e); sum += e.GetValue(); coord++; } else { Explanation r = new Explanation(0.0f, "match on prohibited clause (" + c.GetQuery().ToString() + ")"); r.AddDetail(e); sumExpl.AddDetail(r); fail = true; } if (c.GetOccur() == Occur.SHOULD) shouldMatchCount++; } else if (c.IsRequired()) { Explanation r = new Explanation(0.0f, "no match on required clause (" + c.GetQuery().ToString() + ")"); r.AddDetail(e); sumExpl.AddDetail(r); fail = true; } } if (fail) { System.Boolean tempAux = false; sumExpl.SetMatch(tempAux); sumExpl.SetValue(0.0f); sumExpl.SetDescription("Failure to meet condition(s) of required/prohibited clause(s)"); return sumExpl; } else if (shouldMatchCount < minShouldMatch) { System.Boolean tempAux2 = false; sumExpl.SetMatch(tempAux2); sumExpl.SetValue(0.0f); sumExpl.SetDescription("Failure to match minimum number " + "of optional clauses: " + minShouldMatch); return sumExpl; } sumExpl.SetMatch(0 < coord?true:false); sumExpl.SetValue(sum); float coordFactor = similarity.Coord(coord, maxCoord); if (coordFactor == 1.0f) // coord is no-op return sumExpl; // eliminate wrapper else { ComplexExplanation result = new ComplexExplanation(sumExpl.IsMatch(), sum * coordFactor, "product of:"); result.AddDetail(sumExpl); result.AddDetail(new Explanation(coordFactor, "coord(" + coord + "/" + maxCoord + ")")); return result; } } public override Scorer Scorer(IndexReader reader, bool scoreDocsInOrder, bool topScorer) { System.Collections.IList required = new System.Collections.ArrayList(); System.Collections.IList prohibited = new System.Collections.ArrayList(); System.Collections.IList optional = new System.Collections.ArrayList(); for (System.Collections.IEnumerator wIter = weights.GetEnumerator(), cIter = Enclosing_Instance.clauses.GetEnumerator(); wIter.MoveNext(); ) { cIter.MoveNext(); Weight w = (Weight) wIter.Current; BooleanClause c = (BooleanClause) cIter.Current; Scorer subScorer = w.Scorer(reader, true, false); if (subScorer == null) { if (c.IsRequired()) { return null; } } else if (c.IsRequired()) { required.Add(subScorer); } else if (c.IsProhibited()) { prohibited.Add(subScorer); } else { optional.Add(subScorer); } } // Check if we can return a BooleanScorer scoreDocsInOrder |= !Lucene.Net.Search.BooleanQuery.allowDocsOutOfOrder; // until it is removed, factor in the static setting. if (!scoreDocsInOrder && topScorer && required.Count == 0 && prohibited.Count < 32) { return new BooleanScorer(similarity, Enclosing_Instance.minNrShouldMatch, optional, prohibited); } if (required.Count == 0 && optional.Count == 0) { // no required and optional clauses. return null; } else if (optional.Count < Enclosing_Instance.minNrShouldMatch) { // either >1 req scorer, or there are 0 req scorers and at least 1 // optional scorer. Therefore if there are not enough optional scorers // no documents will be matched by the query return null; } // Return a BooleanScorer2 return new BooleanScorer2(similarity, Enclosing_Instance.minNrShouldMatch, required, prohibited, optional); } public override bool ScoresDocsOutOfOrder() { int numProhibited = 0; for (System.Collections.IEnumerator cIter = Enclosing_Instance.clauses.GetEnumerator(); cIter.MoveNext(); ) { BooleanClause c = (BooleanClause) cIter.Current; if (c.IsRequired()) { return false; // BS2 (in-order) will be used by scorer() } else if (c.IsProhibited()) { ++numProhibited; } } if (numProhibited > 32) { // cannot use BS return false; } // scorer() will return an out-of-order scorer if requested. return true; } } /// <summary> Whether hit docs may be collected out of docid order. /// /// </summary> /// <deprecated> this will not be needed anymore, as /// {@link Weight#ScoresDocsOutOfOrder()} is used. /// </deprecated> [Obsolete("this will not be needed anymore, as Weight.ScoresDocsOutOfOrder() is used.")] private static bool allowDocsOutOfOrder = true; /// <summary> Expert: Indicates whether hit docs may be collected out of docid order. /// /// <p/> /// Background: although the contract of the Scorer class requires that /// documents be iterated in order of doc id, this was not true in early /// versions of Lucene. Many pieces of functionality in the current Lucene code /// base have undefined behavior if this contract is not upheld, but in some /// specific simple cases may be faster. (For example: disjunction queries with /// less than 32 prohibited clauses; This setting has no effect for other /// queries.) /// <p/> /// /// <p/> /// Specifics: By setting this option to true, docid N might be scored for a /// single segment before docid N-1. Across multiple segments, docs may be /// scored out of order regardless of this setting - it only applies to scoring /// a single segment. /// /// Being static, this setting is system wide. /// <p/> /// /// </summary> /// <deprecated> this is not needed anymore, as /// {@link Weight#ScoresDocsOutOfOrder()} is used. /// </deprecated> [Obsolete("this is not needed anymore, as Weight.ScoresDocsOutOfOrder() is used.")] public static void SetAllowDocsOutOfOrder(bool allow) { allowDocsOutOfOrder = allow; } /// <summary> Whether hit docs may be collected out of docid order. /// /// </summary> /// <seealso cref="SetAllowDocsOutOfOrder(boolean)"> /// </seealso> /// <deprecated> this is not needed anymore, as /// {@link Weight#ScoresDocsOutOfOrder()} is used. /// </deprecated> [Obsolete("this is not needed anymore, as Weight.ScoresDocsOutOfOrder() is used.")] public static bool GetAllowDocsOutOfOrder() { return allowDocsOutOfOrder; } /// <deprecated> Use {@link #SetAllowDocsOutOfOrder(boolean)} instead. /// </deprecated> [Obsolete("Use SetAllowDocsOutOfOrder(bool) instead.")] public static void SetUseScorer14(bool use14) { SetAllowDocsOutOfOrder(use14); } /// <deprecated> Use {@link #GetAllowDocsOutOfOrder()} instead. /// </deprecated> [Obsolete("Use GetAllowDocsOutOfOrder() instead.")] public static bool GetUseScorer14() { return GetAllowDocsOutOfOrder(); } public override Weight CreateWeight(Searcher searcher) { return new BooleanWeight(this, searcher); } public override Query Rewrite(IndexReader reader) { if (minNrShouldMatch == 0 && clauses.Count == 1) { // optimize 1-clause queries BooleanClause c = (BooleanClause) clauses[0]; if (!c.IsProhibited()) { // just return clause Query query = c.GetQuery().Rewrite(reader); // rewrite first if (GetBoost() != 1.0f) { // incorporate boost if (query == c.GetQuery()) // if rewrite was no-op query = (Query) query.Clone(); // then clone before boost query.SetBoost(GetBoost() * query.GetBoost()); } return query; } } BooleanQuery clone = null; // recursively rewrite for (int i = 0; i < clauses.Count; i++) { BooleanClause c = (BooleanClause) clauses[i]; Query query = c.GetQuery().Rewrite(reader); if (query != c.GetQuery()) { // clause rewrote: must clone if (clone == null) clone = (BooleanQuery) this.Clone(); clone.clauses[i] = new BooleanClause(query, c.GetOccur()); } } if (clone != null) { return clone; // some clauses rewrote } else return this; // no clauses rewrote } // inherit javadoc public override void ExtractTerms(System.Collections.Hashtable terms) { for (System.Collections.IEnumerator i = clauses.GetEnumerator(); i.MoveNext(); ) { BooleanClause clause = (BooleanClause) i.Current; clause.GetQuery().ExtractTerms(terms); } } public override System.Object Clone() { BooleanQuery clone = (BooleanQuery) base.Clone(); clone.clauses = (SupportClass.EquatableList<BooleanClause>) this.clauses.Clone(); return clone; } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); bool needParens = (GetBoost() != 1.0) || (GetMinimumNumberShouldMatch() > 0); if (needParens) { buffer.Append("("); } for (int i = 0; i < clauses.Count; i++) { BooleanClause c = (BooleanClause) clauses[i]; if (c.IsProhibited()) buffer.Append("-"); else if (c.IsRequired()) buffer.Append("+"); Query subQuery = c.GetQuery(); if (subQuery != null) { if (subQuery is BooleanQuery) { // wrap sub-bools in parens buffer.Append("("); buffer.Append(subQuery.ToString(field)); buffer.Append(")"); } else { buffer.Append(subQuery.ToString(field)); } } else { buffer.Append("null"); } if (i != clauses.Count - 1) buffer.Append(" "); } if (needParens) { buffer.Append(")"); } if (GetMinimumNumberShouldMatch() > 0) { buffer.Append('~'); buffer.Append(GetMinimumNumberShouldMatch()); } if (GetBoost() != 1.0f) { buffer.Append(ToStringUtils.Boost(GetBoost())); } return buffer.ToString(); } /// <summary>Returns true iff <code>o</code> is equal to this. </summary> public override bool Equals(System.Object o) { if (!(o is BooleanQuery)) return false; BooleanQuery other = (BooleanQuery)o; return (this.GetBoost() == other.GetBoost()) && this.clauses.Equals(other.clauses) && this.GetMinimumNumberShouldMatch() == other.GetMinimumNumberShouldMatch() && this.disableCoord == other.disableCoord; } /// <summary>Returns a hash code value for this object.</summary> public override int GetHashCode() { return BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0) ^ clauses.GetHashCode() + GetMinimumNumberShouldMatch() + (disableCoord ? 17 : 0); } } }
using System.Linq; using System.Threading.Tasks; using NJsonSchema; using Xunit; namespace NSwag.Core.Tests.Serialization { public class RequestBodySerializationTests { [Fact] public async Task When_request_body_is_added_then_serialized_correctly_in_Swagger() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.Swagger2); document = await SwaggerDocument.FromJsonAsync(json); //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.Equal("foo", requestBody.Name); } [Fact] public async Task When_request_body_is_added_then_serialized_correctly_in_OpenApi() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.Equal("foo", requestBody.Name); } [Fact] public async Task When_body_parameter_is_changed_then_request_body_IsRequired_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); parameter.IsRequired = true; //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.True(requestBody.IsRequired); Assert.True(parameter.IsRequired); } [Fact] public async Task When_body_parameter_is_changed_then_request_body_Name_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); parameter.Name = parameter.Name + "123"; //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.Equal("foo123", requestBody.Name); } [Fact] public async Task When_body_parameter_is_changed_then_request_body_Schema_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); parameter.Schema = new JsonSchema4 { Title = "blub" }; //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.Equal("blub", requestBody.Content["application/json"].Schema.Title); } [Fact] public async Task When_body_parameter_is_changed_then_request_body_Description_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); parameter.Description = parameter.Description + "123"; //// Assert var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; Assert.Equal("bar123", requestBody.Description); } [Fact] public async Task When_request_body_is_changed_then_body_parameter_Name_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; requestBody.Name = requestBody.Name + "123"; //// Assert var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); Assert.Equal("foo123", parameter.Name); } [Fact] public async Task When_request_body_is_changed_then_body_parameter_IsRequired_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; requestBody.IsRequired = true; //// Assert var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); Assert.True(parameter.IsRequired); Assert.True(requestBody.IsRequired); } [Fact] public async Task When_request_body_is_changed_then_body_parameter_Content_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; requestBody.Content["application/json"] = new OpenApiMediaType { Schema = new JsonSchema4 { Title = "blub" } }; //// Assert var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); Assert.Equal("blub", parameter.Schema.Title); } [Fact] public async Task When_request_body_is_changed_then_body_parameter_Description_is_updated() { //// Arrange var document = CreateDocument(); //// Act var json = document.ToJson(SchemaType.OpenApi3); document = await SwaggerDocument.FromJsonAsync(json); var requestBody = document.Paths["/baz"][SwaggerOperationMethod.Get].RequestBody; requestBody.Description = requestBody.Description + "123"; //// Assert var parameter = document.Paths["/baz"][SwaggerOperationMethod.Get].Parameters .Single(p => p.Kind == SwaggerParameterKind.Body); Assert.Equal("bar123", parameter.Description); } private static SwaggerDocument CreateDocument() { var schema = new JsonSchema4 { Type = JsonObjectType.String }; var document = new SwaggerDocument { Paths = { { "/baz", new SwaggerPathItem { { SwaggerOperationMethod.Get, new SwaggerOperation { RequestBody = new OpenApiRequestBody { Name = "foo", Description = "bar", Content = { { "application/json", new OpenApiMediaType { Schema = new JsonSchema4 { Reference = schema } } } } } } } } } }, Definitions = { { "Abc", schema } } }; return document; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================================= ** ** Class: RegistrationServices ** ** ** Purpose: This class provides services for registering and unregistering ** a managed server for use by COM. ** ** ** ** ** Change the way how to register and unregister a managed server ** =============================================================================*/ namespace System.Runtime.InteropServices { using System; using System.Collections; using System.IO; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; [Flags] public enum RegistrationClassContext { InProcessServer = 0x1, InProcessHandler = 0x2, LocalServer = 0x4, InProcessServer16 = 0x8, RemoteServer = 0x10, InProcessHandler16 = 0x20, Reserved1 = 0x40, Reserved2 = 0x80, Reserved3 = 0x100, Reserved4 = 0x200, NoCodeDownload = 0x400, Reserved5 = 0x800, NoCustomMarshal = 0x1000, EnableCodeDownload = 0x2000, NoFailureLog = 0x4000, DisableActivateAsActivator = 0x8000, EnableActivateAsActivator = 0x10000, FromDefaultContext = 0x20000 } [Flags] public enum RegistrationConnectionType { SingleUse = 0, MultipleUse = 1, MultiSeparate = 2, Suspended = 4, Surrogate = 8, } [Guid("475E398F-8AFA-43a7-A3BE-F4EF8D6787C9")] [ClassInterface(ClassInterfaceType.None)] [System.Runtime.InteropServices.ComVisible(true)] public class RegistrationServices : IRegistrationServices { #region Constants private const String strManagedCategoryGuid = "{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}"; private const String strDocStringPrefix = ""; private const String strManagedTypeThreadingModel = "Both"; private const String strComponentCategorySubKey = "Component Categories"; private const String strManagedCategoryDescription = ".NET Category"; private const String strImplementedCategoriesSubKey = "Implemented Categories"; private const String strMsCorEEFileName = "mscoree.dll"; private const String strRecordRootName = "Record"; private const String strClsIdRootName = "CLSID"; private const String strTlbRootName = "TypeLib"; private static Guid s_ManagedCategoryGuid = new Guid(strManagedCategoryGuid); #endregion #region IRegistrationServices [System.Security.SecurityCritical] // auto-generated_required [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] public virtual bool RegisterAssembly(Assembly assembly, AssemblyRegistrationFlags flags) { // Validate the arguments. if (assembly == null) throw new ArgumentNullException("assembly"); if (assembly.ReflectionOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly")); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; if (rtAssembly == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly")); // Retrieve the assembly names. String strAsmName = assembly.FullName; if (strAsmName == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmName")); // Retrieve the assembly codebase. String strAsmCodeBase = null; if ((flags & AssemblyRegistrationFlags.SetCodeBase) != 0) { strAsmCodeBase = rtAssembly.GetCodeBase(false); if (strAsmCodeBase == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoAsmCodeBase")); } // Go through all the registerable types in the assembly and register them. Type[] aTypes = GetRegistrableTypesInAssembly(assembly); int NumTypes = aTypes.Length; String strAsmVersion = rtAssembly.GetVersion().ToString(); // Retrieve the runtime version used to build the assembly. String strRuntimeVersion = assembly.ImageRuntimeVersion; for (int cTypes = 0; cTypes < NumTypes; cTypes++) { if (IsRegisteredAsValueType(aTypes[cTypes])) RegisterValueType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion); else if (TypeRepresentsComType(aTypes[cTypes])) RegisterComImportedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion); else RegisterManagedType(aTypes[cTypes], strAsmName, strAsmVersion, strAsmCodeBase, strRuntimeVersion); CallUserDefinedRegistrationMethod(aTypes[cTypes], true); } // If this assembly has the PIA attribute, then register it as a PIA. Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute), false); int NumPIAAttrs = aPIAAttrs.Length; for (int cPIAAttrs = 0; cPIAAttrs < NumPIAAttrs; cPIAAttrs++) RegisterPrimaryInteropAssembly(rtAssembly, strAsmCodeBase, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]); // Return value indicating if we actually registered any types. if (aTypes.Length > 0 || NumPIAAttrs > 0) return true; else return false; } [System.Security.SecurityCritical] // auto-generated_required public virtual bool UnregisterAssembly(Assembly assembly) { // Validate the arguments. if (assembly == null) throw new ArgumentNullException("assembly"); if (assembly.ReflectionOnly) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsmLoadedForReflectionOnly")); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; if (rtAssembly == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly")); bool bAllVersionsGone = true; // Go through all the registrable types in the assembly and register them. Type[] aTypes = GetRegistrableTypesInAssembly(assembly); int NumTypes = aTypes.Length; // Retrieve the assembly version String strAsmVersion = rtAssembly.GetVersion().ToString(); for (int cTypes = 0;cTypes < NumTypes;cTypes++) { CallUserDefinedRegistrationMethod(aTypes[cTypes], false); if (IsRegisteredAsValueType(aTypes[cTypes])) { if (!UnregisterValueType(aTypes[cTypes], strAsmVersion)) bAllVersionsGone = false; } else if (TypeRepresentsComType(aTypes[cTypes])) { if (!UnregisterComImportedType(aTypes[cTypes], strAsmVersion)) bAllVersionsGone = false; } else { if (!UnregisterManagedType(aTypes[cTypes], strAsmVersion)) bAllVersionsGone = false; } } // If this assembly has the PIA attribute, then unregister it as a PIA. Object[] aPIAAttrs = assembly.GetCustomAttributes(typeof(PrimaryInteropAssemblyAttribute),false); int NumPIAAttrs = aPIAAttrs.Length; if (bAllVersionsGone) { for (int cPIAAttrs = 0;cPIAAttrs < NumPIAAttrs;cPIAAttrs++) UnregisterPrimaryInteropAssembly(assembly, (PrimaryInteropAssemblyAttribute)aPIAAttrs[cPIAAttrs]); } // Return value indicating if we actually un-registered any types. if (aTypes.Length > 0 || NumPIAAttrs > 0) return true; else return false; } [System.Security.SecurityCritical] // auto-generated_required public virtual Type[] GetRegistrableTypesInAssembly(Assembly assembly) { // Validate the arguments. if (assembly == null) throw new ArgumentNullException("assembly"); Contract.EndContractBlock(); if (!(assembly is RuntimeAssembly)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); // Retrieve the list of types in the assembly. Type[] aTypes = assembly.GetExportedTypes(); int NumTypes = aTypes.Length; // Create an array list that will be filled in. ArrayList TypeList = new ArrayList(); // Register all the types that require registration. for (int cTypes = 0; cTypes < NumTypes; cTypes++) { Type CurrentType = aTypes[cTypes]; if (TypeRequiresRegistration(CurrentType)) TypeList.Add(CurrentType); } // Copy the array list to an array and return it. Type[] RetArray = new Type[TypeList.Count]; TypeList.CopyTo(RetArray); return RetArray; } [System.Security.SecurityCritical] // auto-generated_required public virtual String GetProgIdForType(Type type) { return Marshal.GenerateProgIdForType(type); } [System.Security.SecurityCritical] // auto-generated_required public virtual void RegisterTypeForComClients(Type type, ref Guid g) { #if FEATURE_COMINTEROP_MANAGED_ACTIVATION if(type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if((type as RuntimeType) == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type"); if(!TypeRequiresRegistration(type)) throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type"); // Call the native method to do CoRegisterClassObject RegisterTypeForComClientsNative(type, ref g); #else // FEATURE_COMINTEROP_MANAGED_ACTIVATION throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed"); // @ #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION } public virtual Guid GetManagedCategoryGuid() { return s_ManagedCategoryGuid; } [System.Security.SecurityCritical] // auto-generated_required public virtual bool TypeRequiresRegistration(Type type) { return TypeRequiresRegistrationHelper(type); } [System.Security.SecuritySafeCritical] // auto-generated public virtual bool TypeRepresentsComType(Type type) { // If the type is not a COM import, then it does not represent a COM type. if (!type.IsCOMObject) return false; // If it is marked as tdImport, then it represents a COM type directly. if (type.IsImport) return true; // If the type is derived from a tdImport class and has the same GUID as the // imported class, then it represents a COM type. Type baseComImportType = GetBaseComImportType(type); Contract.Assert(baseComImportType != null, "baseComImportType != null"); if (Marshal.GenerateGuidForType(type) == Marshal.GenerateGuidForType(baseComImportType)) return true; return false; } #endregion #region Public methods not on IRegistrationServices [System.Security.SecurityCritical] // auto-generated_required [ComVisible(false)] public virtual int RegisterTypeForComClients(Type type, RegistrationClassContext classContext, RegistrationConnectionType flags) { #if FEATURE_COMINTEROP_MANAGED_ACTIVATION if (type == null) throw new ArgumentNullException("type"); Contract.EndContractBlock(); if ((type as RuntimeType) == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"),"type"); if (!TypeRequiresRegistration(type)) throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustBeComCreatable"),"type"); // Call the native method to do CoRegisterClassObject return RegisterTypeForComClientsExNative(type, classContext, flags); #else // FEATURE_COMINTEROP_MANAGED_ACTIVATION throw new NotImplementedException("CoreCLR_REMOVED -- managed activation removed"); // @ #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION } [System.Security.SecurityCritical] // auto-generated_required [ComVisible(false)] public virtual void UnregisterTypeForComClients(int cookie) { // Call the native method to do CoRevokeClassObject. CoRevokeClassObject(cookie); } #endregion #region Internal helpers [System.Security.SecurityCritical] // auto-generated_required internal static bool TypeRequiresRegistrationHelper(Type type) { // If the type is not a class or a value class, then it does not get registered. if (!type.IsClass && !type.IsValueType) return false; // If the type is abstract then it does not get registered. if (type.IsAbstract) return false; // If the does not have a public default constructor then is not creatable from COM so // it does not require registration unless it is a value class. if (!type.IsValueType && type.GetConstructor(BindingFlags.Instance | BindingFlags.Public,null,new Type[0],null) == null) return false; // All other conditions are met so check to see if the type is visible from COM. return Marshal.IsTypeVisibleFromCom(type); } #endregion #region Private helpers [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void RegisterValueType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // Retrieve some information that will be used during the registration process. String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; // Create the HKEY_CLASS_ROOT\Record key. using (RegistryKey RecordRootKey = Registry.ClassesRoot.CreateSubKey(strRecordRootName)) { // Create the HKEY_CLASS_ROOT\Record\<RecordID> key. using (RegistryKey RecordKey = RecordRootKey.CreateSubKey(strRecordId)) { // Create the HKEY_CLASS_ROOT\Record\<RecordId>\<version> key. using (RegistryKey RecordVersionKey = RecordKey.CreateSubKey(strAsmVersion)) { // Set the class value. RecordVersionKey.SetValue("Class", type.FullName); // Set the assembly value. RecordVersionKey.SetValue("Assembly", strAsmName); // Set the runtime version value. RecordVersionKey.SetValue("RuntimeVersion", strRuntimeVersion); // Set the assembly code base value if a code base was specified. if (strAsmCodeBase != null) RecordVersionKey.SetValue("CodeBase", strAsmCodeBase); } } } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void RegisterManagedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // // Retrieve some information that will be used during the registration process. // String strDocString = strDocStringPrefix + type.FullName; String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; String strProgId = GetProgIdForType(type); // // Write the actual type information in the registry. // if (strProgId != String.Empty) { // Create the HKEY_CLASS_ROOT\<wzProgId> key. using (RegistryKey TypeNameKey = Registry.ClassesRoot.CreateSubKey(strProgId)) { TypeNameKey.SetValue("", strDocString); // Create the HKEY_CLASS_ROOT\<wzProgId>\CLSID key. using (RegistryKey ProgIdClsIdKey = TypeNameKey.CreateSubKey("CLSID")) { ProgIdClsIdKey.SetValue("", strClsId); } } } // Create the HKEY_CLASS_ROOT\CLSID key. using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName)) { // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key. using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId)) { ClsIdKey.SetValue("", strDocString); // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key. using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32")) { InProcServerKey.SetValue("", strMsCorEEFileName); InProcServerKey.SetValue("ThreadingModel", strManagedTypeThreadingModel); InProcServerKey.SetValue("Class", type.FullName); InProcServerKey.SetValue("Assembly", strAsmName); InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion); if (strAsmCodeBase != null) InProcServerKey.SetValue("CodeBase", strAsmCodeBase); // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion)) { VersionSubKey.SetValue("Class", type.FullName); VersionSubKey.SetValue("Assembly", strAsmName); VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion); if (strAsmCodeBase != null) VersionSubKey.SetValue("CodeBase", strAsmCodeBase); } if (strProgId != String.Empty) { // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProdId key. using (RegistryKey ProgIdKey = ClsIdKey.CreateSubKey("ProgId")) { ProgIdKey.SetValue("", strProgId); } } } // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key. using (RegistryKey CategoryKey = ClsIdKey.CreateSubKey(strImplementedCategoriesSubKey)) { using (RegistryKey ManagedCategoryKey = CategoryKey.CreateSubKey(strManagedCategoryGuid)) {} } } } // // Ensure that the managed category exists. // EnsureManagedCategoryExists(); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void RegisterComImportedType(Type type, String strAsmName, String strAsmVersion, String strAsmCodeBase, String strRuntimeVersion) { // Retrieve some information that will be used during the registration process. String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; // Create the HKEY_CLASS_ROOT\CLSID key. using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.CreateSubKey(strClsIdRootName)) { // Create the HKEY_CLASS_ROOT\CLSID\<CLSID> key. using (RegistryKey ClsIdKey = ClsIdRootKey.CreateSubKey(strClsId)) { // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key. using (RegistryKey InProcServerKey = ClsIdKey.CreateSubKey("InprocServer32")) { // Set the class value. InProcServerKey.SetValue("Class", type.FullName); // Set the assembly value. InProcServerKey.SetValue("Assembly", strAsmName); // Set the runtime version value. InProcServerKey.SetValue("RuntimeVersion", strRuntimeVersion); // Set the assembly code base value if a code base was specified. if (strAsmCodeBase != null) InProcServerKey.SetValue("CodeBase", strAsmCodeBase); // Create the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> subkey using (RegistryKey VersionSubKey = InProcServerKey.CreateSubKey(strAsmVersion)) { VersionSubKey.SetValue("Class", type.FullName); VersionSubKey.SetValue("Assembly", strAsmName); VersionSubKey.SetValue("RuntimeVersion", strRuntimeVersion); if (strAsmCodeBase != null) VersionSubKey.SetValue("CodeBase", strAsmCodeBase); } } } } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private bool UnregisterValueType(Type type, String strAsmVersion) { bool bAllVersionsGone = true; // Try to open the HKEY_CLASS_ROOT\Record key. String strRecordId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; using (RegistryKey RecordRootKey = Registry.ClassesRoot.OpenSubKey(strRecordRootName, true)) { if (RecordRootKey != null) { // Open the HKEY_CLASS_ROOT\Record\{RecordId} key. using (RegistryKey RecordKey = RecordRootKey.OpenSubKey(strRecordId,true)) { if (RecordKey != null) { using (RegistryKey VersionSubKey = RecordKey.OpenSubKey(strAsmVersion,true)) { if (VersionSubKey != null) { // Delete the values we created. VersionSubKey.DeleteValue("Assembly",false); VersionSubKey.DeleteValue("Class",false); VersionSubKey.DeleteValue("CodeBase",false); VersionSubKey.DeleteValue("RuntimeVersion",false); // delete the version sub key if no value or subkeys under it if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0)) RecordKey.DeleteSubKey(strAsmVersion); } } // If there are sub keys left then there are versions left. if (RecordKey.SubKeyCount != 0) bAllVersionsGone = false; // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record\{RecordId}. if ((RecordKey.SubKeyCount == 0) && (RecordKey.ValueCount == 0)) RecordRootKey.DeleteSubKey(strRecordId); } } // If there are no other values or subkeys then we can delete the HKEY_CLASS_ROOT\Record. if ((RecordRootKey.SubKeyCount == 0) && (RecordRootKey.ValueCount == 0)) Registry.ClassesRoot.DeleteSubKey(strRecordRootName); } } return bAllVersionsGone; } // UnregisterManagedType // // Return : // true: All versions are gone. // false: Some versions are still left in registry [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private bool UnregisterManagedType(Type type,String strAsmVersion) { bool bAllVersionsGone = true; // // Create the CLSID string. // String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; String strProgId = GetProgIdForType(type); // // Remove the entries under HKEY_CLASS_ROOT\CLSID key. // using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true)) { if (ClsIdRootKey != null) { // // Remove the entries under HKEY_CLASS_ROOT\CLSID\<CLSID> key. // using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true)) { if (ClsIdKey != null) { // // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32 key. // using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true)) { if (InProcServerKey != null) { // // Remove the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InprocServer32\<Version> // using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion, true)) { if (VersionSubKey != null) { // Delete the values we created VersionSubKey.DeleteValue("Assembly",false); VersionSubKey.DeleteValue("Class",false); VersionSubKey.DeleteValue("RuntimeVersion",false); VersionSubKey.DeleteValue("CodeBase",false); // If there are no other values or subkeys then we can delete the VersionSubKey. if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0)) InProcServerKey.DeleteSubKey(strAsmVersion); } } // If there are sub keys left then there are versions left. if (InProcServerKey.SubKeyCount != 0) bAllVersionsGone = false; // If there are no versions left, then delete the threading model and default value. if (bAllVersionsGone) { InProcServerKey.DeleteValue("",false); InProcServerKey.DeleteValue("ThreadingModel",false); } InProcServerKey.DeleteValue("Assembly",false); InProcServerKey.DeleteValue("Class",false); InProcServerKey.DeleteValue("RuntimeVersion",false); InProcServerKey.DeleteValue("CodeBase",false); // If there are no other values or subkeys then we can delete the InProcServerKey. if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0)) ClsIdKey.DeleteSubKey("InprocServer32"); } } // remove HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId // and HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Category // only when all versions are removed if (bAllVersionsGone) { // Delete the value we created. ClsIdKey.DeleteValue("",false); if (strProgId != String.Empty) { // // Remove the entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\ProgId key. // using (RegistryKey ProgIdKey = ClsIdKey.OpenSubKey("ProgId", true)) { if (ProgIdKey != null) { // Delete the value we created. ProgIdKey.DeleteValue("",false); // If there are no other values or subkeys then we can delete the ProgIdSubKey. if ((ProgIdKey.SubKeyCount == 0) && (ProgIdKey.ValueCount == 0)) ClsIdKey.DeleteSubKey("ProgId"); } } } // // Remove entries in the HKEY_CLASS_ROOT\CLSID\<CLSID>\Implemented Categories\<Managed Category Guid> key. // using (RegistryKey CategoryKey = ClsIdKey.OpenSubKey(strImplementedCategoriesSubKey, true)) { if (CategoryKey != null) { using (RegistryKey ManagedCategoryKey = CategoryKey.OpenSubKey(strManagedCategoryGuid, true)) { if (ManagedCategoryKey != null) { // If there are no other values or subkeys then we can delete the ManagedCategoryKey. if ((ManagedCategoryKey.SubKeyCount == 0) && (ManagedCategoryKey.ValueCount == 0)) CategoryKey.DeleteSubKey(strManagedCategoryGuid); } } // If there are no other values or subkeys then we can delete the CategoryKey. if ((CategoryKey.SubKeyCount == 0) && (CategoryKey.ValueCount == 0)) ClsIdKey.DeleteSubKey(strImplementedCategoriesSubKey); } } } // If there are no other values or subkeys then we can delete the ClsIdKey. if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0)) ClsIdRootKey.DeleteSubKey(strClsId); } } // If there are no other values or subkeys then we can delete the CLSID key. if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0)) Registry.ClassesRoot.DeleteSubKey(strClsIdRootName); } // // Remove the entries under HKEY_CLASS_ROOT\<wzProgId> key. // if (bAllVersionsGone) { if (strProgId != String.Empty) { using (RegistryKey TypeNameKey = Registry.ClassesRoot.OpenSubKey(strProgId, true)) { if (TypeNameKey != null) { // Delete the values we created. TypeNameKey.DeleteValue("",false); // // Remove the entries in the HKEY_CLASS_ROOT\<wzProgId>\CLSID key. // using (RegistryKey ProgIdClsIdKey = TypeNameKey.OpenSubKey("CLSID", true)) { if (ProgIdClsIdKey != null) { // Delete the values we created. ProgIdClsIdKey.DeleteValue("",false); // If there are no other values or subkeys then we can delete the ProgIdClsIdKey. if ((ProgIdClsIdKey.SubKeyCount == 0) && (ProgIdClsIdKey.ValueCount == 0)) TypeNameKey.DeleteSubKey("CLSID"); } } // If there are no other values or subkeys then we can delete the TypeNameKey. if ((TypeNameKey.SubKeyCount == 0) && (TypeNameKey.ValueCount == 0)) Registry.ClassesRoot.DeleteSubKey(strProgId); } } } } } return bAllVersionsGone; } // UnregisterComImportedType // Return: // true: All version information are gone. // false: There are still some version left in registry [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private bool UnregisterComImportedType(Type type, String strAsmVersion) { bool bAllVersionsGone = true; String strClsId = "{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; // Try to open the HKEY_CLASS_ROOT\CLSID key. using (RegistryKey ClsIdRootKey = Registry.ClassesRoot.OpenSubKey(strClsIdRootName, true)) { if (ClsIdRootKey != null) { // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID> key. using (RegistryKey ClsIdKey = ClsIdRootKey.OpenSubKey(strClsId, true)) { if (ClsIdKey != null) { // Try to open the HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32 key. using (RegistryKey InProcServerKey = ClsIdKey.OpenSubKey("InprocServer32", true)) { if (InProcServerKey != null) { // Delete the values we created. InProcServerKey.DeleteValue("Assembly",false); InProcServerKey.DeleteValue("Class",false); InProcServerKey.DeleteValue("RuntimeVersion",false); InProcServerKey.DeleteValue("CodeBase",false); // Try to open the entries in HKEY_CLASS_ROOT\CLSID\<CLSID>\InProcServer32\<Version> using (RegistryKey VersionSubKey = InProcServerKey.OpenSubKey(strAsmVersion,true)) { if (VersionSubKey != null) { // Delete the value we created VersionSubKey.DeleteValue("Assembly",false); VersionSubKey.DeleteValue("Class",false); VersionSubKey.DeleteValue("RuntimeVersion",false); VersionSubKey.DeleteValue("CodeBase",false); // If there are no other values or subkeys then we can delete the VersionSubKey if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0)) InProcServerKey.DeleteSubKey(strAsmVersion); } } // If there are sub keys left then there are versions left. if (InProcServerKey.SubKeyCount != 0) bAllVersionsGone = false; // If there are no other values or subkeys then we can delete the InProcServerKey. if ((InProcServerKey.SubKeyCount == 0) && (InProcServerKey.ValueCount == 0)) ClsIdKey.DeleteSubKey("InprocServer32"); } } // If there are no other values or subkeys then we can delete the ClsIdKey. if ((ClsIdKey.SubKeyCount == 0) && (ClsIdKey.ValueCount == 0)) ClsIdRootKey.DeleteSubKey(strClsId); } } // If there are no other values or subkeys then we can delete the CLSID key. if ((ClsIdRootKey.SubKeyCount == 0) && (ClsIdRootKey.ValueCount == 0)) Registry.ClassesRoot.DeleteSubKey(strClsIdRootName); } } return bAllVersionsGone; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private void RegisterPrimaryInteropAssembly(RuntimeAssembly assembly, String strAsmCodeBase, PrimaryInteropAssemblyAttribute attr) { // Validate that the PIA has a strong name. if (assembly.GetPublicKey().Length == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed")); String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture); // Create the HKEY_CLASS_ROOT\TypeLib key. using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.CreateSubKey(strTlbRootName)) { // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID> key. using (RegistryKey TypeLibKey = TypeLibRootKey.CreateSubKey(strTlbId)) { // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\<Major.Minor> key. using (RegistryKey VersionSubKey = TypeLibKey.CreateSubKey(strVersion)) { // Create the HKEY_CLASS_ROOT\TypeLib\<TLBID>\PrimaryInteropAssembly key. VersionSubKey.SetValue("PrimaryInteropAssemblyName", assembly.FullName); if (strAsmCodeBase != null) VersionSubKey.SetValue("PrimaryInteropAssemblyCodeBase", strAsmCodeBase); } } } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void UnregisterPrimaryInteropAssembly(Assembly assembly, PrimaryInteropAssemblyAttribute attr) { String strTlbId = "{" + Marshal.GetTypeLibGuidForAssembly(assembly).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; String strVersion = attr.MajorVersion.ToString("x", CultureInfo.InvariantCulture) + "." + attr.MinorVersion.ToString("x", CultureInfo.InvariantCulture); // Try to open the HKEY_CLASS_ROOT\TypeLib key. using (RegistryKey TypeLibRootKey = Registry.ClassesRoot.OpenSubKey(strTlbRootName, true)) { if (TypeLibRootKey != null) { // Try to open the HKEY_CLASS_ROOT\TypeLib\<TLBID> key. using (RegistryKey TypeLibKey = TypeLibRootKey.OpenSubKey(strTlbId, true)) { if (TypeLibKey != null) { // Try to open the HKEY_CLASS_ROOT\TypeLib<TLBID>\<Major.Minor> key. using (RegistryKey VersionSubKey = TypeLibKey.OpenSubKey(strVersion, true)) { if (VersionSubKey != null) { // Delete the values we created. VersionSubKey.DeleteValue("PrimaryInteropAssemblyName",false); VersionSubKey.DeleteValue("PrimaryInteropAssemblyCodeBase",false); // If there are no other values or subkeys then we can delete the VersionKey. if ((VersionSubKey.SubKeyCount == 0) && (VersionSubKey.ValueCount == 0)) TypeLibKey.DeleteSubKey(strVersion); } } // If there are no other values or subkeys then we can delete the TypeLibKey. if ((TypeLibKey.SubKeyCount == 0) && (TypeLibKey.ValueCount == 0)) TypeLibRootKey.DeleteSubKey(strTlbId); } } // If there are no other values or subkeys then we can delete the TypeLib key. if ((TypeLibRootKey.SubKeyCount == 0) && (TypeLibRootKey.ValueCount == 0)) Registry.ClassesRoot.DeleteSubKey(strTlbRootName); } } } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private void EnsureManagedCategoryExists() { if (!ManagedCategoryExists()) { // Create the HKEY_CLASS_ROOT\Component Category key. using (RegistryKey ComponentCategoryKey = Registry.ClassesRoot.CreateSubKey(strComponentCategorySubKey)) { // Create the HKEY_CLASS_ROOT\Component Category\<Managed Category Guid> key. using (RegistryKey ManagedCategoryKey = ComponentCategoryKey.CreateSubKey(strManagedCategoryGuid)) { ManagedCategoryKey.SetValue("0", strManagedCategoryDescription); } } } } [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] private static bool ManagedCategoryExists() { using (RegistryKey componentCategoryKey = Registry.ClassesRoot.OpenSubKey(strComponentCategorySubKey, #if FEATURE_MACL RegistryKeyPermissionCheck.ReadSubTree)) #else false)) #endif { if (componentCategoryKey == null) return false; using (RegistryKey managedCategoryKey = componentCategoryKey.OpenSubKey(strManagedCategoryGuid, #if FEATURE_MACL RegistryKeyPermissionCheck.ReadSubTree)) #else false)) #endif { if (managedCategoryKey == null) return false; object value = managedCategoryKey.GetValue("0"); if (value == null || value.GetType() != typeof(string)) return false; string stringValue = (string)value; if (stringValue != strManagedCategoryDescription) return false; } } return true; } [System.Security.SecurityCritical] // auto-generated private void CallUserDefinedRegistrationMethod(Type type, bool bRegister) { bool bFunctionCalled = false; // Retrieve the attribute type to use to determine if a function is the requested user defined // registration function. Type RegFuncAttrType = null; if(bRegister) RegFuncAttrType = typeof(ComRegisterFunctionAttribute); else RegFuncAttrType = typeof(ComUnregisterFunctionAttribute); for(Type currType = type; !bFunctionCalled && currType != null; currType = currType.BaseType) { // Retrieve all the methods. MethodInfo[] aMethods = currType.GetMethods(BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Static); int NumMethods = aMethods.Length; // Go through all the methods and check for the ComRegisterMethod custom attribute. for(int cMethods = 0;cMethods < NumMethods;cMethods++) { MethodInfo CurrentMethod = aMethods[cMethods]; // Check to see if the method has the custom attribute. if(CurrentMethod.GetCustomAttributes(RegFuncAttrType, true).Length != 0) { // Check to see if the method is static before we call it. if(!CurrentMethod.IsStatic) { if(bRegister) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComRegFunction",CurrentMethod.Name,currType.Name)); else throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NonStaticComUnRegFunction",CurrentMethod.Name,currType.Name)); } // Finally check that the signature is string ret void. ParameterInfo[] aParams = CurrentMethod.GetParameters(); if (CurrentMethod.ReturnType != typeof(void) || aParams == null || aParams.Length != 1 || (aParams[0].ParameterType != typeof(String) && aParams[0].ParameterType != typeof(Type))) { if(bRegister) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComRegFunctionSig",CurrentMethod.Name,currType.Name)); else throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_InvalidComUnRegFunctionSig",CurrentMethod.Name,currType.Name)); } // There can only be one register and one unregister function per type. if(bFunctionCalled) { if(bRegister) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComRegFunctions",currType.Name)); else throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MultipleComUnRegFunctions",currType.Name)); } // The function is valid so set up the arguments to call it. Object[] objs = new Object[1]; if(aParams[0].ParameterType == typeof(String)) { // We are dealing with the string overload of the function. objs[0] = "HKEY_CLASSES_ROOT\\CLSID\\{" + Marshal.GenerateGuidForType(type).ToString().ToUpper(CultureInfo.InvariantCulture) + "}"; } else { // We are dealing with the type overload of the function. objs[0] = type; } // Invoke the COM register function. CurrentMethod.Invoke(null, objs); // Mark the function as having been called. bFunctionCalled = true; } } } } private Type GetBaseComImportType(Type type) { for (; type != null && !type.IsImport; type = type.BaseType); return type; } private bool IsRegisteredAsValueType(Type type) { if (!type.IsValueType) return false; return true; } #endregion #region FCalls and DllImports #if FEATURE_COMINTEROP_MANAGED_ACTIVATION // GUID versioning can be controlled by using the GuidAttribute or // letting the runtime generate it based on type and assembly strong name. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void RegisterTypeForComClientsNative(Type type,ref Guid g); // GUID versioning can be controlled by using the GuidAttribute or // letting the runtime generate it based on type and assembly strong name. [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int RegisterTypeForComClientsExNative(Type t, RegistrationClassContext clsContext, RegistrationConnectionType flags); #endif // FEATURE_COMINTEROP_MANAGED_ACTIVATION [DllImport(Win32Native.OLE32,CharSet=CharSet.Auto,PreserveSig=false)] [ResourceExposure(ResourceScope.None)] private static extern void CoRevokeClassObject(int cookie); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryDivideTests { #region Test methods [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckByteDivideTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteDivide(array[i], array[j]); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckSByteDivideTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteDivide(array[i], array[j]); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUShortDivideTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortDivide(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckShortDivideTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortDivide(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckUIntDivideTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntDivide(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckIntDivideTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntDivide(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckULongDivideTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongDivide(array[i], array[j], useInterpreter); } } } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 [ClassData(typeof(CompilationTypes))] public static void CheckLongDivideTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatDivideTest(bool useInterpreter) { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleDivideTest(bool useInterpreter) { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleDivide(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalDivideTest(bool useInterpreter) { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalDivide(array[i], array[j], useInterpreter); } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void CheckCharDivideTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharDivide(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteDivide(byte a, byte b) { Expression aExp = Expression.Constant(a, typeof(byte)); Expression bExp = Expression.Constant(b, typeof(byte)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifySByteDivide(sbyte a, sbyte b) { Expression aExp = Expression.Constant(a, typeof(sbyte)); Expression bExp = Expression.Constant(b, typeof(sbyte)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } private static void VerifyUShortDivide(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Divide( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort)(a / b), f()); } private static void VerifyShortDivide(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Divide( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(unchecked((short)(a / b)), f()); } private static void VerifyUIntDivide(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Divide( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyIntDivide(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Divide( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == int.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyULongDivide(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Divide( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyLongDivide(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Divide( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (b == -1 && a == long.MinValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyFloatDivide(float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Divide( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDoubleDivide(double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Divide( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal(a / b, f()); } private static void VerifyDecimalDivide(decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Divide( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); if (b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a / b, f()); } private static void VerifyCharDivide(char a, char b) { Expression aExp = Expression.Constant(a, typeof(char)); Expression bExp = Expression.Constant(b, typeof(char)); Assert.Throws<InvalidOperationException>(() => Expression.Divide(aExp, bExp)); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Divide(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Divide(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Divide(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Divide(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Divide(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e = Expression.Divide(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a / b)", e.ToString()); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Provisioning.CreateSiteWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#define MCG_WINRT_SUPPORTED using Mcg.System; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; // ----------------------------------------------------------------------------------------------------------- // // WARNING: THIS SOURCE FILE IS FOR 64-BIT BUILDS ONLY! // // MCG GENERATED CODE // // This C# source file is generated by MCG and is added into the application at compile time to support interop features. // // It has three primary components: // // 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes. // // 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code. // // 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code. // // ----------------------------------------------------------------------------------------------------------- // // warning CS0067: The event 'event' is never used #pragma warning disable 67 // warning CS0169: The field 'field' is never used #pragma warning disable 169 // warning CS0649: Field 'field' is never assigned to, and will always have its default value 0 #pragma warning disable 414 // warning CS0414: The private field 'field' is assigned but its value is never used #pragma warning disable 649 // warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member' #pragma warning disable 1591 // warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended. #pragma warning disable 108 // warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword. #pragma warning disable 114 // warning CS0659 'type' overrides Object.Equals but does not override GetHashCode. #pragma warning disable 659 // warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? #pragma warning disable 465 // warning CS0028 'function declaration' has the wrong signature to be an entry point #pragma warning disable 28 // warning CS0162 Unreachable code Detected #pragma warning disable 162 // warning CS0628 new protected member declared in sealed class #pragma warning disable 628 namespace McgInterop { /// <summary> /// P/Invoke class for module 'sqlite3' /// </summary> public unsafe static partial class sqlite3 { // Signature, Open, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")] public static global::SQLite.Net.Interop.Result__SQLite_Net Open( string filename, out global::System.IntPtr db) { // Setup byte* unsafe_filename = default(byte*); global::System.IntPtr unsafe_db; global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; try { // Marshalling unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false); // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Open( unsafe_filename, &(unsafe_db) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); db = unsafe_db; // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename); } } // Signature, Open__0, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")] public static global::SQLite.Net.Interop.Result__SQLite_Net Open__0( string filename, out global::System.IntPtr db, int flags, global::System.IntPtr zvfs) { // Setup byte* unsafe_filename = default(byte*); global::System.IntPtr unsafe_db; global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; try { // Marshalling unsafe_filename = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(filename, true, false); // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__0( unsafe_filename, &(unsafe_db), flags, zvfs ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); db = unsafe_db; // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_filename); } } // Signature, Open__1, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open")] public static global::SQLite.Net.Interop.Result__SQLite_Net Open__1( byte[] filename, out global::System.IntPtr db, int flags, global::System.IntPtr zvfs) { // Setup byte* unsafe_filename; global::System.IntPtr unsafe_db; global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling fixed (byte* pinned_filename = global::McgInterop.McgCoreHelpers.GetArrayForCompat(filename)) { unsafe_filename = (byte*)pinned_filename; // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Open__1( unsafe_filename, &(unsafe_db), flags, zvfs ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); db = unsafe_db; } // Return return unsafe___value; } // Signature, Open16, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Open16")] public static global::SQLite.Net.Interop.Result__SQLite_Net Open16( string filename, out global::System.IntPtr db) { // Setup ushort* unsafe_filename = default(ushort*); global::System.IntPtr unsafe_db; global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling fixed (char* pinned_filename = filename) { unsafe_filename = (ushort*)pinned_filename; // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Open16( unsafe_filename, &(unsafe_db) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); db = unsafe_db; } // Return return unsafe___value; } // Signature, Close, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Close")] public static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Close(db); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Config, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ConfigOption__SQLite_Net__ConfigOption__SQLite_Net, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Config")] public static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Config(option); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, SetDirectory, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "SetDirectory")] public static int SetDirectory( uint directoryType, string directoryPath) { // Setup ushort* unsafe_directoryPath = default(ushort*); int unsafe___value; // Marshalling fixed (char* pinned_directoryPath = directoryPath) { unsafe_directoryPath = (ushort*)pinned_directoryPath; // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.SetDirectory( directoryType, unsafe_directoryPath ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); } // Return return unsafe___value; } // Signature, BusyTimeout, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BusyTimeout")] public static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout( global::System.IntPtr db, int milliseconds) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BusyTimeout( db, milliseconds ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Changes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Changes")] public static int Changes(global::System.IntPtr db) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Changes(db); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Prepare2, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Prepare2")] public static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2( global::System.IntPtr db, string sql, int numBytes, out global::System.IntPtr stmt, global::System.IntPtr pzTail) { // Setup byte* unsafe_sql = default(byte*); global::System.IntPtr unsafe_stmt; global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; try { // Marshalling unsafe_sql = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(sql, true, false); // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Prepare2( db, unsafe_sql, numBytes, &(unsafe_stmt), pzTail ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); stmt = unsafe_stmt; // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_sql); } } // Signature, Step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Step")] public static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Step(stmt); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Reset, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Reset")] public static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Reset(stmt); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Finalize, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Finalize")] public static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Finalize(stmt); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, LastInsertRowid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "LastInsertRowid")] public static long LastInsertRowid(global::System.IntPtr db) { // Setup long unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.LastInsertRowid(db); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, Errmsg, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "Errmsg")] public static global::System.IntPtr Errmsg(global::System.IntPtr db) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.Errmsg(db); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, BindParameterIndex, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindParameterIndex")] public static int BindParameterIndex( global::System.IntPtr stmt, string name) { // Setup byte* unsafe_name = default(byte*); int unsafe___value; try { // Marshalling unsafe_name = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(name, true, false); // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindParameterIndex( stmt, unsafe_name ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_name); } } // Signature, BindNull, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindNull")] public static int BindNull( global::System.IntPtr stmt, int index) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindNull( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, BindInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt")] public static int BindInt( global::System.IntPtr stmt, int index, int val) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt( stmt, index, val ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, BindInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindInt64")] public static int BindInt64( global::System.IntPtr stmt, int index, long val) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindInt64( stmt, index, val ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, BindDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindDouble")] public static int BindDouble( global::System.IntPtr stmt, int index, double val) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindDouble( stmt, index, val ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, BindText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindText")] public static int BindText( global::System.IntPtr stmt, int index, string val, int n, global::System.IntPtr free) { // Setup ushort* unsafe_val = default(ushort*); int unsafe___value; // Marshalling fixed (char* pinned_val = val) { unsafe_val = (ushort*)pinned_val; // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindText( stmt, index, unsafe_val, n, free ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); } // Return return unsafe___value; } // Signature, BindBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_byte__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "BindBlob")] public static int BindBlob( global::System.IntPtr stmt, int index, byte[] val, int n, global::System.IntPtr free) { // Setup byte* unsafe_val; int unsafe___value; // Marshalling fixed (byte* pinned_val = global::McgInterop.McgCoreHelpers.GetArrayForCompat(val)) { unsafe_val = (byte*)pinned_val; // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.BindBlob( stmt, index, unsafe_val, n, free ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); } // Return return unsafe___value; } // Signature, ColumnCount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnCount")] public static int ColumnCount(global::System.IntPtr stmt) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnCount(stmt); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName")] public static global::System.IntPtr ColumnName( global::System.IntPtr stmt, int index) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnName16Internal, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnName16Internal")] public static global::System.IntPtr ColumnName16Internal( global::System.IntPtr stmt, int index) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnName16Internal( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnType, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ColType__SQLite_Net__ColType__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnType")] public static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType( global::System.IntPtr stmt, int index) { // Setup global::SQLite.Net.Interop.ColType__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnType( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnInt, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt")] public static int ColumnInt( global::System.IntPtr stmt, int index) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnInt64, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnInt64")] public static long ColumnInt64( global::System.IntPtr stmt, int index) { // Setup long unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnInt64( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnDouble, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnDouble")] public static double ColumnDouble( global::System.IntPtr stmt, int index) { // Setup double unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnDouble( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnText, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText")] public static global::System.IntPtr ColumnText( global::System.IntPtr stmt, int index) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnText16, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnText16")] public static global::System.IntPtr ColumnText16( global::System.IntPtr stmt, int index) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnText16( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnBlob, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBlob")] public static global::System.IntPtr ColumnBlob( global::System.IntPtr stmt, int index) { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBlob( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ColumnBytes, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "ColumnBytes")] public static int ColumnBytes( global::System.IntPtr stmt, int index) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.ColumnBytes( stmt, index ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_extended_errcode, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_ExtendedResult__SQLite_Net__ExtendedResult__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_extended_errcode")] public static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db) { // Setup global::SQLite.Net.Interop.ExtendedResult__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_extended_errcode(db); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_libversion_number, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_libversion_number")] public static int sqlite3_libversion_number() { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_libversion_number(); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_sourceid, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sourceid")] public static global::System.IntPtr sqlite3_sourceid() { // Setup global::System.IntPtr unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sourceid(); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_backup_init, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.AnsiStringMarshaller] string__unsigned char *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_init")] public static global::System.IntPtr sqlite3_backup_init( global::System.IntPtr destDB, string destName, global::System.IntPtr srcDB, string srcName) { // Setup byte* unsafe_destName = default(byte*); byte* unsafe_srcName = default(byte*); global::System.IntPtr unsafe___value; try { // Marshalling unsafe_destName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(destName, true, false); unsafe_srcName = global::System.Runtime.InteropServices.McgMarshal.StringToAnsiString(srcName, true, false); // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_init( destDB, unsafe_destName, srcDB, unsafe_srcName ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_destName); global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_srcName); } } // Signature, sqlite3_backup_step, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_step")] public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step( global::System.IntPtr backup, int pageCount) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_step( backup, pageCount ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_backup_finish, [fwd] [return] [Mcg.CodeGen.EnumMarshaller] SQLite_Net_Interop_Result__SQLite_Net__Result__SQLite_Net, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_finish")] public static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup) { // Setup global::SQLite.Net.Interop.Result__SQLite_Net unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_finish(backup); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_backup_remaining, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_remaining")] public static int sqlite3_backup_remaining(global::System.IntPtr backup) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_remaining(backup); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_backup_pagecount, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_backup_pagecount")] public static int sqlite3_backup_pagecount(global::System.IntPtr backup) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_backup_pagecount(backup); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, sqlite3_sleep, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("SQLite.Net.Platform.WinRT, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null", "SQLite.Net.Platform.WinRT.SQLite3", "sqlite3_sleep")] public static int sqlite3_sleep(int millis) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.sqlite3_PInvokes.sqlite3_sleep(millis); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } } /// <summary> /// P/Invoke class for module '[MRT]' /// </summary> public unsafe static partial class _MRT_ { // Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")] public static void RhWaitForPendingFinalizers(int allowReentrantWait) { // Marshalling // Call to native method global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return } // Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")] public static int RhCompatibleReentrantWaitAny( int alertable, int timeout, int count, global::System.IntPtr* handles) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny( alertable, timeout, count, ((global::System.IntPtr*)handles) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")] public static void _ecvt_s( byte* buffer, int sizeInBytes, double value, int count, int* dec, int* sign) { // Marshalling // Call to native method global::McgInterop._MRT__PInvokes._ecvt_s( ((byte*)buffer), sizeInBytes, value, count, ((int*)dec), ((int*)sign) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return } // Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] ulong__unsigned __int64, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")] public static void memmove( byte* dmem, byte* smem, ulong size) { // Marshalling // Call to native method global::McgInterop._MRT__PInvokes.memmove( ((byte*)dmem), ((byte*)smem), size ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return } } /// <summary> /// P/Invoke class for module '*' /// </summary> public unsafe static partial class _ { // Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")] public static void CallingConventionConverter_GetStubs( out global::System.IntPtr returnVoidStub, out global::System.IntPtr returnIntegerStub, out global::System.IntPtr commonStub) { // Setup global::System.IntPtr unsafe_returnVoidStub; global::System.IntPtr unsafe_returnIntegerStub; global::System.IntPtr unsafe_commonStub; // Marshalling // Call to native method global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs( &(unsafe_returnVoidStub), &(unsafe_returnIntegerStub), &(unsafe_commonStub) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); commonStub = unsafe_commonStub; returnIntegerStub = unsafe_returnIntegerStub; returnVoidStub = unsafe_returnVoidStub; // Return } } /// <summary> /// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll' /// </summary> public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll { // Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")] public static int GetLastError() { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError(); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } } /// <summary> /// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll' /// </summary> public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll { // Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")] public static int RoInitialize(uint initType) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } } /// <summary> /// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll' /// </summary> public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll { // Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")] public static int IsValidLocaleName(char* lpLocaleName) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName)); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")] public static int ResolveLocaleName( char* lpNameToResolve, char* lpLocaleName, int cchLocaleName) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName( ((ushort*)lpNameToResolve), ((ushort*)lpLocaleName), cchLocaleName ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } // Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")] public static int GetCPInfoExW( uint CodePage, uint dwFlags, global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx) { // Setup int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW( CodePage, dwFlags, ((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return return unsafe___value; } } /// <summary> /// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll' /// </summary> public unsafe static partial class api_ms_win_core_com_l1_1_0_dll { // Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")] public static int CoCreateInstance( byte* rclsid, global::System.IntPtr pUnkOuter, int dwClsContext, byte* riid, out global::System.IntPtr ppv) { // Setup global::System.IntPtr unsafe_ppv; int unsafe___value; // Marshalling // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance( ((byte*)rclsid), pUnkOuter, dwClsContext, ((byte*)riid), &(unsafe_ppv) ); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); ppv = unsafe_ppv; // Return return unsafe___value; } } /// <summary> /// P/Invoke class for module 'OleAut32' /// </summary> public unsafe static partial class OleAut32 { // Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")] public static void SysFreeString(global::System.IntPtr bstr) { // Marshalling // Call to native method global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); // Return } } /// <summary> /// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll' /// </summary> public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll { // Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *, [global::System.Runtime.InteropServices.McgGeneratedMarshallingCode] [global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore", "RoGetBufferMarshaler")] public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr) { // Setup global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**); int unsafe___value; try { // Marshalling unsafe_bufferMarshalerPtr = null; // Call to native method unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr)); global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode(); bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject( ((global::System.IntPtr)unsafe_bufferMarshalerPtr), global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.11.0, Culture=neutral, Public" + "KeyToken=b77a5c561934e089") ); // Return return unsafe___value; } finally { // Cleanup global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr))); } } } public unsafe static partial class sqlite3_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open( byte* filename, global::System.IntPtr* db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__0( byte* filename, global::System.IntPtr* db, int flags, global::System.IntPtr zvfs); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open__1( byte* filename, global::System.IntPtr* db, int flags, global::System.IntPtr zvfs); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_open16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Open16( ushort* filename, global::System.IntPtr* db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_close", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Close(global::System.IntPtr db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_config", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Config(global::SQLite.Net.Interop.ConfigOption__SQLite_Net option); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_win32_set_directory", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int SetDirectory( uint directoryType, ushort* directoryPath); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_busy_timeout", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net BusyTimeout( global::System.IntPtr db, int milliseconds); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_changes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int Changes(global::System.IntPtr db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_prepare_v2", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Prepare2( global::System.IntPtr db, byte* sql, int numBytes, global::System.IntPtr* stmt, global::System.IntPtr pzTail); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_step", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Step(global::System.IntPtr stmt); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_reset", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Reset(global::System.IntPtr stmt); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_finalize", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net Finalize(global::System.IntPtr stmt); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_last_insert_rowid", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static long LastInsertRowid(global::System.IntPtr db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_errmsg16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr Errmsg(global::System.IntPtr db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_parameter_index", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindParameterIndex( global::System.IntPtr stmt, byte* name); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_null", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindNull( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindInt( global::System.IntPtr stmt, int index, int val); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindInt64( global::System.IntPtr stmt, int index, long val); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindDouble( global::System.IntPtr stmt, int index, double val); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindText( global::System.IntPtr stmt, int index, ushort* val, int n, global::System.IntPtr free); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_bind_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int BindBlob( global::System.IntPtr stmt, int index, byte* val, int n, global::System.IntPtr free); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_count", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int ColumnCount(global::System.IntPtr stmt); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr ColumnName( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_name16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr ColumnName16Internal( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_type", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.ColType__SQLite_Net ColumnType( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int ColumnInt( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_int64", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static long ColumnInt64( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_double", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static double ColumnDouble( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr ColumnText( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_text16", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr ColumnText16( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_blob", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr ColumnBlob( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", EntryPoint="sqlite3_column_bytes", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int ColumnBytes( global::System.IntPtr stmt, int index); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.ExtendedResult__SQLite_Net sqlite3_extended_errcode(global::System.IntPtr db); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int sqlite3_libversion_number(); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr sqlite3_sourceid(); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::System.IntPtr sqlite3_backup_init( global::System.IntPtr destDB, byte* destName, global::System.IntPtr srcDB, byte* srcName); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_step( global::System.IntPtr backup, int pageCount); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static global::SQLite.Net.Interop.Result__SQLite_Net sqlite3_backup_finish(global::System.IntPtr backup); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int sqlite3_backup_remaining(global::System.IntPtr backup); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int sqlite3_backup_pagecount(global::System.IntPtr backup); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("sqlite3", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Cdecl)] public extern static int sqlite3_sleep(int millis); } public unsafe static partial class _MRT__PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static void RhWaitForPendingFinalizers(int allowReentrantWait); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int RhCompatibleReentrantWaitAny( int alertable, int timeout, int count, global::System.IntPtr* handles); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static void _ecvt_s( byte* buffer, int sizeInBytes, double value, int count, int* dec, int* sign); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static void memmove( byte* dmem, byte* smem, ulong size); } public unsafe static partial class __PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static void CallingConventionConverter_GetStubs( global::System.IntPtr* returnVoidStub, global::System.IntPtr* returnIntegerStub, global::System.IntPtr* commonStub); } public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int GetLastError(); } public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int RoInitialize(uint initType); } public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int IsValidLocaleName(ushort* lpLocaleName); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int ResolveLocaleName( ushort* lpNameToResolve, ushort* lpLocaleName, int cchLocaleName); [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int GetCPInfoExW( uint CodePage, uint dwFlags, global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx); } public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static int CoCreateInstance( byte* rclsid, global::System.IntPtr pUnkOuter, int dwClsContext, byte* riid, global::System.IntPtr* ppv); } public unsafe static partial class OleAut32_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)] public extern static void SysFreeString(global::System.IntPtr bstr); } public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes { [global::McgInterop.McgGeneratedNativeCallCode] [global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)] public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr); } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System { public static class __TimeZoneInfo { public static IObservable<System.TimeZoneInfo.AdjustmentRule[]> GetAdjustmentRules( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.GetAdjustmentRules()); } public static IObservable<System.TimeSpan[]> GetAmbiguousTimeOffsets( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.GetAmbiguousTimeOffsets(dateTimeOffsetLambda)); } public static IObservable<System.TimeSpan[]> GetAmbiguousTimeOffsets( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.GetAmbiguousTimeOffsets(dateTimeLambda)); } public static IObservable<System.TimeSpan> GetUtcOffset(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.GetUtcOffset(dateTimeOffsetLambda)); } public static IObservable<System.TimeSpan> GetUtcOffset(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.GetUtcOffset(dateTimeLambda)); } public static IObservable<System.Boolean> IsAmbiguousTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.IsAmbiguousTime(dateTimeOffsetLambda)); } public static IObservable<System.Boolean> IsAmbiguousTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsAmbiguousTime(dateTimeLambda)); } public static IObservable<System.Boolean> IsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTimeOffset> dateTimeOffset) { return Observable.Zip(TimeZoneInfoValue, dateTimeOffset, (TimeZoneInfoValueLambda, dateTimeOffsetLambda) => TimeZoneInfoValueLambda.IsDaylightSavingTime(dateTimeOffsetLambda)); } public static IObservable<System.Boolean> IsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsDaylightSavingTime(dateTimeLambda)); } public static IObservable<System.Boolean> IsInvalidTime(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.DateTime> dateTime) { return Observable.Zip(TimeZoneInfoValue, dateTime, (TimeZoneInfoValueLambda, dateTimeLambda) => TimeZoneInfoValueLambda.IsInvalidTime(dateTimeLambda)); } public static IObservable<System.Reactive.Unit> ClearCachedData() { return ObservableExt.Factory(() => System.TimeZoneInfo.ClearCachedData()); } public static IObservable<System.DateTimeOffset> ConvertTimeBySystemTimeZoneId( IObservable<System.DateTimeOffset> dateTimeOffset, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTimeOffset, destinationTimeZoneId, (dateTimeOffsetLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeOffsetLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTime> ConvertTimeBySystemTimeZoneId(IObservable<System.DateTime> dateTime, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTime, destinationTimeZoneId, (dateTimeLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTime> ConvertTimeBySystemTimeZoneId(IObservable<System.DateTime> dateTime, IObservable<System.String> sourceTimeZoneId, IObservable<System.String> destinationTimeZoneId) { return Observable.Zip(dateTime, sourceTimeZoneId, destinationTimeZoneId, (dateTimeLambda, sourceTimeZoneIdLambda, destinationTimeZoneIdLambda) => System.TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeLambda, sourceTimeZoneIdLambda, destinationTimeZoneIdLambda)); } public static IObservable<System.DateTimeOffset> ConvertTime(IObservable<System.DateTimeOffset> dateTimeOffset, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTimeOffset, destinationTimeZone, (dateTimeOffsetLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeOffsetLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTime(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, destinationTimeZone, (dateTimeLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTime(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> sourceTimeZone, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, sourceTimeZone, destinationTimeZone, (dateTimeLambda, sourceTimeZoneLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTime(dateTimeLambda, sourceTimeZoneLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTimeFromUtc(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> destinationTimeZone) { return Observable.Zip(dateTime, destinationTimeZone, (dateTimeLambda, destinationTimeZoneLambda) => System.TimeZoneInfo.ConvertTimeFromUtc(dateTimeLambda, destinationTimeZoneLambda)); } public static IObservable<System.DateTime> ConvertTimeToUtc(IObservable<System.DateTime> dateTime) { return Observable.Select(dateTime, (dateTimeLambda) => System.TimeZoneInfo.ConvertTimeToUtc(dateTimeLambda)); } public static IObservable<System.DateTime> ConvertTimeToUtc(IObservable<System.DateTime> dateTime, IObservable<System.TimeZoneInfo> sourceTimeZone) { return Observable.Zip(dateTime, sourceTimeZone, (dateTimeLambda, sourceTimeZoneLambda) => System.TimeZoneInfo.ConvertTimeToUtc(dateTimeLambda, sourceTimeZoneLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.TimeZoneInfo> other) { return Observable.Zip(TimeZoneInfoValue, other, (TimeZoneInfoValueLambda, otherLambda) => TimeZoneInfoValueLambda.Equals(otherLambda)); } public static IObservable<System.Boolean> Equals(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.Object> obj) { return Observable.Zip(TimeZoneInfoValue, obj, (TimeZoneInfoValueLambda, objLambda) => TimeZoneInfoValueLambda.Equals(objLambda)); } public static IObservable<System.TimeZoneInfo> FromSerializedString(IObservable<System.String> source) { return Observable.Select(source, (sourceLambda) => System.TimeZoneInfo.FromSerializedString(sourceLambda)); } public static IObservable<System.Int32> GetHashCode(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.GetHashCode()); } public static IObservable<System.Collections.ObjectModel.ReadOnlyCollection<System.TimeZoneInfo>> GetSystemTimeZones() { return ObservableExt.Factory(() => System.TimeZoneInfo.GetSystemTimeZones()); } public static IObservable<System.Boolean> HasSameRules(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue, IObservable<System.TimeZoneInfo> other) { return Observable.Zip(TimeZoneInfoValue, other, (TimeZoneInfoValueLambda, otherLambda) => TimeZoneInfoValueLambda.HasSameRules(otherLambda)); } public static IObservable<System.String> ToSerializedString( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.ToSerializedString()); } public static IObservable<System.String> ToString(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.ToString()); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda)); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName, IObservable<System.String> daylightDisplayName, IObservable<System.TimeZoneInfo.AdjustmentRule[]> adjustmentRules) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda)); } public static IObservable<System.TimeZoneInfo> CreateCustomTimeZone(IObservable<System.String> id, IObservable<System.TimeSpan> baseUtcOffset, IObservable<System.String> displayName, IObservable<System.String> standardDisplayName, IObservable<System.String> daylightDisplayName, IObservable<System.TimeZoneInfo.AdjustmentRule[]> adjustmentRules, IObservable<System.Boolean> disableDaylightSavingTime) { return Observable.Zip(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime, (idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda, disableDaylightSavingTimeLambda) => System.TimeZoneInfo.CreateCustomTimeZone(idLambda, baseUtcOffsetLambda, displayNameLambda, standardDisplayNameLambda, daylightDisplayNameLambda, adjustmentRulesLambda, disableDaylightSavingTimeLambda)); } public static IObservable<System.TimeZoneInfo> FindSystemTimeZoneById(IObservable<System.String> id) { return Observable.Select(id, (idLambda) => System.TimeZoneInfo.FindSystemTimeZoneById(idLambda)); } public static IObservable<System.String> get_Id(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.Id); } public static IObservable<System.String> get_DisplayName(this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.DisplayName); } public static IObservable<System.String> get_StandardName( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.StandardName); } public static IObservable<System.String> get_DaylightName( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.DaylightName); } public static IObservable<System.TimeSpan> get_BaseUtcOffset( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.BaseUtcOffset); } public static IObservable<System.Boolean> get_SupportsDaylightSavingTime( this IObservable<System.TimeZoneInfo> TimeZoneInfoValue) { return Observable.Select(TimeZoneInfoValue, (TimeZoneInfoValueLambda) => TimeZoneInfoValueLambda.SupportsDaylightSavingTime); } public static IObservable<System.TimeZoneInfo> get_Local() { return ObservableExt.Factory(() => System.TimeZoneInfo.Local); } public static IObservable<System.TimeZoneInfo> get_Utc() { return ObservableExt.Factory(() => System.TimeZoneInfo.Utc); } } }
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using java = biz.ritter.javapi; using javax = biz.ritter.javapix; /*import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.harmony.prefs.internal.nls.Messages; import org.apache.xpath.XPathAPI; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; */ namespace biz.ritter.javapi.util.prefs { /** * Utility class for the Preferences import/export from XML file. */ internal class XMLParser { /* * Constant - the specified DTD URL */ const String PREFS_DTD_NAME = "http://java.sun.com/dtd/preferences.dtd"; //$NON-NLS-1$ /* * Constant - the DTD string */ const String PREFS_DTD = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + " <!ELEMENT preferences (root)>" + " <!ATTLIST preferences EXTERNAL_XML_VERSION CDATA \"0.0\" >" + " <!ELEMENT root (map, node*) >" + " <!ATTLIST root type (system|user) #REQUIRED >" + " <!ELEMENT node (map, node*) >" + " <!ATTLIST node name CDATA #REQUIRED >" + " <!ELEMENT map (entry*) >" + " <!ELEMENT entry EMPTY >" + " <!ATTLIST entry key CDATA #REQUIRED value CDATA #REQUIRED >"; /* * Constant - the specified header */ const String HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; //$NON-NLS-1$ /* * Constant - the specified DOCTYPE */ const String DOCTYPE = "<!DOCTYPE preferences SYSTEM"; //$NON-NLS-1$ /* * empty string array constant */ private static readonly String[] EMPTY_SARRAY = new String[0]; /* * Constant - used by FilePreferencesImpl, which is default implementation * of Linux platform */ private const String FILE_PREFS = "<!DOCTYPE map SYSTEM 'http://java.sun.com/dtd/preferences.dtd'>"; //$NON-NLS-1$ /* * Constant - specify the DTD version */ private const float XML_VERSION = 1.0f; /* * DOM builder */ private static readonly javax.xml.parsers.DocumentBuilder builder; /* * specify the indent level */ private static int indent = -1; /* * init DOM builder */ static XMLParser () { javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance (); factory.setValidating (true); try { builder = factory.newDocumentBuilder (); } catch (javax.xml.parsers.ParserConfigurationException e) { throw new java.lang.Error (e); } builder.setEntityResolver (new IAC_EntityResolver ()); builder.setErrorHandler (new IAC_ErrorHandler ()); } class IAC_ErrorHandler : org.xml.sax.ErrorHandler { public void warning (org.xml.sax.SAXParseException e) {// throws SAXException { throw e; } public void error (org.xml.sax.SAXParseException e) {//throws SAXException { throw e; } public void fatalError (org.xml.sax.SAXParseException e) {//throws SAXException { throw e; } } class IAC_EntityResolver : org.xml.sax.EntityResolver { public org.xml.sax.InputSource resolveEntity (String publicId, String systemId) {// throws SAXException, IOException { if (systemId.equals (PREFS_DTD_NAME)) { org.xml.sax.InputSource result = new org.xml.sax.InputSource (new java.io.StringReader ( PREFS_DTD)); result.setSystemId (PREFS_DTD_NAME); return result; } // prefs.1=Invalid DOCTYPE declaration: {0} throw new org.xml.sax.SAXException ("Invalid DOCTYPE declaration: " + systemId); //$NON-NLS-1$ } } private XMLParser () {// empty constructor } /* * Utilities for Preferences export */ internal static void exportPrefs (Preferences prefs, java.io.OutputStream stream, bool withSubTree) {//throws IOException, BackingStoreException { indent = -1; java.io.BufferedWriter outJ = new java.io.BufferedWriter (new java.io.OutputStreamWriter (stream, "UTF-8")); outJ.write (HEADER); outJ.newLine (); outJ.newLine (); outJ.write (DOCTYPE); outJ.write (" '"); outJ.write (PREFS_DTD_NAME); outJ.write ("'>"); outJ.newLine (); outJ.newLine (); flushStartTag ("preferences", new String[] { "EXTERNAL_XML_VERSION" }, new String[] { java.lang.StringJ.valueOf (XML_VERSION) }, outJ); flushStartTag ("root", new String[] { "type" }, new String[] { prefs .isUserNode () ? "user" : "system" }, outJ); flushEmptyElement ("map", outJ); StringTokenizer ancestors = new StringTokenizer (prefs.absolutePath (), "/"); exportNode (ancestors, prefs, withSubTree, outJ); flushEndTag ("root", outJ); flushEndTag ("preferences", outJ); outJ.flush (); outJ = null; } private static void exportNode (StringTokenizer ancestors, Preferences prefs, bool withSubTree, java.io.BufferedWriter outJ) {//throws IOException, BackingStoreException { if (ancestors.hasMoreTokens ()) { String name = ancestors.nextToken (); flushStartTag ( "node", new String[] { "name" }, new String[] { name }, outJ); //$NON-NLS-1$ //$NON-NLS-2$ if (ancestors.hasMoreTokens ()) { flushEmptyElement ("map", outJ); //$NON-NLS-1$ exportNode (ancestors, prefs, withSubTree, outJ); } else { exportEntries (prefs, outJ); if (withSubTree) { exportSubTree (prefs, outJ); } } flushEndTag ("node", outJ); //$NON-NLS-1$ } } private static void exportSubTree (Preferences prefs, java.io.BufferedWriter outJ) {//throws BackingStoreException, IOException { String[] names = prefs.childrenNames (); if (names.Length > 0) { for (int i = 0; i < names.Length; i++) { Preferences child = prefs.node (names [i]); flushStartTag ( "node", new String[] { "name" }, new String[] { names [i] }, outJ); //$NON-NLS-1$ //$NON-NLS-2$ exportEntries (child, outJ); exportSubTree (child, outJ); flushEndTag ("node", outJ); //$NON-NLS-1$ } } } private static void exportEntries (Preferences prefs, java.io.BufferedWriter outJ) {//throws BackingStoreException, IOException { String[] keys = prefs.keys (); String[] values = new String[keys.Length]; for (int i = 0; i < keys.Length; i++) { values [i] = prefs.get (keys [i], null); } exportEntries (keys, values, outJ); } private static void exportEntries (String[] keys, String[] values, java.io.BufferedWriter outJ) {// throws IOException { if (keys.Length == 0) { flushEmptyElement ("map", outJ); //$NON-NLS-1$ return; } flushStartTag ("map", outJ); //$NON-NLS-1$ for (int i = 0; i < keys.Length; i++) { if (values [i] != null) { flushEmptyElement ( "entry", new String[] { "key", "value" }, new String[] { keys [i], values [i] }, outJ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } } flushEndTag ("map", outJ); //$NON-NLS-1$ } private static void flushEndTag (String tagName, java.io.BufferedWriter outJ) {//throws IOException { flushIndent (indent--, outJ); outJ.write ("</"); //$NON-NLS-1$ outJ.write (tagName); outJ.write (">"); //$NON-NLS-1$ outJ.newLine (); } private static void flushEmptyElement (String tagName, java.io.BufferedWriter outJ) {//throws IOException { flushIndent (++indent, outJ); outJ.write ("<"); //$NON-NLS-1$ outJ.write (tagName); outJ.write (" />"); //$NON-NLS-1$ outJ.newLine (); indent--; } private static void flushEmptyElement (String tagName, String[] attrKeys, String[] attrValues, java.io.BufferedWriter outJ) {// throws IOException { flushIndent (++indent, outJ); outJ.write ("<"); //$NON-NLS-1$ outJ.write (tagName); flushPairs (attrKeys, attrValues, outJ); outJ.write (" />"); //$NON-NLS-1$ outJ.newLine (); indent--; } private static void flushPairs (String[] attrKeys, String[] attrValues, java.io.BufferedWriter outJ) {// throws IOException { for (int i = 0; i < attrKeys.Length; i++) { outJ.write (" "); //$NON-NLS-1$ outJ.write (attrKeys [i]); outJ.write ("=\""); //$NON-NLS-1$ outJ.write (htmlEncode (attrValues [i])); outJ.write ("\""); //$NON-NLS-1$ } } private static void flushIndent (int ind, java.io.BufferedWriter outJ) {//throws IOException { for (int i = 0; i < ind; i++) { outJ.write (" "); //$NON-NLS-1$ } } private static void flushStartTag (String tagName, String[] attrKeys, String[] attrValues, java.io.BufferedWriter outJ) {// throws IOException { flushIndent (++indent, outJ); outJ.write ("<"); //$NON-NLS-1$ outJ.write (tagName); flushPairs (attrKeys, attrValues, outJ); outJ.write (">"); //$NON-NLS-1$ outJ.newLine (); } private static void flushStartTag (String tagName, java.io.BufferedWriter outJ) {//throws IOException { flushIndent (++indent, outJ); outJ.write ("<"); //$NON-NLS-1$ outJ.write (tagName); outJ.write (">"); //$NON-NLS-1$ outJ.newLine (); } private static String htmlEncode (String s) { java.lang.StringBuilder sb = new java.lang.StringBuilder (); char c; for (int i = 0; i < s.length(); i++) { c = s.charAt (i); switch (c) { case '<': sb.append ("&lt;"); //$NON-NLS-1$ break; case '>': sb.append ("&gt;"); //$NON-NLS-1$ break; case '&': sb.append ("&amp;"); //$NON-NLS-1$ break; case '\\': sb.append ("&apos;"); //$NON-NLS-1$ break; case '"': sb.append ("&quot;"); //$NON-NLS-1$ break; default: sb.append (c); break; } } return sb.toString (); } /* * Utilities for Preferences import */ internal static void importPrefs (java.io.InputStream inJ) //throws IOException, {//InvalidPreferencesFormatException { try { // load XML document org.w3c.dom.Document doc = builder.parse (new org.xml.sax.InputSource (inJ)); // check preferences' export version org.w3c.dom.Element preferences; preferences = doc.getDocumentElement (); String version = preferences.getAttribute ("EXTERNAL_XML_VERSION"); //$NON-NLS-1$ if (version != null && java.lang.Float.parseFloat (version) > XML_VERSION) { // prefs.2=This preferences exported version is not // supported:{0} throw new java.util.prefs.InvalidPreferencesFormatException ("his preferences exported version is not supported:" + version); //$NON-NLS-1$ } // check preferences root's type org.w3c.dom.Element root = (org.w3c.dom.Element)preferences .getElementsByTagName ("root").item (0); //$NON-NLS-1$ Preferences prefsRoot = null; String type = root.getAttribute ("type"); //$NON-NLS-1$ if (type.equals ("user")) { //$NON-NLS-1$ prefsRoot = Preferences.userRoot (); } else { prefsRoot = Preferences.systemRoot (); } // load node loadNode (prefsRoot, root); } catch (javax.xml.parsers.FactoryConfigurationError e) { throw new InvalidPreferencesFormatException (e); } catch (org.xml.sax.SAXException e) { throw new InvalidPreferencesFormatException (e); } catch (javax.xml.transform.TransformerException e) { throw new InvalidPreferencesFormatException (e); } } private static void loadNode (Preferences prefs, org.w3c.dom.Element node) {//throws TransformerException { // load preferences org.w3c.dom.NodeList children = org.apache.xpath.XPathAPI.selectNodeList (node, "node"); //$NON-NLS-1$ org.w3c.dom.NodeList entries = org.apache.xpath.XPathAPI.selectNodeList (node, "map/entry"); //$NON-NLS-1$ int childNumber = children.getLength (); Preferences[] prefChildren = new Preferences[childNumber]; int entryNumber = entries.getLength (); lock (((AbstractPreferences) prefs).lockJ) { if (((AbstractPreferences)prefs).isRemoved ()) { return; } for (int i = 0; i < entryNumber; i++) { org.w3c.dom.Element entry = (org.w3c.dom.Element)entries.item (i); String key = entry.getAttribute ("key"); //$NON-NLS-1$ String value = entry.getAttribute ("value"); //$NON-NLS-1$ prefs.put (key, value); } // get children preferences node for (int i = 0; i < childNumber; i++) { org.w3c.dom.Element child = (org.w3c.dom.Element)children.item (i); String name = child.getAttribute ("name"); //$NON-NLS-1$ prefChildren [i] = prefs.node (name); } } // load children nodes after unlock for (int i = 0; i < childNumber; i++) { loadNode (prefChildren [i], (org.w3c.dom.Element)children.item (i)); } } /** * Load preferences from file, if cannot load, create a new one. * * @param file * the XML file to be read * @return Properties instance which indicates the preferences key-value * pairs */ static java.util.Properties loadFilePrefs (java.io.File file) { //FIXME: need lock or not? return loadFilePrefsImpl (file); } static java.util.Properties loadFilePrefsImpl (java.io.File file) { Properties result = new Properties (); if (!file.exists ()) { file.getParentFile ().mkdirs (); return result; } if (file.canRead ()) { java.io.InputStream inJ = null; java.nio.channels.FileLock lockJ = null; try { java.io.FileInputStream istream = new java.io.FileInputStream (file); inJ = new java.io.BufferedInputStream (istream); java.nio.channels.FileChannel channel = istream.getChannel (); lockJ = channel.lockJ (0L, java.lang.Long.MAX_VALUE, true); org.w3c.dom.Document doc = builder.parse (inJ); org.w3c.dom.NodeList entries = org.apache.xpath.XPathAPI.selectNodeList (doc .getDocumentElement (), "entry"); //$NON-NLS-1$ int length = entries.getLength (); for (int i = 0; i < length; i++) { org.w3c.dom.Element node = (org.w3c.dom.Element)entries.item (i); String key = node.getAttribute ("key"); //$NON-NLS-1$ String value = node.getAttribute ("value"); //$NON-NLS-1$ result.setProperty (key, value); } return result; } catch (java.io.IOException e) { } catch (org.xml.sax.SAXException e) { } catch (javax.xml.transform.TransformerException e) { // transform shouldn't fail for xpath call throw new java.lang.AssertionError (e); } finally { releaseQuietly (lockJ); closeQuietly (inJ); } } else { file.delete (); } return result; } static void flushFilePrefs (java.io.File file, java.util.Properties prefs) {//throws PrivilegedActionException { flushFilePrefsImpl (file, prefs); } static void flushFilePrefsImpl (java.io.File file, java.util.Properties prefs) {//throws IOException { java.io.BufferedWriter outJ = null; java.nio.channels.FileLock lockJ = null; try { java.io.FileOutputStream ostream = new java.io.FileOutputStream (file); outJ = new java.io.BufferedWriter (new java.io.OutputStreamWriter (ostream, "UTF-8")); //$NON-NLS-1$ java.nio.channels.FileChannel channel = ostream.getChannel (); lockJ = channel.lockJ (); outJ.write (HEADER); outJ.newLine (); outJ.write (FILE_PREFS); outJ.newLine (); if (prefs.size () == 0) { exportEntries (EMPTY_SARRAY, EMPTY_SARRAY, outJ); } else { String[] keys = prefs.keySet () .toArray (new String[prefs.size ()]); int length = keys.Length; String[] values = new String[length]; for (int i = 0; i < length; i++) { values [i] = prefs.getProperty (keys [i]); } exportEntries (keys, values, outJ); } outJ.flush (); } finally { releaseQuietly (lockJ); closeQuietly (outJ); } } private static void releaseQuietly (java.nio.channels.FileLock lockJ) { if (lockJ == null) { return; } try { lockJ.release (); } catch (java.io.IOException e) { } } private static void closeQuietly (java.io.Writer outJ) { if (outJ == null) { return; } try { outJ.close (); } catch (java.io.IOException e) { } } private static void closeQuietly (java.io.InputStream inJ) { if (inJ == null) { return; } try { inJ.close (); } catch (java.io.IOException e) { } } } }
namespace RestSharp.Authenticators.OAuth { using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; internal class WebPairCollection : IList<WebPair> { private IList<WebPair> parameters; public WebPairCollection(IEnumerable<WebPair> parameters) { this.parameters = new List<WebPair>(parameters); } public WebPairCollection(IDictionary<string, string> collection) : this() { this.AddCollection(collection); } public WebPairCollection() { this.parameters = new List<WebPair>(0); } public WebPairCollection(int capacity) { this.parameters = new List<WebPair>(capacity); } #if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC public WebPairCollection(NameValueCollection collection) : this() { this.AddCollection(collection); } #endif public virtual IEnumerable<string> Names { get { return this.parameters.Select(p => p.Name); } } public virtual IEnumerable<string> Values { get { return this.parameters.Select(p => p.Value); } } public virtual int Count { get { return this.parameters.Count; } } public virtual bool IsReadOnly { get { return this.parameters.IsReadOnly; } } public virtual WebPair this[string name] { get { return this.SingleOrDefault(p => p.Name.Equals(name)); } } public virtual WebPair this[int index] { get { return this.parameters[index]; } set { this.parameters[index] = value; } } public void AddCollection(IDictionary<string, string> collection) { foreach (var key in collection.Keys) { var parameter = new WebPair(key, collection[key]); this.parameters.Add(parameter); } } #if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC public virtual void AddRange(NameValueCollection collection) { this.AddCollection(collection); } #endif public virtual void AddRange(WebPairCollection collection) { this.AddCollection(collection); } public virtual void AddRange(IEnumerable<WebPair> collection) { this.AddCollection(collection); } public virtual void Sort(Comparison<WebPair> comparison) { var sorted = new List<WebPair>(this.parameters); sorted.Sort(comparison); this.parameters = sorted; } public virtual bool RemoveAll(IEnumerable<WebPair> parameters) { var success = true; var array = this.parameters.ToArray(); for (var p = 0; p < array.Length; p++) { var parameter = array[p]; success &= this.parameters.Remove(parameter); } return success && array.Length > 0; } public virtual void Add(string name, string value) { var pair = new WebPair(name, value); this.parameters.Add(pair); } #region IList<WebParameter> Members public virtual IEnumerator<WebPair> GetEnumerator() { return this.parameters.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public virtual void Add(WebPair parameter) { this.parameters.Add(parameter); } public virtual void Clear() { this.parameters.Clear(); } public virtual bool Contains(WebPair parameter) { return this.parameters.Contains(parameter); } public virtual void CopyTo(WebPair[] parameters, int arrayIndex) { this.parameters.CopyTo(parameters, arrayIndex); } public virtual bool Remove(WebPair parameter) { return this.parameters.Remove(parameter); } public virtual int IndexOf(WebPair parameter) { return this.parameters.IndexOf(parameter); } public virtual void Insert(int index, WebPair parameter) { this.parameters.Insert(index, parameter); } public virtual void RemoveAt(int index) { this.parameters.RemoveAt(index); } private void AddCollection(IEnumerable<WebPair> collection) { foreach (var parameter in collection) { var pair = new WebPair(parameter.Name, parameter.Value); this.parameters.Add(pair); } } #if !WINDOWS_PHONE && !SILVERLIGHT && !PocketPC private void AddCollection(NameValueCollection collection) { var parameters = collection.AllKeys.Select(key => new WebPair(key, collection[key])); foreach (var parameter in parameters) { this.parameters.Add(parameter); } } #endif #endregion } }
using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.ComponentModel; using Process = System.Diagnostics.Process; using Microsoft.VisualStudio; using BuildVision.Common; using BuildVision.Contracts; using BuildVision.UI.Contracts; using BuildVision.UI.DataGrid; using BuildVision.UI.Common.Logging; using BuildVision.UI.Helpers; using BuildVision.UI.Models; using BuildVision.UI.Models.Indicators.Core; using BuildVision.UI.Settings.Models.Columns; using SortDescription = BuildVision.UI.Settings.Models.Sorting.SortDescription; using BuildVision.UI.Settings.Models; using BuildVision.Helpers; namespace BuildVision.UI.ViewModels { public class ControlViewModel : BindableBase { private BuildState _buildState; private IBuildInfo _buildInfo; private ObservableCollection<DataGridColumn> _gridColumnsRef; public bool HideUpToDateTargets { get => ControlSettings.GeneralSettings.HideUpToDateTargets; set => SetProperty(() => ControlSettings.GeneralSettings.HideUpToDateTargets, val => ControlSettings.GeneralSettings.HideUpToDateTargets = val, value); } public ControlModel Model { get; } public BuildProgressViewModel BuildProgressViewModel { get; } public ControlSettings ControlSettings { get; } public ControlTemplate ImageCurrentState { get => Model.ImageCurrentState; set => SetProperty(() => Model.ImageCurrentState, val => Model.ImageCurrentState = val, value); } public ControlTemplate ImageCurrentStateResult { get => Model.ImageCurrentStateResult; set => SetProperty(() => Model.ImageCurrentStateResult, val => Model.ImageCurrentStateResult = val, value); } public string TextCurrentState { get => Model.TextCurrentState; set => SetProperty(() => Model.TextCurrentState, val => Model.TextCurrentState = val, value); } public ProjectItem CurrentProject { get => Model.CurrentProject; set => SetProperty(() => Model.CurrentProject, val => Model.CurrentProject = val, value); } public ObservableCollection<ValueIndicator> ValueIndicators => Model.ValueIndicators; public SolutionItem SolutionItem => Model.SolutionItem; public ObservableCollection<ProjectItem> ProjectsList => Model.SolutionItem.Projects; public string GridGroupPropertyName { get { return ControlSettings.GridSettings.GroupName; } set { if (ControlSettings.GridSettings.GroupName != value) { ControlSettings.GridSettings.GroupName = value; OnPropertyChanged(nameof(GridGroupPropertyName)); OnPropertyChanged(nameof(GroupedProjectsList)); OnPropertyChanged(nameof(GridColumnsGroupMenuItems)); OnPropertyChanged(nameof(GridGroupHeaderName)); } } } public string GridGroupHeaderName { get { if (string.IsNullOrEmpty(GridGroupPropertyName)) return string.Empty; return ControlSettings.GridSettings.Columns[GridGroupPropertyName].Header; } } public CompositeCollection GridColumnsGroupMenuItems => CreateContextMenu(); private CompositeCollection CreateContextMenu() { var collection = new CompositeCollection(); collection.Add(new MenuItem { Header = Resources.NoneMenuItem, Tag = string.Empty }); foreach (GridColumnSettings column in ControlSettings.GridSettings.Columns) { if (!ColumnsManager.ColumnIsGroupable(column)) continue; string header = column.Header; var menuItem = new MenuItem { Header = !string.IsNullOrEmpty(header) ? header : ColumnsManager.GetInitialColumnHeader(column), Tag = column.PropertyNameId }; collection.Add(menuItem); } foreach (MenuItem menuItem in collection) { menuItem.IsCheckable = false; menuItem.StaysOpenOnClick = false; menuItem.IsChecked = (GridGroupPropertyName == (string) menuItem.Tag); menuItem.Command = GridGroupPropertyMenuItemClicked; menuItem.CommandParameter = menuItem.Tag; } return collection; } public SortDescription GridSortDescription { get => ControlSettings.GridSettings.Sort; set { if (ControlSettings.GridSettings.Sort != value) { ControlSettings.GridSettings.Sort = value; OnPropertyChanged(nameof(GridSortDescription)); OnPropertyChanged(nameof(GroupedProjectsList)); } } } // Should be initialized by View. public void SetGridColumnsRef(ObservableCollection<DataGridColumn> gridColumnsRef) { if (_gridColumnsRef != gridColumnsRef) { _gridColumnsRef = gridColumnsRef; GenerateColumns(); } } // TODO: Rewrite using CollectionViewSource? // http://stackoverflow.com/questions/11505283/re-sort-wpf-datagrid-after-bounded-data-has-changed public ListCollectionView GroupedProjectsList { get { var groupedList = new ListCollectionView(ProjectsList); if (!string.IsNullOrWhiteSpace(GridGroupPropertyName)) { Debug.Assert(groupedList.GroupDescriptions != null); groupedList.GroupDescriptions.Add(new PropertyGroupDescription(GridGroupPropertyName)); } groupedList.CustomSort = GetProjectItemSorter(GridSortDescription); groupedList.IsLiveGrouping = true; groupedList.IsLiveSorting = true; return groupedList; } } public DataGridHeadersVisibility GridHeadersVisibility { get { return ControlSettings.GridSettings.ShowColumnsHeader ? DataGridHeadersVisibility.Column : DataGridHeadersVisibility.None; } set { bool showColumnsHeader = (value != DataGridHeadersVisibility.None); if (ControlSettings.GridSettings.ShowColumnsHeader != showColumnsHeader) { ControlSettings.GridSettings.ShowColumnsHeader = showColumnsHeader; OnPropertyChanged(nameof(GridHeadersVisibility)); } } } private ProjectItem _selectedProjectItem; public ProjectItem SelectedProjectItem { get => _selectedProjectItem; set => SetProperty(ref _selectedProjectItem, value); } public ControlViewModel(ControlModel model, ControlSettings controlSettings) { Model = model; ControlSettings = controlSettings; BuildProgressViewModel = new BuildProgressViewModel(ControlSettings); } /// <summary> /// Uses as design-time ViewModel. /// </summary> internal ControlViewModel() { Model = new ControlModel(); ControlSettings = new ControlSettings(); BuildProgressViewModel = new BuildProgressViewModel(ControlSettings); } private void OpenContainingFolder() { try { string dir = Path.GetDirectoryName(SelectedProjectItem.FullName); Debug.Assert(dir != null); Process.Start(dir); } catch (Exception ex) { ex.Trace(string.Format( "Unable to open folder '{0}' containing the project '{1}'.", SelectedProjectItem.FullName, SelectedProjectItem.UniqueName)); MessageBox.Show( ex.Message + "\n\nSee log for details.", Resources.ProductName, MessageBoxButton.OK, MessageBoxImage.Error); } } private void ReorderGrid(object obj) { var e = (DataGridSortingEventArgs)obj; ListSortDirection? oldSortDirection = e.Column.SortDirection; ListSortDirection? newSortDirection; switch (oldSortDirection) { case null: newSortDirection = ListSortDirection.Ascending; break; case ListSortDirection.Ascending: newSortDirection = ListSortDirection.Descending; break; case ListSortDirection.Descending: newSortDirection = null; break; default: throw new ArgumentOutOfRangeException(nameof(obj)); } e.Handled = true; e.Column.SortDirection = newSortDirection; GridSortDescription = new SortDescription(newSortDirection.ToMedia(), e.Column.GetBindedProperty()); } private static ProjectItemColumnSorter GetProjectItemSorter(SortDescription sortDescription) { SortOrder sortOrder = sortDescription.Order; string sortPropertyName = sortDescription.Property; if (sortOrder != SortOrder.None && !string.IsNullOrEmpty(sortPropertyName)) { ListSortDirection? sortDirection = sortOrder.ToSystem(); Debug.Assert(sortDirection != null); try { return new ProjectItemColumnSorter(sortDirection.Value, sortPropertyName); } catch (PropertyNotFoundException ex) { ex.Trace("Trying to sort Project Items by nonexistent property."); return null; } } return null; } public void ResetIndicators(ResetIndicatorMode resetMode) { foreach (ValueIndicator indicator in ValueIndicators) indicator.ResetValue(resetMode); OnPropertyChanged(nameof(ValueIndicators)); } public void UpdateIndicators(IBuildInfo buildContext) { foreach (ValueIndicator indicator in ValueIndicators) indicator.UpdateValue(buildContext); OnPropertyChanged(nameof(ValueIndicators)); } public void GenerateColumns() { Debug.Assert(_gridColumnsRef != null); ColumnsManager.GenerateColumns(_gridColumnsRef, ControlSettings.GridSettings); } public void SyncColumnSettings() { Debug.Assert(_gridColumnsRef != null); ColumnsManager.SyncColumnSettings(_gridColumnsRef, ControlSettings.GridSettings); } public void OnControlSettingsChanged(ControlSettings settings, Func<IBuildInfo, string> getBuildMessage) { ControlSettings.InitFrom(settings); GenerateColumns(); if (_buildState == BuildState.Done) { Model.TextCurrentState = getBuildMessage(_buildInfo); } // Raise all properties have changed. OnPropertyChanged(null); BuildProgressViewModel.ResetTaskBarInfo(false); } public void OnBuildProjectBegin() { BuildProgressViewModel.OnBuildProjectBegin(); } public void OnBuildProjectDone(BuildedProject buildedProjectInfo) { bool success = buildedProjectInfo.Success.GetValueOrDefault(true); BuildProgressViewModel.OnBuildProjectDone(success); } public void OnBuildBegin(int projectsCount, IBuildInfo buildContext) { _buildState = BuildState.InProgress; _buildInfo = buildContext; BuildProgressViewModel.OnBuildBegin(projectsCount); } public void OnBuildDone(IBuildInfo buildInfo) { _buildInfo = buildInfo; _buildState = BuildState.Done; BuildProgressViewModel.OnBuildDone(); } public void OnBuildCancelled(IBuildInfo buildInfo) { _buildInfo = buildInfo; BuildProgressViewModel.OnBuildCancelled(); } private bool IsProjectItemEnabledForActions() { return (SelectedProjectItem != null && !string.IsNullOrEmpty(SelectedProjectItem.UniqueName) && !SelectedProjectItem.IsBatchBuildProject); } #region Commands public ICommand ReportIssues => new RelayCommand(obj => GithubHelper.OpenBrowserWithPrefilledIssue()); public ICommand GridSorting => new RelayCommand(obj => ReorderGrid(obj)); public ICommand GridGroupPropertyMenuItemClicked => new RelayCommand(obj => GridGroupPropertyName = (obj != null) ? obj.ToString() : string.Empty); public ICommand SelectedProjectOpenContainingFolderAction => new RelayCommand(obj => OpenContainingFolder(), canExecute: obj => (SelectedProjectItem != null && !string.IsNullOrEmpty(SelectedProjectItem.FullName))); public ICommand SelectedProjectCopyBuildOutputFilesToClipboardAction => new RelayCommand( obj => ProjectCopyBuildOutputFilesToClipBoard(SelectedProjectItem), canExecute: obj => (SelectedProjectItem != null && !string.IsNullOrEmpty(SelectedProjectItem.UniqueName) && !ControlSettings.ProjectItemSettings.CopyBuildOutputFileTypesToClipboard.IsEmpty)); public ICommand SelectedProjectBuildAction => new RelayCommand( obj => RaiseCommandForSelectedProject(SelectedProjectItem, (int)VSConstants.VSStd97CmdID.BuildCtx), canExecute: obj => IsProjectItemEnabledForActions()); public ICommand SelectedProjectRebuildAction => new RelayCommand( obj => RaiseCommandForSelectedProject(SelectedProjectItem, (int)VSConstants.VSStd97CmdID.RebuildCtx), canExecute: obj => IsProjectItemEnabledForActions()); public ICommand SelectedProjectCleanAction => new RelayCommand( obj => RaiseCommandForSelectedProject(SelectedProjectItem, (int)VSConstants.VSStd97CmdID.CleanCtx), canExecute: obj => IsProjectItemEnabledForActions()); public ICommand SelectedProjectCopyErrorMessagesAction => new RelayCommand(obj => CopyErrorMessageToClipboard(SelectedProjectItem), canExecute: obj => SelectedProjectItem?.ErrorsCount > 0); public ICommand BuildSolutionAction => new RelayCommand(obj => BuildSolution()); public ICommand RebuildSolutionAction => new RelayCommand(obj => RebuildSolution()); public ICommand CleanSolutionAction => new RelayCommand(obj => CleanSolution()); public ICommand CancelBuildSolutionAction => new RelayCommand(obj => CancelBuildSolution()); public ICommand OpenGridColumnsSettingsAction => new RelayCommand(obj => ShowGridColumnsSettingsPage()); public ICommand OpenGeneralSettingsAction => new RelayCommand(obj => ShowGeneralSettingsPage()); #endregion public event Action ShowGridColumnsSettingsPage; public event Action ShowGeneralSettingsPage; public event Action BuildSolution; public event Action CleanSolution; public event Action RebuildSolution; public event Action CancelBuildSolution; public event Action<ProjectItem> ProjectCopyBuildOutputFilesToClipBoard; public event Action<ProjectItem, int> RaiseCommandForSelectedProject; public event Action<ProjectItem> CopyErrorMessageToClipboard; } }
using System; using System.Collections.Generic; using xsc = DotNetXmlSwfChart; namespace testWeb.tests { public class FloatingColumnTwo : ChartTestBase { #region ChartInclude public override DotNetXmlSwfChart.ChartHTML ChartInclude { get { DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "ff9922"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override DotNetXmlSwfChart.Chart Chart { get { xsc.Chart c = new xsc.Chart(); c.AddChartType(xsc.XmlSwfChartType.ColumnFloating); c.AxisCategory = SetAxisCategory(c.ChartType[0]); c.AxisTicks = SetAxisTicks(); c.AxisValue = SetAxisValue(); c.ChartBorder = SetChartBorder(); c.Data = SetChartData(); c.ChartGridH = SetChartGridH(); c.ChartRectangle = SetChartRectangle(); c.AddDrawImage(GetDrawImage()); c.AddDrawText(GetDrawText(1)); c.AddDrawText(GetDrawText(2)); c.AddDrawText(GetDrawText(3)); c.AddDrawText(GetDrawText(4)); c.AddDrawText(GetDrawText(5)); c.LegendRectangle = SetLegendRectangle(); c.AddSeriesColor("666666"); c.SeriesGap = SetSeriesGap(); return c; } } #endregion #region Helpers #region SetSeriesGap() private xsc.SeriesGap SetSeriesGap() { xsc.SeriesGap sg = new xsc.SeriesGap(); sg.SetGap = 20; sg.BarGap = 0; return sg; } #endregion #region SetLegendRectangle() private xsc.LegendRectangle SetLegendRectangle() { xsc.LegendRectangle lr = new xsc.LegendRectangle(); lr.X = -100; lr.Y = -100; lr.Width = 10; lr.Height = 10; lr.Margin = 0; return lr; } #endregion #region GetDrawText(int number) private xsc.DrawText GetDrawText(int number) { xsc.DrawText text = new xsc.DrawText(); text.Width = 400; text.Height = 400; text.HAlign = xsc.TextHAlign.left; switch (number) { case 1: text.Color = "ffffff"; text.Alpha = 20; text.Rotation = -10; text.Size = 200; text.X = 290; text.Y = -15; text.Text = "&"; break; case 2: text.Color = "000000"; text.Alpha = 5; text.Rotation = 0; text.Size = 90; text.X = 69; text.Y = -33; text.Text = "music"; break; case 3: text.Color = "88ff00"; text.Alpha = 50; text.Rotation = 0; text.Size = 90; text.X = 66; text.Y = -36; text.Text = "music"; break; case 4: text.Color = "000000"; text.Alpha = 3; text.Rotation = 3; text.Size = 150; text.X = 22390; text.Y = 153; text.Text = "sound"; break; case 5: text.Color = "ff6644"; text.Alpha = 40; text.Rotation = 3; text.Size = 150; text.X = 20; text.Y = 150; text.Text = "sound"; break; } return text; } #endregion #region GetDrawImage() private DotNetXmlSwfChart.DrawImage GetDrawImage() { xsc.DrawImage di = new xsc.DrawImage(); di.Alpha = 0; di.Url = "images/slow.swf"; return di; } #endregion #region SetChartRectangle() private DotNetXmlSwfChart.ChartRectangle SetChartRectangle() { xsc.ChartRectangle cr = new xsc.ChartRectangle(); cr.X = 75; cr.Y = 50; cr.Width = 300; cr.Height = 180; cr.PositiveColor = "88ff00"; cr.PositiveAlpha = 80; cr.NegativeColor = "88ff00"; cr.NegativeAlpha = 80; return cr; } #endregion #region SetChartGridH() private xsc.ChartGrid SetChartGridH() { xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal); cg.Alpha = 10; cg.Color = "ffffff"; cg.Thickness = 12; cg.GridLineType = xsc.ChartGridLineType.solid; return cg; } #endregion #region SetChartData() private xsc.ChartData SetChartData() { xsc.ChartData d = new xsc.ChartData(); d.AddDataPoint("hi", "1", 59); d.AddDataPoint("hi", "2", 35); d.AddDataPoint("hi", "3", 81); d.AddDataPoint("hi", "4", 44); d.AddDataPoint("hi", "5", 74); d.AddDataPoint("hi", "6", 20); d.AddDataPoint("hi", "7", 51); d.AddDataPoint("hi", "8", 25); d.AddDataPoint("hi", "9", 58); d.AddDataPoint("hi", "10", 7); d.AddDataPoint("hi", "11", 60); d.AddDataPoint("hi", "12", 2); d.AddDataPoint("hi", "13", 4); d.AddDataPoint("hi", "14", 84); d.AddDataPoint("hi", "15", 51); d.AddDataPoint("hi", "16", 88); d.AddDataPoint("hi", "17", 8); d.AddDataPoint("hi", "18", 66); d.AddDataPoint("hi", "19", 4); d.AddDataPoint("hi", "20", 21); d.AddDataPoint("hi", "21", 89); d.AddDataPoint("hi", "22", 70); d.AddDataPoint("hi", "23", 25); d.AddDataPoint("hi", "24", 61); d.AddDataPoint("hi", "25", 56); d.AddDataPoint("hi", "26", 57); d.AddDataPoint("hi", "27", 31); d.AddDataPoint("hi", "28", 84); d.AddDataPoint("hi", "29", 77); d.AddDataPoint("hi", "30", 49); d.AddDataPoint("hi", "31", 35); d.AddDataPoint("hi", "32", 46); d.AddDataPoint("hi", "33", 83); d.AddDataPoint("hi", "34", 25); d.AddDataPoint("hi", "35", 89); d.AddDataPoint("hi", "36", 67); d.AddDataPoint("hi", "37", 45); d.AddDataPoint("hi", "38", 50); d.AddDataPoint("hi", "39", 1); d.AddDataPoint("hi", "40", 12); d.AddDataPoint("hi", "41", 57); d.AddDataPoint("hi", "42", 61); d.AddDataPoint("hi", "43", 13); d.AddDataPoint("hi", "44", 61); d.AddDataPoint("hi", "45", 54); d.AddDataPoint("hi", "46", 64); d.AddDataPoint("hi", "47", 58); d.AddDataPoint("hi", "48", 62); d.AddDataPoint("hi", "49", 39); d.AddDataPoint("hi", "50", 61); d.AddDataPoint("hi", "51", 82); d.AddDataPoint("hi", "52", 38); d.AddDataPoint("hi", "53", 41); d.AddDataPoint("hi", "54", 17); d.AddDataPoint("hi", "55", 8); d.AddDataPoint("hi", "56", 7); d.AddDataPoint("hi", "57", 74); d.AddDataPoint("hi", "58", 39); d.AddDataPoint("hi", "59", 1); d.AddDataPoint("hi", "60", 60); d.AddDataPoint("hi", "61", 87); d.AddDataPoint("hi", "62", 35); d.AddDataPoint("hi", "63", 15); d.AddDataPoint("hi", "64", 79); d.AddDataPoint("hi", "65", 59); d.AddDataPoint("hi", "66", 14); d.AddDataPoint("hi", "67", 55); d.AddDataPoint("hi", "68", 14); d.AddDataPoint("hi", "69", 64); d.AddDataPoint("hi", "70", 56); d.AddDataPoint("hi", "71", 25); d.AddDataPoint("hi", "72", 31); d.AddDataPoint("hi", "73", 26); d.AddDataPoint("hi", "74", 38); d.AddDataPoint("hi", "75", 1); d.AddDataPoint("hi", "76", 80); d.AddDataPoint("hi", "77", 12); d.AddDataPoint("hi", "78", 58); d.AddDataPoint("hi", "79", 51); d.AddDataPoint("hi", "80", 50); d.AddDataPoint("hi", "81", 29); d.AddDataPoint("hi", "82", 43); d.AddDataPoint("hi", "83", 87); d.AddDataPoint("hi", "84", 70); d.AddDataPoint("hi", "85", 59); d.AddDataPoint("hi", "86", 5); d.AddDataPoint("hi", "87", 76); d.AddDataPoint("hi", "88", 42); d.AddDataPoint("hi", "89", 43); d.AddDataPoint("hi", "90", 76); d.AddDataPoint("hi", "91", 12); d.AddDataPoint("hi", "92", 40); d.AddDataPoint("hi", "93", 20); d.AddDataPoint("hi", "94", 27); d.AddDataPoint("hi", "95", 29); d.AddDataPoint("hi", "96", 79); d.AddDataPoint("hi", "97", 41); d.AddDataPoint("hi", "98", 83); d.AddDataPoint("hi", "99", 2); d.AddDataPoint("lo", "1", -59); d.AddDataPoint("lo", "2", -35); d.AddDataPoint("lo", "3", -81); d.AddDataPoint("lo", "4", -44); d.AddDataPoint("lo", "5", -74); d.AddDataPoint("lo", "6", -20); d.AddDataPoint("lo", "7", -51); d.AddDataPoint("lo", "8", -25); d.AddDataPoint("lo", "9", -58); d.AddDataPoint("lo", "10", -7); d.AddDataPoint("lo", "11", -60); d.AddDataPoint("lo", "12", -2); d.AddDataPoint("lo", "13", -4); d.AddDataPoint("lo", "14", -84); d.AddDataPoint("lo", "15", -51); d.AddDataPoint("lo", "16", -88); d.AddDataPoint("lo", "17", -8); d.AddDataPoint("lo", "18", -66); d.AddDataPoint("lo", "19", -4); d.AddDataPoint("lo", "20", -21); d.AddDataPoint("lo", "21", -89); d.AddDataPoint("lo", "22", -70); d.AddDataPoint("lo", "23", -25); d.AddDataPoint("lo", "24", -61); d.AddDataPoint("lo", "25", -56); d.AddDataPoint("lo", "26", -57); d.AddDataPoint("lo", "27", -31); d.AddDataPoint("lo", "28", -84); d.AddDataPoint("lo", "29", -77); d.AddDataPoint("lo", "30", -49); d.AddDataPoint("lo", "31", -35); d.AddDataPoint("lo", "32", -46); d.AddDataPoint("lo", "33", -83); d.AddDataPoint("lo", "34", -25); d.AddDataPoint("lo", "35", -89); d.AddDataPoint("lo", "36", -67); d.AddDataPoint("lo", "37", -45); d.AddDataPoint("lo", "38", -50); d.AddDataPoint("lo", "39", -1); d.AddDataPoint("lo", "40", -12); d.AddDataPoint("lo", "41", -57); d.AddDataPoint("lo", "42", -61); d.AddDataPoint("lo", "43", -13); d.AddDataPoint("lo", "44", -61); d.AddDataPoint("lo", "45", -54); d.AddDataPoint("lo", "46", -64); d.AddDataPoint("lo", "47", -58); d.AddDataPoint("lo", "48", -62); d.AddDataPoint("lo", "49", -39); d.AddDataPoint("lo", "50", -61); d.AddDataPoint("lo", "51", -82); d.AddDataPoint("lo", "52", -38); d.AddDataPoint("lo", "53", -41); d.AddDataPoint("lo", "54", -17); d.AddDataPoint("lo", "55", -8); d.AddDataPoint("lo", "56", -7); d.AddDataPoint("lo", "57", -74); d.AddDataPoint("lo", "58", -39); d.AddDataPoint("lo", "59", -1); d.AddDataPoint("lo", "60", -60); d.AddDataPoint("lo", "61", -87); d.AddDataPoint("lo", "62", -35); d.AddDataPoint("lo", "63", -15); d.AddDataPoint("lo", "64", -79); d.AddDataPoint("lo", "65", -59); d.AddDataPoint("lo", "66", -14); d.AddDataPoint("lo", "67", -55); d.AddDataPoint("lo", "68", -14); d.AddDataPoint("lo", "69", -64); d.AddDataPoint("lo", "70", -56); d.AddDataPoint("lo", "71", -25); d.AddDataPoint("lo", "72", -31); d.AddDataPoint("lo", "73", -26); d.AddDataPoint("lo", "74", -38); d.AddDataPoint("lo", "75", -1); d.AddDataPoint("lo", "76", -80); d.AddDataPoint("lo", "77", -12); d.AddDataPoint("lo", "78", -58); d.AddDataPoint("lo", "79", -51); d.AddDataPoint("lo", "80", -50); d.AddDataPoint("lo", "81", -29); d.AddDataPoint("lo", "82", -43); d.AddDataPoint("lo", "83", -87); d.AddDataPoint("lo", "84", -70); d.AddDataPoint("lo", "85", -59); d.AddDataPoint("lo", "86", -5); d.AddDataPoint("lo", "87", -76); d.AddDataPoint("lo", "88", -42); d.AddDataPoint("lo", "89", -43); d.AddDataPoint("lo", "90", -76); d.AddDataPoint("lo", "91", -12); d.AddDataPoint("lo", "92", -40); d.AddDataPoint("lo", "93", -20); d.AddDataPoint("lo", "94", -27); d.AddDataPoint("lo", "95", -29); d.AddDataPoint("lo", "96", -79); d.AddDataPoint("lo", "97", -41); d.AddDataPoint("lo", "98", -83); d.AddDataPoint("lo", "99", -2); return d; } #endregion #region SetChartBorder() private xsc.ChartBorder SetChartBorder() { xsc.ChartBorder cb = new xsc.ChartBorder(); cb.Color = "8888ff"; cb.TopThickness = 2; cb.BottomThickness = 2; cb.LeftThickness = 2; cb.RightThickness = 2; return cb; } #endregion #region SetAxisValue() private xsc.AxisValue SetAxisValue() { xsc.AxisValue av = new xsc.AxisValue(); av.Font = "Arial"; av.Bold = true; av.Size = 10; av.Color = "ffffff"; av.Alpha = 75; av.Steps = 4; av.Prefix = ""; av.Suffix = ""; av.Decimals = 0; av.Separator = ""; av.ShowMin = true; av.Max = 100; av.Min = -100; return av; } #endregion #region SetAxisTicks() private xsc.AxisTicks SetAxisTicks() { xsc.AxisTicks at = new xsc.AxisTicks(); at.ValueTicks = true; at.CategoryTicks = false; at.MajorThickness = 2; at.MinorThickness = 1; at.MinorCount = 1; at.MajorColor = "8888ff"; at.MinorColor = "ff4400"; at.Position = "outside"; return at; } #endregion #region SetAxisCategory() private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType type) { xsc.AxisCategory ac = new xsc.AxisCategory(type); ac.Alpha = 0; return ac; } #endregion #endregion } }
// 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.Diagnostics; using System.Threading.Tasks; using System.Windows.Controls; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.UnitTests.Classification; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo { public abstract class AbstractSemanticQuickInfoSourceTests { protected readonly ClassificationBuilder ClassificationBuilder; protected AbstractSemanticQuickInfoSourceTests() { this.ClassificationBuilder = new ClassificationBuilder(); } [DebuggerStepThrough] protected Tuple<string, string> Struct(string value) { return ClassificationBuilder.Struct(value); } [DebuggerStepThrough] protected Tuple<string, string> Enum(string value) { return ClassificationBuilder.Enum(value); } [DebuggerStepThrough] protected Tuple<string, string> Interface(string value) { return ClassificationBuilder.Interface(value); } [DebuggerStepThrough] protected Tuple<string, string> Class(string value) { return ClassificationBuilder.Class(value); } [DebuggerStepThrough] protected Tuple<string, string> Delegate(string value) { return ClassificationBuilder.Delegate(value); } [DebuggerStepThrough] protected Tuple<string, string> TypeParameter(string value) { return ClassificationBuilder.TypeParameter(value); } [DebuggerStepThrough] protected Tuple<string, string> String(string value) { return ClassificationBuilder.String(value); } [DebuggerStepThrough] protected Tuple<string, string> Verbatim(string value) { return ClassificationBuilder.Verbatim(value); } [DebuggerStepThrough] protected Tuple<string, string> Keyword(string value) { return ClassificationBuilder.Keyword(value); } [DebuggerStepThrough] protected Tuple<string, string> WhiteSpace(string value) { return ClassificationBuilder.WhiteSpace(value); } [DebuggerStepThrough] protected Tuple<string, string> Text(string value) { return ClassificationBuilder.Text(value); } [DebuggerStepThrough] protected Tuple<string, string> NumericLiteral(string value) { return ClassificationBuilder.NumericLiteral(value); } [DebuggerStepThrough] protected Tuple<string, string> PPKeyword(string value) { return ClassificationBuilder.PPKeyword(value); } [DebuggerStepThrough] protected Tuple<string, string> PPText(string value) { return ClassificationBuilder.PPText(value); } [DebuggerStepThrough] protected Tuple<string, string> Identifier(string value) { return ClassificationBuilder.Identifier(value); } [DebuggerStepThrough] protected Tuple<string, string> Inactive(string value) { return ClassificationBuilder.Inactive(value); } [DebuggerStepThrough] protected Tuple<string, string> Comment(string value) { return ClassificationBuilder.Comment(value); } [DebuggerStepThrough] protected Tuple<string, string> Number(string value) { return ClassificationBuilder.Number(value); } protected ClassificationBuilder.PunctuationClassificationTypes Punctuation { get { return ClassificationBuilder.Punctuation; } } protected ClassificationBuilder.OperatorClassificationTypes Operators { get { return ClassificationBuilder.Operator; } } protected ClassificationBuilder.XmlDocClassificationTypes XmlDoc { get { return ClassificationBuilder.XmlDoc; } } protected string Lines(params string[] lines) { return string.Join("\r\n", lines); } protected Tuple<string, string>[] ExpectedClassifications( params Tuple<string, string>[] expectedClassifications) { return expectedClassifications; } protected Tuple<string, string>[] NoClassifications() { return null; } protected void WaitForDocumentationComment(object content) { if (content is QuickInfoDisplayDeferredContent deferredContent) { if (deferredContent.Documentation is DocumentationCommentDeferredContent docCommentDeferredContent) { docCommentDeferredContent.WaitForDocumentationCommentTask_ForTestingPurposesOnly(); } } } internal Action<object> SymbolGlyph(Glyph expectedGlyph) { return (content) => { var actualIcon = ((QuickInfoDisplayDeferredContent)content).SymbolGlyph; Assert.Equal(expectedGlyph, actualIcon.Glyph); }; } protected Action<object> MainDescription( string expectedText, Tuple<string, string>[] expectedClassifications = null) { return content => { switch (content) { case QuickInfoDisplayDeferredContent qiContent: { var actualContent = qiContent.MainDescription.ClassifiableContent; ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent); } break; case ClassifiableDeferredContent classifiable: { var actualContent = classifiable.ClassifiableContent; ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent); } break; } }; } protected Action<object> Documentation( string expectedText, Tuple<string, string>[] expectedClassifications = null) { return content => { var documentationCommentContent = ((QuickInfoDisplayDeferredContent)content).Documentation; switch (documentationCommentContent) { case DocumentationCommentDeferredContent docComment: { var documentationCommentBlock = (TextBlock)docComment.Create(); var actualText = documentationCommentBlock.Text; Assert.Equal(expectedText, actualText); } break; case ClassifiableDeferredContent classifiable: { var actualContent = classifiable.ClassifiableContent; Assert.Equal(expectedText, actualContent.GetFullText()); ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent); } break; } }; } protected Action<object> TypeParameterMap( string expectedText, Tuple<string, string>[] expectedClassifications = null) { return (content) => { var actualContent = ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent; // The type parameter map should have an additional line break at the beginning. We // create a copy here because we've captured expectedText and this delegate might be // executed more than once (e.g. with different parse options). // var expectedTextCopy = "\r\n" + expectedText; ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent); }; } protected Action<object> AnonymousTypes( string expectedText, Tuple<string, string>[] expectedClassifications = null) { return (content) => { var actualContent = ((QuickInfoDisplayDeferredContent)content).AnonymousTypes.ClassifiableContent; // The type parameter map should have an additional line break at the beginning. We // create a copy here because we've captured expectedText and this delegate might be // executed more than once (e.g. with different parse options). // var expectedTextCopy = "\r\n" + expectedText; ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent); }; } protected Action<object> NoTypeParameterMap { get { return (content) => { Assert.Equal(string.Empty, ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent.GetFullText()); }; } } protected Action<object> Usage(string expectedText, bool expectsWarningGlyph = false) { return (content) => { var quickInfoContent = (QuickInfoDisplayDeferredContent)content; Assert.Equal(expectedText, quickInfoContent.UsageText.ClassifiableContent.GetFullText()); Assert.Equal(expectsWarningGlyph, quickInfoContent.WarningGlyph != null && quickInfoContent.WarningGlyph.Glyph == Glyph.CompletionWarning); }; } protected Action<object> Exceptions(string expectedText) { return (content) => { var quickInfoContent = (QuickInfoDisplayDeferredContent)content; Assert.Equal(expectedText, quickInfoContent.ExceptionText.ClassifiableContent.GetFullText()); }; } protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } protected abstract Task TestAsync(string markup, params Action<object>[] expectedResults); } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows.Controls; using System.Windows; using WPFDemo.Common.Extensions; namespace WPFDemo.Presentation.Controls.ListBox { [TemplatePart(Name = PART_BulletChrome, Type = typeof(Microsoft.Windows.Themes.BulletChrome))] public class CheckedListBoxExItem : ListBoxItem { #region Constants private const string PART_BulletChrome = "PART_BulletChrome"; #endregion #region Static Members static CheckedListBoxExItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CheckedListBoxExItem), new FrameworkPropertyMetadata(typeof(CheckedListBoxExItem))); EventManager.RegisterClassHandler(typeof(CheckedListBoxExItem), MouseDownEvent, new System.Windows.Input.MouseButtonEventHandler(OnPreviewMouseDownEvent)); EventManager.RegisterClassHandler(typeof(CheckedListBoxExItem), MouseDoubleClickEvent, new System.Windows.Input.MouseButtonEventHandler(OnPreviewMouseDoubleClick)); } public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register( "IsChecked", typeof(bool), typeof(CheckedListBoxExItem), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, IsChecked_PropertyChanged) ); public static readonly DependencyProperty IsCheckBoxEnabledProperty = DependencyProperty.Register( "IsCheckBoxEnabled", typeof(bool), typeof(CheckedListBoxExItem), new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.None, IsCheckBoxEnabled_PropertyChanged) ); public static readonly DependencyProperty ClickSelectModeProperty = DependencyProperty.Register( "ClickSelectMode", typeof(CheckedListBoxExClickSelectMode), typeof(CheckedListBoxExItem), new FrameworkPropertyMetadata(CheckedListBoxExClickSelectMode.DoubleClick, FrameworkPropertyMetadataOptions.None, CheckedListBoxExClickSelectMode_PropertyChanged) ); private static void IsChecked_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Item = o as CheckedListBoxExItem; if (Item == null) return; Item.OnIsCheckedChanged(); } private static void IsCheckBoxEnabled_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Item = o as CheckedListBoxExItem; if (Item == null) return; Item.OnIsCheckBoxEnabledChanged(); } private static void CheckedListBoxExClickSelectMode_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { var Item = o as CheckedListBoxExItem; if (Item == null) return; Item.OnClickSelectModeChanged(); } public static readonly RoutedEvent IsCheckedChangedEvent = EventManager.RegisterRoutedEvent( "IsCheckedChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CheckedListBoxExItem) ); public static readonly RoutedEvent IsCheckBoxEnabledChangedEvent = EventManager.RegisterRoutedEvent( "IsCheckBoxEnabledChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CheckedListBoxExItem) ); public static readonly RoutedEvent ClickSelectModeChangedEvent = EventManager.RegisterRoutedEvent( "ClickSelectModeChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CheckedListBoxExItem) ); private static void OnPreviewMouseDownEvent(object sender, System.Windows.Input.MouseButtonEventArgs e) { var Sender = sender as CheckedListBoxExItem; if (Sender == null || e.LeftButton != System.Windows.Input.MouseButtonState.Pressed || !Sender.IsCheckBoxEnabled) return; switch (Sender.ClickSelectMode) { case CheckedListBoxExClickSelectMode.SingleClick: Sender.IsChecked = !Sender.IsChecked; break; } } private static void OnPreviewMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { var Sender = sender as CheckedListBoxExItem; if (Sender == null || e.LeftButton != System.Windows.Input.MouseButtonState.Pressed || !Sender.IsCheckBoxEnabled) return; switch (Sender.ClickSelectMode) { case CheckedListBoxExClickSelectMode.DoubleClick: Sender.IsChecked = !Sender.IsChecked; break; } } #endregion #region Global Variables private Microsoft.Windows.Themes.BulletChrome _BulletChrome; #endregion #region Properties private Microsoft.Windows.Themes.BulletChrome BulletChrome { get { return _BulletChrome; } set { if (_BulletChrome != null) DetachBulletChrome(_BulletChrome); _BulletChrome = value; if (_BulletChrome != null) AttachBulletChrome(_BulletChrome); } } private void AttachBulletChrome(Microsoft.Windows.Themes.BulletChrome bulletChrome) { if (bulletChrome == null) throw new ArgumentNullException("bulletChrome"); bulletChrome.MouseDown += BulletChrome_MouseDown; } private void DetachBulletChrome(Microsoft.Windows.Themes.BulletChrome bulletChrome) { if (bulletChrome == null) throw new ArgumentNullException("bulletChrome"); bulletChrome.MouseDown -= BulletChrome_MouseDown; } public bool IsChecked { get { return (bool)GetValue(IsCheckedProperty); } set { SetValue(IsCheckedProperty, value); } } public bool IsCheckBoxEnabled { get { return (bool)GetValue(IsCheckBoxEnabledProperty); } set { SetValue(IsCheckBoxEnabledProperty, value); } } public CheckedListBoxExClickSelectMode ClickSelectMode { get { return (CheckedListBoxExClickSelectMode)GetValue(ClickSelectModeProperty); } set { SetValue(ClickSelectModeProperty, value); } } #endregion #region Events public event RoutedEventHandler IsCheckedChanged { add { AddHandler(IsCheckedChangedEvent, value); } remove { RemoveHandler(IsCheckedChangedEvent, value); } } public event RoutedEventHandler IsCheckBoxEnabledChanged { add { AddHandler(IsCheckBoxEnabledChangedEvent, value); } remove { RemoveHandler(IsCheckBoxEnabledChangedEvent, value); } } public event RoutedEventHandler ClickSelectModeChanged { add { AddHandler(ClickSelectModeChangedEvent, value); } remove { RemoveHandler(ClickSelectModeChangedEvent, value); } } #endregion #region Event Handlers private void BulletChrome_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { if (!this.IsCheckBoxEnabled) return; this.IsChecked = !this.IsChecked; //If the owning listbox is in single selection mode, select the item var ListBox = this.FindVisualParent<System.Windows.Controls.ListBox>(); if (ListBox != null && ListBox.SelectionMode == SelectionMode.Single) this.IsSelected = true; //Focus on the item this.Focus(); e.Handled = true; } #endregion #region Methods public override void OnApplyTemplate() { base.OnApplyTemplate(); this.BulletChrome = this.GetTemplateChild("PART_BulletChrome") as Microsoft.Windows.Themes.BulletChrome; } protected virtual void OnIsCheckedChanged() { this.RaiseEvent(new RoutedEventArgs(IsCheckedChangedEvent)); } protected virtual void OnIsCheckBoxEnabledChanged() { this.RaiseEvent(new RoutedEventArgs(IsCheckBoxEnabledChangedEvent)); } protected virtual void OnClickSelectModeChanged() { this.RaiseEvent(new RoutedEventArgs(ClickSelectModeChangedEvent)); } #endregion } public enum CheckedListBoxExClickSelectMode { None = 0, SingleClick = 1, DoubleClick = 2 } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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; namespace Spine { public class Triangulator { private readonly ExposedList<ExposedList<float>> convexPolygons = new ExposedList<ExposedList<float>>(); private readonly ExposedList<ExposedList<int>> convexPolygonsIndices = new ExposedList<ExposedList<int>>(); private readonly ExposedList<int> indicesArray = new ExposedList<int>(); private readonly ExposedList<bool> isConcaveArray = new ExposedList<bool>(); private readonly ExposedList<int> triangles = new ExposedList<int>(); private readonly Pool<ExposedList<float>> polygonPool = new Pool<ExposedList<float>>(); private readonly Pool<ExposedList<int>> polygonIndicesPool = new Pool<ExposedList<int>>(); public ExposedList<int> Triangulate (ExposedList<float> verticesArray) { var vertices = verticesArray.Items; int vertexCount = verticesArray.Count >> 1; var indicesArray = this.indicesArray; indicesArray.Clear(); int[] indices = indicesArray.Resize(vertexCount).Items; for (int i = 0; i < vertexCount; i++) indices[i] = i; var isConcaveArray = this.isConcaveArray; bool[] isConcave = isConcaveArray.Resize(vertexCount).Items; for (int i = 0, n = vertexCount; i < n; ++i) isConcave[i] = IsConcave(i, vertexCount, vertices, indices); var triangles = this.triangles; triangles.Clear(); triangles.EnsureCapacity(Math.Max(0, vertexCount - 2) << 2); while (vertexCount > 3) { // Find ear tip. int previous = vertexCount - 1, i = 0, next = 1; // outer: while (true) { if (!isConcave[i]) { int p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1; float p1x = vertices[p1], p1y = vertices[p1 + 1]; float p2x = vertices[p2], p2y = vertices[p2 + 1]; float p3x = vertices[p3], p3y = vertices[p3 + 1]; for (int ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) { if (!isConcave[ii]) continue; int v = indices[ii] << 1; float vx = vertices[v], vy = vertices[v + 1]; if (PositiveArea(p3x, p3y, p1x, p1y, vx, vy)) { if (PositiveArea(p1x, p1y, p2x, p2y, vx, vy)) { if (PositiveArea(p2x, p2y, p3x, p3y, vx, vy)) goto outer; // break outer; } } } break; } outer: if (next == 0) { do { if (!isConcave[i]) break; i--; } while (i > 0); break; } previous = i; i = next; next = (next + 1) % vertexCount; } // Cut ear tip. triangles.Add(indices[(vertexCount + i - 1) % vertexCount]); triangles.Add(indices[i]); triangles.Add(indices[(i + 1) % vertexCount]); indicesArray.RemoveAt(i); isConcaveArray.RemoveAt(i); vertexCount--; int previousIndex = (vertexCount + i - 1) % vertexCount; int nextIndex = i == vertexCount ? 0 : i; isConcave[previousIndex] = IsConcave(previousIndex, vertexCount, vertices, indices); isConcave[nextIndex] = IsConcave(nextIndex, vertexCount, vertices, indices); } if (vertexCount == 3) { triangles.Add(indices[2]); triangles.Add(indices[0]); triangles.Add(indices[1]); } return triangles; } public ExposedList<ExposedList<float>> Decompose (ExposedList<float> verticesArray, ExposedList<int> triangles) { var vertices = verticesArray.Items; var convexPolygons = this.convexPolygons; for (int i = 0, n = convexPolygons.Count; i < n; i++) { polygonPool.Free(convexPolygons.Items[i]); } convexPolygons.Clear(); var convexPolygonsIndices = this.convexPolygonsIndices; for (int i = 0, n = convexPolygonsIndices.Count; i < n; i++) { polygonIndicesPool.Free(convexPolygonsIndices.Items[i]); } convexPolygonsIndices.Clear(); var polygonIndices = polygonIndicesPool.Obtain(); polygonIndices.Clear(); var polygon = polygonPool.Obtain(); polygon.Clear(); // Merge subsequent triangles if they form a triangle fan. int fanBaseIndex = -1, lastWinding = 0; int[] trianglesItems = triangles.Items; for (int i = 0, n = triangles.Count; i < n; i += 3) { int t1 = trianglesItems[i] << 1, t2 = trianglesItems[i + 1] << 1, t3 = trianglesItems[i + 2] << 1; float x1 = vertices[t1], y1 = vertices[t1 + 1]; float x2 = vertices[t2], y2 = vertices[t2 + 1]; float x3 = vertices[t3], y3 = vertices[t3 + 1]; // If the base of the last triangle is the same as this triangle, check if they form a convex polygon (triangle fan). var merged = false; if (fanBaseIndex == t1) { int o = polygon.Count - 4; float[] p = polygon.Items; int winding1 = Winding(p[o], p[o + 1], p[o + 2], p[o + 3], x3, y3); int winding2 = Winding(x3, y3, p[0], p[1], p[2], p[3]); if (winding1 == lastWinding && winding2 == lastWinding) { polygon.Add(x3); polygon.Add(y3); polygonIndices.Add(t3); merged = true; } } // Otherwise make this triangle the new base. if (!merged) { if (polygon.Count > 0) { convexPolygons.Add(polygon); convexPolygonsIndices.Add(polygonIndices); } else { polygonPool.Free(polygon); polygonIndicesPool.Free(polygonIndices); } polygon = polygonPool.Obtain(); polygon.Clear(); polygon.Add(x1); polygon.Add(y1); polygon.Add(x2); polygon.Add(y2); polygon.Add(x3); polygon.Add(y3); polygonIndices = polygonIndicesPool.Obtain(); polygonIndices.Clear(); polygonIndices.Add(t1); polygonIndices.Add(t2); polygonIndices.Add(t3); lastWinding = Winding(x1, y1, x2, y2, x3, y3); fanBaseIndex = t1; } } if (polygon.Count > 0) { convexPolygons.Add(polygon); convexPolygonsIndices.Add(polygonIndices); } // Go through the list of polygons and try to merge the remaining triangles with the found triangle fans. for (int i = 0, n = convexPolygons.Count; i < n; i++) { polygonIndices = convexPolygonsIndices.Items[i]; if (polygonIndices.Count == 0) continue; int firstIndex = polygonIndices.Items[0]; int lastIndex = polygonIndices.Items[polygonIndices.Count - 1]; polygon = convexPolygons.Items[i]; int o = polygon.Count - 4; float[] p = polygon.Items; float prevPrevX = p[o], prevPrevY = p[o + 1]; float prevX = p[o + 2], prevY = p[o + 3]; float firstX = p[0], firstY = p[1]; float secondX = p[2], secondY = p[3]; int winding = Winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY); for (int ii = 0; ii < n; ii++) { if (ii == i) continue; var otherIndices = convexPolygonsIndices.Items[ii]; if (otherIndices.Count != 3) continue; int otherFirstIndex = otherIndices.Items[0]; int otherSecondIndex = otherIndices.Items[1]; int otherLastIndex = otherIndices.Items[2]; var otherPoly = convexPolygons.Items[ii]; float x3 = otherPoly.Items[otherPoly.Count - 2], y3 = otherPoly.Items[otherPoly.Count - 1]; if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex) continue; int winding1 = Winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3); int winding2 = Winding(x3, y3, firstX, firstY, secondX, secondY); if (winding1 == winding && winding2 == winding) { otherPoly.Clear(); otherIndices.Clear(); polygon.Add(x3); polygon.Add(y3); polygonIndices.Add(otherLastIndex); prevPrevX = prevX; prevPrevY = prevY; prevX = x3; prevY = y3; ii = 0; } } } // Remove empty polygons that resulted from the merge step above. for (int i = convexPolygons.Count - 1; i >= 0; i--) { polygon = convexPolygons.Items[i]; if (polygon.Count == 0) { convexPolygons.RemoveAt(i); polygonPool.Free(polygon); polygonIndices = convexPolygonsIndices.Items[i]; convexPolygonsIndices.RemoveAt(i); polygonIndicesPool.Free(polygonIndices); } } return convexPolygons; } static private bool IsConcave (int index, int vertexCount, float[] vertices, int[] indices) { int previous = indices[(vertexCount + index - 1) % vertexCount] << 1; int current = indices[index] << 1; int next = indices[(index + 1) % vertexCount] << 1; return !PositiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]); } static private bool PositiveArea (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0; } static private int Winding (float p1x, float p1y, float p2x, float p2y, float p3x, float p3y) { float px = p2x - p1x, py = p2y - p1y; return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using MyCouch.Net; using MyCouch.Testing.Model; namespace MyCouch.Testing.TestData { public static class ClientTestData { public static class Artists { public const string Artist1Id = "test:1"; public const string Artist2Id = "test:2"; public const string Artist3Id = "test:3"; public const string Artist4Id = "test:4"; public static Artist Artist1 => new Artist { ArtistId = Artist1Id, Name = "Fake artist 1", Albums = new[] { new Album { Name = "Greatest fakes #1" } } }; public static Artist Artist2 => new Artist { ArtistId = Artist2Id, Name = "Fake artist 1", Albums = new[] { new Album { Name = "Greatest fakes #2.1" }, new Album { Name = "Greatest fakes #2.2" } } }; public static Artist Artist3 => new Artist { ArtistId = Artist3Id, Name = "Fake artist 1", Albums = new[] { new Album { Name = "Greatest fakes #3.1" }, new Album { Name = "Greatest fakes #3.2" }, new Album { Name = "Greatest fakes #3.3" } } }; public static Artist Artist4 => new Artist { ArtistId = Artist4Id, Name = "Fake artist 1", Albums = new[] { new Album { Name = "Greatest fakes #4.1" }, new Album { Name = "Greatest fakes #4.2" }, new Album { Name = "Greatest fakes #4.3" }, new Album { Name = "Greatest fakes #4.4" } } }; public const string Artist1Json = "{\"_id\": \"test:1\", \"$doctype\": \"artist\", \"name\": \"Fake artist 1\", \"albums\":[{\"name\": \"Greatest fakes #1\"}]}"; public const string Artist2Json = "{\"_id\": \"test:2\", \"$doctype\": \"artist\", \"name\": \"Fake artist 2\", \"albums\":[{\"name\": \"Greatest fakes #2.1\"},{\"name\": \"Greatest fakes #2.2\"}]}"; public const string Artist3Json = "{\"_id\": \"test:3\", \"$doctype\": \"artist\", \"name\": \"Fake artist 3\", \"albums\":[{\"name\": \"Greatest fakes #3.1\"},{\"name\": \"Greatest fakes #3.2\"},{\"name\": \"Greatest fakes #3.3\"}]}"; public const string Artist4Json = "{\"_id\": \"test:4\", \"$doctype\": \"artist\", \"name\": \"Fake artist 4\", \"albums\":[{\"name\": \"Greatest fakes #4.1\"},{\"name\": \"Greatest fakes #4.2\"},{\"name\": \"Greatest fakes #4.3\"},{\"name\": \"Greatest fakes #4.4\"}]}"; public static Artist CreateArtist() { return CreateArtists(1).Single(); } public static Artist[] CreateArtists(int numOf) { var artists = new List<Artist>(); var numOfAlbums = new[] { 1, 2, 3 }; for (var c = 0; c < numOf; c++) { var artist = new Artist { ArtistId = string.Format("test:{0}", (c + 1)), Name = "Fake artist " + (c + 1) }; artist.Albums = CreateAlbums(numOfAlbums[c % numOfAlbums.Length], c); artists.Add(artist); } return artists.OrderBy(a => a.ArtistId).ToArray(); } private static Album[] CreateAlbums(int numOf, int artistIndex) { var artistNum = artistIndex + 1; var albums = new List<Album>(); for (var c = 0; c < numOf; c++) { albums.Add(new Album { Name = string.Format("Greatest fakes #{0}.{1}", artistNum + 1, c + 1) }); } return albums.OrderBy(a => a.Name).ToArray(); } } public static class Shows { public const string ArtistsShows = "{" + "\"_id\": \"_design/artistshows\"," + "\"shows\": {" + "\"hello\": \"function(doc, req){" + "return '<h1>hello</h1>';" + "}\"," + "\"jsonShow\": \"function(doc, req){" + "provides('json',function(){" + "send(JSON.stringify({ name: doc.name}));" + "});" + "}\"," + "\"xmlShow\": \"function(doc, req){" + "provides('xml',function(){" + "html = '<foo>' + doc.name + '</foo>';" + "return html;" + "});" + "}\"," + "\"jsonCustomQueryParamShow\": \"function(doc, req){" + "provides('json',function(){" + "send(JSON.stringify({ name: doc.name, foo: req.query.foo}));" + "});" + "}\"" + "}" + "}"; public static readonly ShowIdentity ArtistsHelloShowId = new ShowIdentity("artistshows", "hello"); public static readonly ShowIdentity ArtistsJsonShowId = new ShowIdentity("artistshows", "jsonShow"); public static readonly ShowIdentity ArtistsXmlShowId = new ShowIdentity("artistshows", "xmlShow"); public static readonly ShowIdentity ArtistsJsonShowWithCustomQueryParamId = new ShowIdentity("artistshows", "jsonCustomQueryParamShow"); } public static class Views { public static readonly ViewIdentity[] AllViewIds; static Views() { AllViewIds = new[] { ArtistsAlbumsViewId, ArtistsNameNoValueViewId, ArtistsTotalNumOfAlbumsViewId, ArtistsNameAsKeyAndDocAsValueId }; } public const string ArtistsViews = "{" + "\"_id\": \"_design/artists\"," + "\"language\": \"javascript\"," + "\"lists\": {" + "\"transformToHtml\": \"function(head, req){" + "provides('html',function(){" + "html = '<html><body><ol>';" + "while (row = getRow()) {" + "html += '<li>' + row.value.name + '</li>';" + "}" + "html += '</ol></body></html>';" + "return html;" + "});" + "}\"," + "\"transformToDoc\": \"function(head, req){" + "provides('json',function(){" + "docs = [];" + "while (row = getRow()) {" + "docs.push(row.value);" + "}" + "send(JSON.stringify(docs));" + "});" + "}\"" + "}," + "\"views\": {" + "\"albums\": {" + "\"map\": \"function(doc) { if(doc.$doctype !== 'artist') return; emit(doc.name, doc.albums);}\"" + "}," + "\"name_no_value\": {" + "\"map\": \"function(doc) { if(doc.$doctype !== 'artist') return; emit(doc.name, null);}\"" + "}," + "\"total_num_of_albums\": {" + "\"map\": \"function(doc) { if(doc.$doctype !== 'artist') return; emit(null, doc.albums.length);}\"," + "\"reduce\":\"_sum\"" + "}," + "\"name_as_key_and_doc_as_value\": {" + "\"map\": \"function(doc) { if(doc.$doctype !== 'artist') return; emit(doc.name, doc);}\"" + "}" + "}" + "}"; public static readonly ViewIdentity ArtistsAlbumsViewId = new ViewIdentity("artists", "albums"); public static readonly ViewIdentity ArtistsNameNoValueViewId = new ViewIdentity("artists", "name_no_value"); public static readonly ViewIdentity ArtistsTotalNumOfAlbumsViewId = new ViewIdentity("artists", "total_num_of_albums"); public static readonly ViewIdentity ArtistsNameAsKeyAndDocAsValueId = new ViewIdentity("artists", "name_as_key_and_doc_as_value"); public static class ListNames { public static readonly string TransformToHtmlListId = "transformToHtml"; public static readonly string TransformToDocListId = "transformToDoc"; } } public static class Attachments { public static class One { public const string Name = "att:1"; public const string Content = "MyCouch, the simple asynchronous client for .Net"; public static readonly string ContentType = HttpContentTypes.Text; public static readonly byte[] Bytes = MyCouchRuntime.DefaultEncoding.GetBytes(Content); } } public static string AsBase64EncodedString(this byte[] bytes) { return Convert.ToBase64String(bytes); } public static byte[] AsBytes(this string content) { return MyCouchRuntime.DefaultEncoding.GetBytes(content); } public static Stream AsStream(this string content) { return new MemoryStream(MyCouchRuntime.DefaultEncoding.GetBytes(content)); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace XenAPI { /// <summary> /// individual machine serving provisioning (block) data /// First published in XenServer 7.1. /// </summary> public partial class PVS_server : XenObject<PVS_server> { public PVS_server() { } public PVS_server(string uuid, string[] addresses, long first_port, long last_port, XenRef<PVS_site> site) { this.uuid = uuid; this.addresses = addresses; this.first_port = first_port; this.last_port = last_port; this.site = site; } /// <summary> /// Creates a new PVS_server from a Proxy_PVS_server. /// </summary> /// <param name="proxy"></param> public PVS_server(Proxy_PVS_server proxy) { this.UpdateFromProxy(proxy); } /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PVS_server. /// </summary> public override void UpdateFrom(PVS_server update) { uuid = update.uuid; addresses = update.addresses; first_port = update.first_port; last_port = update.last_port; site = update.site; } internal void UpdateFromProxy(Proxy_PVS_server proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; addresses = proxy.addresses == null ? new string[] {} : (string [])proxy.addresses; first_port = proxy.first_port == null ? 0 : long.Parse((string)proxy.first_port); last_port = proxy.last_port == null ? 0 : long.Parse((string)proxy.last_port); site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site); } public Proxy_PVS_server ToProxy() { Proxy_PVS_server result_ = new Proxy_PVS_server(); result_.uuid = uuid ?? ""; result_.addresses = addresses; result_.first_port = first_port.ToString(); result_.last_port = last_port.ToString(); result_.site = site ?? ""; return result_; } /// <summary> /// Creates a new PVS_server from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public PVS_server(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PVS_server /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("addresses")) addresses = Marshalling.ParseStringArray(table, "addresses"); if (table.ContainsKey("first_port")) first_port = Marshalling.ParseLong(table, "first_port"); if (table.ContainsKey("last_port")) last_port = Marshalling.ParseLong(table, "last_port"); if (table.ContainsKey("site")) site = Marshalling.ParseRef<PVS_site>(table, "site"); } public bool DeepEquals(PVS_server other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._addresses, other._addresses) && Helper.AreEqual2(this._first_port, other._first_port) && Helper.AreEqual2(this._last_port, other._last_port) && Helper.AreEqual2(this._site, other._site); } internal static List<PVS_server> ProxyArrayToObjectList(Proxy_PVS_server[] input) { var result = new List<PVS_server>(); foreach (var item in input) result.Add(new PVS_server(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, PVS_server server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static PVS_server get_record(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_record(session.opaque_ref, _pvs_server); else return new PVS_server((Proxy_PVS_server)session.proxy.pvs_server_get_record(session.opaque_ref, _pvs_server ?? "").parse()); } /// <summary> /// Get a reference to the PVS_server instance with the specified UUID. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PVS_server> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PVS_server>.Create(session.proxy.pvs_server_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static string get_uuid(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_uuid(session.opaque_ref, _pvs_server); else return (string)session.proxy.pvs_server_get_uuid(session.opaque_ref, _pvs_server ?? "").parse(); } /// <summary> /// Get the addresses field of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static string[] get_addresses(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_addresses(session.opaque_ref, _pvs_server); else return (string [])session.proxy.pvs_server_get_addresses(session.opaque_ref, _pvs_server ?? "").parse(); } /// <summary> /// Get the first_port field of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static long get_first_port(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_first_port(session.opaque_ref, _pvs_server); else return long.Parse((string)session.proxy.pvs_server_get_first_port(session.opaque_ref, _pvs_server ?? "").parse()); } /// <summary> /// Get the last_port field of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static long get_last_port(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_last_port(session.opaque_ref, _pvs_server); else return long.Parse((string)session.proxy.pvs_server_get_last_port(session.opaque_ref, _pvs_server ?? "").parse()); } /// <summary> /// Get the site field of the given PVS_server. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static XenRef<PVS_site> get_site(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_site(session.opaque_ref, _pvs_server); else return XenRef<PVS_site>.Create(session.proxy.pvs_server_get_site(session.opaque_ref, _pvs_server ?? "").parse()); } /// <summary> /// introduce new PVS server /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_addresses">IPv4 addresses of the server</param> /// <param name="_first_port">first UDP port accepted by this server</param> /// <param name="_last_port">last UDP port accepted by this server</param> /// <param name="_site">PVS site this server is a part of</param> public static XenRef<PVS_server> introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_introduce(session.opaque_ref, _addresses, _first_port, _last_port, _site); else return XenRef<PVS_server>.Create(session.proxy.pvs_server_introduce(session.opaque_ref, _addresses, _first_port.ToString(), _last_port.ToString(), _site ?? "").parse()); } /// <summary> /// introduce new PVS server /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_addresses">IPv4 addresses of the server</param> /// <param name="_first_port">first UDP port accepted by this server</param> /// <param name="_last_port">last UDP port accepted by this server</param> /// <param name="_site">PVS site this server is a part of</param> public static XenRef<Task> async_introduce(Session session, string[] _addresses, long _first_port, long _last_port, string _site) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pvs_server_introduce(session.opaque_ref, _addresses, _first_port, _last_port, _site); else return XenRef<Task>.Create(session.proxy.async_pvs_server_introduce(session.opaque_ref, _addresses, _first_port.ToString(), _last_port.ToString(), _site ?? "").parse()); } /// <summary> /// forget a PVS server /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static void forget(Session session, string _pvs_server) { if (session.JsonRpcClient != null) session.JsonRpcClient.pvs_server_forget(session.opaque_ref, _pvs_server); else session.proxy.pvs_server_forget(session.opaque_ref, _pvs_server ?? "").parse(); } /// <summary> /// forget a PVS server /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_server">The opaque_ref of the given pvs_server</param> public static XenRef<Task> async_forget(Session session, string _pvs_server) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pvs_server_forget(session.opaque_ref, _pvs_server); else return XenRef<Task>.Create(session.proxy.async_pvs_server_forget(session.opaque_ref, _pvs_server ?? "").parse()); } /// <summary> /// Return a list of all the PVS_servers known to the system. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PVS_server>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_all(session.opaque_ref); else return XenRef<PVS_server>.Create(session.proxy.pvs_server_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PVS_server Records at once, in a single XML RPC call /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PVS_server>, PVS_server> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_server_get_all_records(session.opaque_ref); else return XenRef<PVS_server>.Create<Proxy_PVS_server>(session.proxy.pvs_server_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// IPv4 addresses of this server /// </summary> public virtual string[] addresses { get { return _addresses; } set { if (!Helper.AreEqual(value, _addresses)) { _addresses = value; Changed = true; NotifyPropertyChanged("addresses"); } } } private string[] _addresses = {}; /// <summary> /// First UDP port accepted by this server /// </summary> public virtual long first_port { get { return _first_port; } set { if (!Helper.AreEqual(value, _first_port)) { _first_port = value; Changed = true; NotifyPropertyChanged("first_port"); } } } private long _first_port = 0; /// <summary> /// Last UDP port accepted by this server /// </summary> public virtual long last_port { get { return _last_port; } set { if (!Helper.AreEqual(value, _last_port)) { _last_port = value; Changed = true; NotifyPropertyChanged("last_port"); } } } private long _last_port = 0; /// <summary> /// PVS site this server is part of /// </summary> [JsonConverter(typeof(XenRefConverter<PVS_site>))] public virtual XenRef<PVS_site> site { get { return _site; } set { if (!Helper.AreEqual(value, _site)) { _site = value; Changed = true; NotifyPropertyChanged("site"); } } } private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL"); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/datastore/v1/datastore.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace Google.Cloud.Datastore.V1 { /// <summary> /// Each RPC normalizes the partition IDs of the keys in its input entities, /// and always returns entities with keys with normalized partition IDs. /// This applies to all keys and entities, including those in values, except keys /// with both an empty path and an empty or unset partition ID. Normalization of /// input keys sets the project ID (if not already set) to the project ID from /// the request. /// </summary> public static partial class Datastore { static readonly string __ServiceName = "google.datastore.v1.Datastore"; static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.LookupRequest> __Marshaller_LookupRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.LookupRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.LookupResponse> __Marshaller_LookupResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.LookupResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RunQueryRequest> __Marshaller_RunQueryRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RunQueryRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RunQueryResponse> __Marshaller_RunQueryResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RunQueryResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.BeginTransactionRequest> __Marshaller_BeginTransactionRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.BeginTransactionRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> __Marshaller_BeginTransactionResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.BeginTransactionResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.CommitRequest> __Marshaller_CommitRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.CommitRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.CommitResponse> __Marshaller_CommitResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.CommitResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RollbackRequest> __Marshaller_RollbackRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RollbackRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.RollbackResponse> __Marshaller_RollbackResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.RollbackResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.AllocateIdsRequest> __Marshaller_AllocateIdsRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.AllocateIdsRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> __Marshaller_AllocateIdsResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Datastore.V1.AllocateIdsResponse.Parser.ParseFrom); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.LookupRequest, global::Google.Cloud.Datastore.V1.LookupResponse> __Method_Lookup = new grpc::Method<global::Google.Cloud.Datastore.V1.LookupRequest, global::Google.Cloud.Datastore.V1.LookupResponse>( grpc::MethodType.Unary, __ServiceName, "Lookup", __Marshaller_LookupRequest, __Marshaller_LookupResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.RunQueryRequest, global::Google.Cloud.Datastore.V1.RunQueryResponse> __Method_RunQuery = new grpc::Method<global::Google.Cloud.Datastore.V1.RunQueryRequest, global::Google.Cloud.Datastore.V1.RunQueryResponse>( grpc::MethodType.Unary, __ServiceName, "RunQuery", __Marshaller_RunQueryRequest, __Marshaller_RunQueryResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.BeginTransactionRequest, global::Google.Cloud.Datastore.V1.BeginTransactionResponse> __Method_BeginTransaction = new grpc::Method<global::Google.Cloud.Datastore.V1.BeginTransactionRequest, global::Google.Cloud.Datastore.V1.BeginTransactionResponse>( grpc::MethodType.Unary, __ServiceName, "BeginTransaction", __Marshaller_BeginTransactionRequest, __Marshaller_BeginTransactionResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.CommitRequest, global::Google.Cloud.Datastore.V1.CommitResponse> __Method_Commit = new grpc::Method<global::Google.Cloud.Datastore.V1.CommitRequest, global::Google.Cloud.Datastore.V1.CommitResponse>( grpc::MethodType.Unary, __ServiceName, "Commit", __Marshaller_CommitRequest, __Marshaller_CommitResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.RollbackRequest, global::Google.Cloud.Datastore.V1.RollbackResponse> __Method_Rollback = new grpc::Method<global::Google.Cloud.Datastore.V1.RollbackRequest, global::Google.Cloud.Datastore.V1.RollbackResponse>( grpc::MethodType.Unary, __ServiceName, "Rollback", __Marshaller_RollbackRequest, __Marshaller_RollbackResponse); static readonly grpc::Method<global::Google.Cloud.Datastore.V1.AllocateIdsRequest, global::Google.Cloud.Datastore.V1.AllocateIdsResponse> __Method_AllocateIds = new grpc::Method<global::Google.Cloud.Datastore.V1.AllocateIdsRequest, global::Google.Cloud.Datastore.V1.AllocateIdsResponse>( grpc::MethodType.Unary, __ServiceName, "AllocateIds", __Marshaller_AllocateIdsRequest, __Marshaller_AllocateIdsResponse); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Datastore.V1.DatastoreReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of Datastore</summary> public abstract partial class DatastoreBase { /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.LookupResponse> Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.CommitResponse> Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.RollbackResponse> Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request received from the client.</param> /// <param name="context">The context of the server-side call handler being invoked.</param> /// <returns>The response to send back to the client (wrapped by a task).</returns> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for Datastore</summary> public partial class DatastoreClient : grpc::ClientBase<DatastoreClient> { /// <summary>Creates a new client for Datastore</summary> /// <param name="channel">The channel to use to make remote calls.</param> public DatastoreClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for Datastore that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public DatastoreClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected DatastoreClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected DatastoreClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.LookupResponse Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Lookup(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.LookupResponse Lookup(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Lookup, null, options, request); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.LookupResponse> LookupAsync(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return LookupAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Looks up entities by key. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.LookupResponse> LookupAsync(global::Google.Cloud.Datastore.V1.LookupRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Lookup, null, options, request); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RunQueryResponse RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunQuery(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RunQueryResponse RunQuery(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_RunQuery, null, options, request); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQueryAsync(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RunQueryAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Queries for entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RunQueryResponse> RunQueryAsync(global::Google.Cloud.Datastore.V1.RunQueryRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_RunQuery, null, options, request); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.BeginTransactionResponse BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return BeginTransaction(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.BeginTransactionResponse BeginTransaction(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_BeginTransaction, null, options, request); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransactionAsync(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return BeginTransactionAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Begins a new transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.BeginTransactionResponse> BeginTransactionAsync(global::Google.Cloud.Datastore.V1.BeginTransactionRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_BeginTransaction, null, options, request); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.CommitResponse Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Commit(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.CommitResponse Commit(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Commit, null, options, request); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.CommitResponse> CommitAsync(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CommitAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Commits a transaction, optionally creating, deleting or modifying some /// entities. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.CommitResponse> CommitAsync(global::Google.Cloud.Datastore.V1.CommitRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Commit, null, options, request); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RollbackResponse Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Rollback(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.RollbackResponse Rollback(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Rollback, null, options, request); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RollbackResponse> RollbackAsync(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return RollbackAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Rolls back a transaction. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.RollbackResponse> RollbackAsync(global::Google.Cloud.Datastore.V1.RollbackRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Rollback, null, options, request); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.AllocateIdsResponse AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllocateIds(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The response received from the server.</returns> public virtual global::Google.Cloud.Datastore.V1.AllocateIdsResponse AllocateIds(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_AllocateIds, null, options, request); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param> /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param> /// <param name="cancellationToken">An optional token for canceling the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIdsAsync(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllocateIdsAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Allocates IDs for the given keys, which is useful for referencing an entity /// before it is inserted. /// </summary> /// <param name="request">The request to send to the server.</param> /// <param name="options">The options for the call.</param> /// <returns>The call object.</returns> public virtual grpc::AsyncUnaryCall<global::Google.Cloud.Datastore.V1.AllocateIdsResponse> AllocateIdsAsync(global::Google.Cloud.Datastore.V1.AllocateIdsRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_AllocateIds, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override DatastoreClient NewInstance(ClientBaseConfiguration configuration) { return new DatastoreClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(DatastoreBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_Lookup, serviceImpl.Lookup) .AddMethod(__Method_RunQuery, serviceImpl.RunQuery) .AddMethod(__Method_BeginTransaction, serviceImpl.BeginTransaction) .AddMethod(__Method_Commit, serviceImpl.Commit) .AddMethod(__Method_Rollback, serviceImpl.Rollback) .AddMethod(__Method_AllocateIds, serviceImpl.AllocateIds).Build(); } } } #endregion
using System; using System.Collections; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; namespace Org.BouncyCastle.Asn1 { abstract public class Asn1Set : Asn1Object, IEnumerable { private readonly IList _set; /** * return an ASN1Set from the given object. * * @param obj the object we want converted. * @exception ArgumentException if the object cannot be converted. */ public static Asn1Set GetInstance( object obj) { if (obj == null || obj is Asn1Set) { return (Asn1Set)obj; } throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); } /** * Return an ASN1 set from a tagged object. There is a special * case here, if an object appears to have been explicitly tagged on * reading but we were expecting it to be implicitly tagged in the * normal course of events it indicates that we lost the surrounding * set - so we need to add it back (this will happen if the tagged * object is a sequence that contains other sequences). If you are * dealing with implicitly tagged sets you really <b>should</b> * be using this method. * * @param obj the tagged object. * @param explicitly true if the object is meant to be explicitly tagged * false otherwise. * @exception ArgumentException if the tagged object cannot * be converted. */ public static Asn1Set GetInstance( Asn1TaggedObject obj, bool explicitly) { Asn1Object inner = obj.GetObject(); if (explicitly) { if (!obj.IsExplicit()) throw new ArgumentException("object implicit - explicit expected."); return (Asn1Set) inner; } // // constructed object which appears to be explicitly tagged // and it's really implicit means we have to add the // surrounding sequence. // if (obj.IsExplicit()) { return new DerSet(inner); } if (inner is Asn1Set) { return (Asn1Set) inner; } // // in this case the parser returns a sequence, convert it // into a set. // if (inner is Asn1Sequence) { Asn1EncodableVector v = new Asn1EncodableVector(); Asn1Sequence s = (Asn1Sequence) inner; foreach (Asn1Encodable ae in s) { v.Add(ae); } // TODO Should be able to construct set directly from sequence? return new DerSet(v, false); } throw new ArgumentException("Unknown object in GetInstance: " + obj.GetType().FullName, "obj"); } protected internal Asn1Set( int capacity) { _set = Platform.CreateArrayList(capacity); } public virtual IEnumerator GetEnumerator() { return _set.GetEnumerator(); } [Obsolete("Use GetEnumerator() instead")] public IEnumerator GetObjects() { return GetEnumerator(); } /** * return the object at the set position indicated by index. * * @param index the set number (starting at zero) of the object * @return the object at the set position indicated by index. */ public virtual Asn1Encodable this[int index] { get { return (Asn1Encodable) _set[index]; } } [Obsolete("Use 'object[index]' syntax instead")] public Asn1Encodable GetObjectAt( int index) { return this[index]; } [Obsolete("Use 'Count' property instead")] public int Size { get { return Count; } } public virtual int Count { get { return _set.Count; } } public virtual Asn1Encodable[] ToArray() { Asn1Encodable[] values = new Asn1Encodable[this.Count]; for (int i = 0; i < this.Count; ++i) { values[i] = this[i]; } return values; } private class Asn1SetParserImpl : Asn1SetParser { private readonly Asn1Set outer; private readonly int max; private int index; public Asn1SetParserImpl( Asn1Set outer) { this.outer = outer; this.max = outer.Count; } public IAsn1Convertible ReadObject() { if (index == max) return null; Asn1Encodable obj = outer[index++]; if (obj is Asn1Sequence) return ((Asn1Sequence)obj).Parser; if (obj is Asn1Set) return ((Asn1Set)obj).Parser; // NB: Asn1OctetString implements Asn1OctetStringParser directly // if (obj is Asn1OctetString) // return ((Asn1OctetString)obj).Parser; return obj; } public virtual Asn1Object ToAsn1Object() { return outer; } } public Asn1SetParser Parser { get { return new Asn1SetParserImpl(this); } } protected override int Asn1GetHashCode() { int hc = Count; foreach (object o in this) { hc *= 17; if (o == null) { hc ^= DerNull.Instance.GetHashCode(); } else { hc ^= o.GetHashCode(); } } return hc; } protected override bool Asn1Equals( Asn1Object asn1Object) { Asn1Set other = asn1Object as Asn1Set; if (other == null) return false; if (Count != other.Count) { return false; } IEnumerator s1 = GetEnumerator(); IEnumerator s2 = other.GetEnumerator(); while (s1.MoveNext() && s2.MoveNext()) { Asn1Object o1 = GetCurrent(s1).ToAsn1Object(); Asn1Object o2 = GetCurrent(s2).ToAsn1Object(); if (!o1.Equals(o2)) return false; } return true; } private Asn1Encodable GetCurrent(IEnumerator e) { Asn1Encodable encObj = (Asn1Encodable)e.Current; // unfortunately null was allowed as a substitute for DER null if (encObj == null) return DerNull.Instance; return encObj; } /** * return true if a &lt;= b (arrays are assumed padded with zeros). */ private bool LessThanOrEqual( byte[] a, byte[] b) { int len = System.Math.Min(a.Length, b.Length); for (int i = 0; i != len; ++i) { if (a[i] != b[i]) { return a[i] < b[i]; } } return len == a.Length; } protected internal void Sort() { if (_set.Count > 1) { bool swapped = true; int lastSwap = _set.Count - 1; while (swapped) { int index = 0; int swapIndex = 0; byte[] a = ((Asn1Encodable) _set[0]).GetEncoded(); swapped = false; while (index != lastSwap) { byte[] b = ((Asn1Encodable) _set[index + 1]).GetEncoded(); if (LessThanOrEqual(a, b)) { a = b; } else { object o = _set[index]; _set[index] = _set[index + 1]; _set[index + 1] = o; swapped = true; swapIndex = index; } index++; } lastSwap = swapIndex; } } } protected internal void AddObject( Asn1Encodable obj) { _set.Add(obj); } public override string ToString() { return CollectionUtilities.ToString(_set); } } }
// // SqlitePclRawStorageEngine.cs // // Author: // Zachary Gramana <zack@couchbase.com> // // Copyright (c) 2014 Couchbase Inc. // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, 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.Threading.Tasks; using Couchbase.Lite.Storage; using System.Threading; using SQLitePCL; using Couchbase.Lite.Util; using System.Diagnostics; using System.Text; using System.Collections.Generic; using System.Linq; using SQLitePCL.Ugly; using Couchbase.Lite.Store; #if !NET_3_5 using StringEx = System.String; #endif namespace Couchbase.Lite { internal sealed class SqlitePCLRawStorageEngine : ISQLiteStorageEngine, IDisposable { // NOTE: SqlitePCL.raw only defines a subset of the ones we want, // so we just redefine them here instead. private const int SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN = 0x00200000; private const int SQLITE_OPEN_READONLY = 0x00000001; private const int SQLITE_OPEN_READWRITE = 0x00000002; private const int SQLITE_OPEN_CREATE = 0x00000004; private const int SQLITE_OPEN_FULLMUTEX = 0x00010000; private const int SQLITE_OPEN_NOMUTEX = 0x00008000; private const int SQLITE_OPEN_PRIVATECACHE = 0x00040000; private const int SQLITE_OPEN_SHAREDCACHE = 0x00020000; private const String Tag = "SqlitePCLRawStorageEngine"; private sqlite3 _writeConnection; private sqlite3 _readConnection; private Boolean shouldCommit; private string Path { get; set; } private TaskFactory Factory { get; set; } private CancellationTokenSource _cts = new CancellationTokenSource(); #region implemented abstract members of SQLiteStorageEngine public int LastErrorCode { get; private set; } public bool Open(String path) { if (IsOpen) return true; Path = path; Factory = new TaskFactory(new SingleThreadScheduler()); var result = true; try { Log.I(Tag, "Sqlite Version: {0}".Fmt(raw.sqlite3_libversion())); shouldCommit = false; const int writer_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; OpenSqliteConnection(writer_flags, out _writeConnection); const int reader_flags = SQLITE_OPEN_FILEPROTECTION_COMPLETEUNLESSOPEN | SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX; OpenSqliteConnection(reader_flags, out _readConnection); } catch (Exception ex) { Log.E(Tag, "Error opening the Sqlite connection using connection String: {0}".Fmt(path), ex); result = false; } return result; } void OpenSqliteConnection(int flags, out sqlite3 db) { LastErrorCode = raw.sqlite3_open_v2(Path, out db, flags, null); if (LastErrorCode != raw.SQLITE_OK) { Path = null; var errMessage = "Cannot open Sqlite Database at pth {0}".Fmt(Path); throw new CouchbaseLiteException(errMessage, StatusCode.DbError); } #if !__ANDROID__ && !NET_3_5 && VERBOSE var i = 0; var val = raw.sqlite3_compileoption_get(i); while (val != null) { Log.V(Tag, "Sqlite Config: {0}".Fmt(val)); val = raw.sqlite3_compileoption_get(++i); } #endif raw.sqlite3_create_collation(db, "JSON", null, CouchbaseSqliteJsonUnicodeCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_ASCII", null, CouchbaseSqliteJsonAsciiCollationFunction.Compare); raw.sqlite3_create_collation(db, "JSON_RAW", null, CouchbaseSqliteJsonRawCollationFunction.Compare); raw.sqlite3_create_collation(db, "REVID", null, CouchbaseSqliteRevIdCollationFunction.Compare); } public Int32 GetVersion() { const string commandText = "PRAGMA user_version;"; sqlite3_stmt statement; //NOTE.JHB Even though this is a read, iOS doesn't return the correct value on the read connection //but someone should try again when the version goes beyond 3.7.13 statement = BuildCommand (_writeConnection, commandText, null); var result = -1; try { LastErrorCode = raw.sqlite3_step(statement); if (LastErrorCode != raw.SQLITE_ERROR) { Debug.Assert(LastErrorCode == raw.SQLITE_ROW); result = raw.sqlite3_column_int(statement, 0); } } catch (Exception e) { Log.E(Tag, "Error getting user version", e); } finally { statement.Dispose(); } return result; } public void SetVersion(Int32 version) { var errMessage = "Unable to set version to {0}".Fmt(version); var commandText = "PRAGMA user_version = ?"; Factory.StartNew(() => { sqlite3_stmt statement = BuildCommand(_writeConnection, commandText, null); if ((LastErrorCode = raw.sqlite3_bind_int(statement, 1, version)) == raw.SQLITE_ERROR) throw new CouchbaseLiteException(errMessage, StatusCode.DbError); try { LastErrorCode = statement.step(); if (LastErrorCode != SQLiteResult.OK) throw new CouchbaseLiteException(errMessage, StatusCode.DbError); } catch (Exception e) { Log.E(Tag, "Error getting user version", e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); } finally { statement.Dispose(); } }); } public bool IsOpen { get { return _writeConnection != null; } } int transactionCount = 0; public int BeginTransaction() { if (!IsOpen) { Open(Path); } // NOTE.ZJG: Seems like we should really be using TO SAVEPOINT // but this is how Android SqliteDatabase does it, // so I'm matching that for now. var value = Interlocked.Increment(ref transactionCount); if (value == 1) { var t = Factory.StartNew(() => { try { using (var statement = BuildCommand(_writeConnection, "BEGIN IMMEDIATE TRANSACTION", null)) { statement.step_done(); } } catch (Exception e) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.E(Tag, "Error BeginTransaction", e); } }); t.Wait(); } return value; } public int EndTransaction() { if (_writeConnection == null) throw new InvalidOperationException("Database is not open."); var count = Interlocked.Decrement(ref transactionCount); if (count > 0) return count; var t = Factory.StartNew(() => { try { if (shouldCommit) { using (var statement = BuildCommand(_writeConnection, "COMMIT", null)) { statement.step_done(); } shouldCommit = false; } else { using (var statement = BuildCommand(_writeConnection, "ROLLBACK", null)) { statement.step_done(); } } } catch (Exception e) { Log.E(Tag, "Error EndTransaction", e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); } }); t.Wait(); return 0; } public void SetTransactionSuccessful() { shouldCommit = true; } /// <summary> /// Execute any SQL that changes the database. /// </summary> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public int ExecSQL(String sql, params Object[] paramArgs) { var t = Factory.StartNew(()=> { sqlite3_stmt command = null; try { command = BuildCommand(_writeConnection, sql, paramArgs); LastErrorCode = command.step(); if (LastErrorCode == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } catch (ugly.sqlite3_exception e) { Log.E(Tag, "Error {0}, {1} executing sql '{2}'".Fmt(e.errcode, _writeConnection.extended_errcode(), sql), e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); throw; } finally { if(command != null) { command.Dispose(); } } }, _cts.Token); try { //FIXME.JHB: This wait should be optional (API change) t.Wait(30000, _cts.Token); } catch (AggregateException ex) { throw ex.InnerException; } catch (OperationCanceledException) { //Closing the storage engine will cause the factory to stop processing, but still //accept new jobs into the scheduler. If execution has gotten here, it means that //ExecSQL was called after Close, and the job will be ignored. Might consider //subclassing the factory to avoid this awkward behavior Log.D(Tag, "StorageEngine closed, canceling operation"); return 0; } if (t.Status != TaskStatus.RanToCompletion) { Log.E(Tag, "ExecSQL timed out waiting for Task #{0}", t.Id); throw new CouchbaseLiteException("ExecSQL timed out", StatusCode.InternalServerError); } return _writeConnection.changes(); } /// <summary> /// Executes only read-only SQL. /// </summary> /// <returns>The query.</returns> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public Cursor IntransactionRawQuery(String sql, params Object[] paramArgs) { if (!IsOpen) { Open(Path); } if (transactionCount == 0) { return RawQuery(sql, paramArgs); } var t = Factory.StartNew(() => { Cursor cursor = null; sqlite3_stmt command = null; try { Log.V(Tag, "RawQuery sql: {0} ({1})", sql, String.Join(", ", paramArgs.ToStringArray())); command = BuildCommand (_writeConnection, sql, paramArgs); cursor = new Cursor(command); } catch (Exception e) { if (command != null) { command.Dispose(); } Log.E(Tag, "Error executing raw query '{0}'".Fmt(sql), e); LastErrorCode = raw.sqlite3_errcode(_writeConnection); throw; } return cursor; }); return t.Result; } /// <summary> /// Executes only read-only SQL. /// </summary> /// <returns>The query.</returns> /// <param name="sql">Sql.</param> /// <param name="paramArgs">Parameter arguments.</param> public Cursor RawQuery(String sql, params Object[] paramArgs) { if (!IsOpen) { Open(Path); } Cursor cursor = null; sqlite3_stmt command = null; var t = Factory.StartNew (() => { try { Log.V (Tag, "RawQuery sql: {0} ({1})", sql, String.Join (", ", paramArgs.ToStringArray ())); command = BuildCommand (_readConnection, sql, paramArgs); cursor = new Cursor (command); } catch (Exception e) { if (command != null) { command.Dispose (); } var args = paramArgs == null ? String.Empty : String.Join (",", paramArgs.ToStringArray ()); Log.E (Tag, "Error executing raw query '{0}' is values '{1}' {2}".Fmt (sql, args, _readConnection.errmsg ()), e); LastErrorCode = raw.sqlite3_errcode(_readConnection); throw; } return cursor; }); return t.Result; } public long Insert(String table, String nullColumnHack, ContentValues values) { return InsertWithOnConflict(table, null, values, ConflictResolutionStrategy.None); } public long InsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, ConflictResolutionStrategy conflictResolutionStrategy) { if (!StringEx.IsNullOrWhiteSpace(nullColumnHack)) { var e = new InvalidOperationException("{0} does not support the 'nullColumnHack'.".Fmt(Tag)); Log.E(Tag, "Unsupported use of nullColumnHack", e); throw e; } var t = Factory.StartNew(() => { var lastInsertedId = -1L; var command = GetInsertCommand(table, initialValues, conflictResolutionStrategy); try { LastErrorCode = command.step(); command.Dispose(); if (LastErrorCode == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); int changes = _writeConnection.changes(); if (changes > 0) { lastInsertedId = _writeConnection.last_insert_rowid(); } if (lastInsertedId == -1L) { if(conflictResolutionStrategy != ConflictResolutionStrategy.Ignore) { Log.E(Tag, "Error inserting " + initialValues + " using " + command); throw new CouchbaseLiteException("Error inserting " + initialValues + " using " + command, StatusCode.DbError); } } else { Log.V(Tag, "Inserting row {0} into {1} with values {2}", lastInsertedId, table, initialValues); } } catch (Exception ex) { Log.E(Tag, "Error inserting into table " + table, ex); LastErrorCode = raw.sqlite3_errcode(_writeConnection); throw; } return lastInsertedId; }); var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) throw t.Exception; return r; } public int Update(String table, ContentValues values, String whereClause, params String[] whereArgs) { Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); Debug.Assert(values != null); var t = Factory.StartNew(() => { var resultCount = 0; var command = GetUpdateCommand(table, values, whereClause, whereArgs); try { LastErrorCode = command.step(); if (LastErrorCode == SQLiteResult.ERROR) throw new CouchbaseLiteException(raw.sqlite3_errmsg(_writeConnection), StatusCode.DbError); } catch (ugly.sqlite3_exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); var msg = raw.sqlite3_extended_errcode(_writeConnection); Log.E(Tag, "Error {0}: \"{1}\" while updating table {2}\r\n{3}", ex.errcode, msg, table, ex); } resultCount = _writeConnection.changes(); if (resultCount < 0) { Log.E(Tag, "Error updating " + values + " using " + command); throw new CouchbaseLiteException("Failed to update any records.", StatusCode.DbError); } command.Dispose(); return resultCount; }, CancellationToken.None); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. //doesn't look good var r = t.ConfigureAwait(false).GetAwaiter().GetResult(); if (t.Exception != null) throw t.Exception; return r; } public int Delete(String table, String whereClause, params String[] whereArgs) { Debug.Assert(!StringEx.IsNullOrWhiteSpace(table)); var t = Factory.StartNew(() => { var resultCount = -1; var command = GetDeleteCommand(table, whereClause, whereArgs); try { var result = command.step(); if (result == SQLiteResult.ERROR) throw new CouchbaseLiteException("Error deleting from table " + table, StatusCode.DbError); resultCount = _writeConnection.changes(); if (resultCount < 0) { throw new CouchbaseLiteException("Failed to delete the records.", StatusCode.DbError); } } catch (Exception ex) { LastErrorCode = raw.sqlite3_errcode(_writeConnection); Log.E(Tag, "Error {0} when deleting from table {1}".Fmt(_writeConnection.extended_errcode(), table), ex); throw; } finally { command.Dispose(); } return resultCount; }); // NOTE.ZJG: Just a sketch here. Needs better error handling, etc. var r = t.GetAwaiter().GetResult(); if (t.Exception != null) { //this is bad: should not arbitrarily crash the app throw t.Exception; } return r; } public void Close() { _cts.Cancel(); ((SingleThreadScheduler)Factory.Scheduler).Dispose(); Close(ref _readConnection); Close(ref _writeConnection); Path = null; } static void Close(ref sqlite3 db) { if (db == null) { return; } var dbCopy = db; db = null; try { // Close any open statements, otherwise the // sqlite connection won't actually close. sqlite3_stmt next = null; while ((next = dbCopy.next_stmt(next))!= null) { next.Dispose(); } dbCopy.close(); Log.I(Tag, "db connection {0} closed", dbCopy); } catch (KeyNotFoundException ex) { // Appears to be a bug in sqlite3.find_stmt. Concurrency issue in static dictionary? // Assuming we're done. Log.W(Tag, "Abandoning database close.", ex); } catch (ugly.sqlite3_exception ex) { Log.E(Tag, "Retrying database close.", ex); // Assuming a basic retry fixes this. Thread.Sleep(5000); dbCopy.close(); } GC.Collect(); GC.WaitForPendingFinalizers(); try { dbCopy.Dispose(); } catch (Exception ex) { Log.E(Tag, "Error while closing database.", ex); } } #endregion #region Non-public Members private sqlite3_stmt BuildCommand(sqlite3 db, string sql, object[] paramArgs) { if (db == null) { throw new ArgumentNullException("db"); } sqlite3_stmt command = null; try { if (!IsOpen) { if(!Open(Path)) { throw new CouchbaseLiteException("Failed to Open " + Path, StatusCode.DbError); } } lock(Cursor.StmtDisposeLock) { LastErrorCode = raw.sqlite3_prepare_v2(db, sql, out command); } if (LastErrorCode != raw.SQLITE_OK || command == null) { Log.E(Tag, "sqlite3_prepare_v2: " + LastErrorCode); } if (paramArgs != null && paramArgs.Length > 0 && command != null && LastErrorCode != raw.SQLITE_ERROR) { command.bind(paramArgs); } } catch (Exception e) { Log.E(Tag, "Error when build a sql " + sql + " with params " + paramArgs, e); throw; } return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The update command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetUpdateCommand(string table, ContentValues values, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("UPDATE "); builder.Append(table); builder.Append(" SET "); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var paramList = new List<object>(); var index = 0; foreach (var column in valueSet) { if (index++ > 0) { builder.Append(","); } builder.AppendFormat("{0} = ?", column.Key); paramList.Add(column.Value); } if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } if (whereArgs != null) { paramList.AddRange(whereArgs); } var sql = builder.ToString(); var command = BuildCommand(_writeConnection, sql, paramList.ToArray<object>()); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The insert command.</returns> /// <param name="table">Table.</param> /// <param name="values">Values.</param> /// <param name="conflictResolutionStrategy">Conflict resolution strategy.</param> sqlite3_stmt GetInsertCommand(String table, ContentValues values, ConflictResolutionStrategy conflictResolutionStrategy) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("INSERT"); if (conflictResolutionStrategy != ConflictResolutionStrategy.None) { builder.Append(" OR "); builder.Append(conflictResolutionStrategy); } builder.Append(" INTO "); builder.Append(table); builder.Append(" ("); // Append our content column names and create our SQL parameters. var valueSet = values.ValueSet(); var valueBuilder = new StringBuilder(); var index = 0; var args = new object[valueSet.Count]; foreach (var column in valueSet) { if (index > 0) { builder.Append(","); valueBuilder.Append(","); } builder.AppendFormat("{0}", column.Key); valueBuilder.Append("?"); args[index] = column.Value; index++; } builder.Append(") VALUES ("); builder.Append(valueBuilder); builder.Append(")"); var sql = builder.ToString(); sqlite3_stmt command = null; if (args != null) { Log.D(Tag, "Preparing statement: '{0}' with values: {1}", sql, String.Join(", ", args.Select(o => o == null ? "null" : o.ToString()).ToArray())); } else { Log.D(Tag, "Preparing statement: '{0}'", sql); } command = BuildCommand(_writeConnection, sql, args); return command; } /// <summary> /// Avoids the additional database trip that using SqliteCommandBuilder requires. /// </summary> /// <returns>The delete command.</returns> /// <param name="table">Table.</param> /// <param name="whereClause">Where clause.</param> /// <param name="whereArgs">Where arguments.</param> sqlite3_stmt GetDeleteCommand(string table, string whereClause, string[] whereArgs) { if (!IsOpen) { Open(Path); } var builder = new StringBuilder("DELETE FROM "); builder.Append(table); if (!StringEx.IsNullOrWhiteSpace(whereClause)) { builder.Append(" WHERE "); builder.Append(whereClause); } sqlite3_stmt command; command = BuildCommand(_writeConnection, builder.ToString(), whereArgs); return command; } #endregion #region IDisposable implementation public void Dispose() { Close(); } #endregion } }
/// <summary> /// This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System; using System.Net; #if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3 using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; #endif #if UNITY_METRO && !UNITY_EDITOR using GA_Compatibility.Collections; #endif public class GA_GenericInfo { #region public values /// <summary> /// The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used. /// </summary> public string UserID { get { if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID) { _userID = GetUserUUID(); } return _userID; } } /// <summary> /// The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session. /// </summary> public string SessionID { get { if (_sessionID == null) { _sessionID = GetSessionUUID(); } return _sessionID; } } /// <summary> /// The current UTC date/time in seconds /// </summary> /*public string TimeStamp { get { return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); } }*/ #endregion #region private values private string _userID = string.Empty; private string _sessionID; private bool _settingUserID; #endregion #region public methods /// <summary> /// Gets generic system information at the beginning of a play session /// </summary> /// <param name="inclSpecs"> /// Determines if all the system specs should be included <see cref="System.Bool"/> /// </param> /// <returns> /// The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/> /// </returns> public List<Hashtable> GetGenericInfo(string message) { List<Hashtable> systemspecs = new List<Hashtable>(); systemspecs.Add(AddSystemSpecs("unity_wrapper", GA_Settings.VERSION, message)); /* * Apple does not allow tracking of device specific data: * "You may not use analytics software in your application to collect and send device data to a third party" * - iOS Developer Program License Agreement: http://www.scribd.com/doc/41213383/iOS-Developer-Program-License-Agreement */ #if !UNITY_IPHONE systemspecs.Add(AddSystemSpecs("os", SystemInfo.operatingSystem, message)); systemspecs.Add(AddSystemSpecs("processor_type", SystemInfo.processorType, message)); systemspecs.Add(AddSystemSpecs("gfx_name", SystemInfo.graphicsDeviceName, message)); systemspecs.Add(AddSystemSpecs("gfx_version", SystemInfo.graphicsDeviceVersion, message)); // Unity provides lots of additional system info which might be worth tracking for some games: //systemspecs.Add(AddSystemSpecs("process_count", SystemInfo.processorCount.ToString(), message)); //systemspecs.Add(AddSystemSpecs("sys_mem_size", SystemInfo.systemMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs("gfx_mem_size", SystemInfo.graphicsMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs("gfx_vendor", SystemInfo.graphicsDeviceVendor, message)); //systemspecs.Add(AddSystemSpecs("gfx_id", SystemInfo.graphicsDeviceID.ToString(), message)); //systemspecs.Add(AddSystemSpecs("gfx_vendor_id", SystemInfo.graphicsDeviceVendorID.ToString(), message)); //systemspecs.Add(AddSystemSpecs("gfx_shader_level", SystemInfo.graphicsShaderLevel.ToString(), message)); //systemspecs.Add(AddSystemSpecs("gfx_pixel_fillrate", SystemInfo.graphicsPixelFillrate.ToString(), message)); //systemspecs.Add(AddSystemSpecs("sup_shadows", SystemInfo.supportsShadows.ToString(), message)); //systemspecs.Add(AddSystemSpecs("sup_render_textures", SystemInfo.supportsRenderTextures.ToString(), message)); //systemspecs.Add(AddSystemSpecs("sup_image_effects", SystemInfo.supportsImageEffects.ToString(), message)); #else systemspecs.Add(AddSystemSpecs("os", "iOS", message)); #endif return systemspecs; } /// <summary> /// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device: /// -- Android uses deviceUniqueIdentifier. /// -- iOS/PC/Mac uses the first MAC addresses available. /// -- Webplayer uses deviceUniqueIdentifier. /// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public string GetUserUUID() { #if UNITY_IPHONE && !UNITY_EDITOR string uid = GA.SettingsGA.GetUniqueIDiOS(); if (uid == null) { return ""; } else if (uid != "OLD") { if (uid.StartsWith("VENDOR-")) return uid.Remove(0, 7); else return uid; } #endif #if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3 return SystemInfo.deviceUniqueIdentifier; #elif !UNITY_FLASH try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); string mac = ""; foreach (NetworkInterface adapter in nics) { PhysicalAddress address = adapter.GetPhysicalAddress(); if (address.ToString() != "" && mac == "") { byte[] bytes = Encoding.UTF8.GetBytes(address.ToString()); SHA1CryptoServiceProvider SHA = new SHA1CryptoServiceProvider(); mac = BitConverter.ToString(SHA.ComputeHash(bytes)).Replace("-", ""); } } return mac; } catch { return SystemInfo.deviceUniqueIdentifier; } #else return GetSessionUUID(); #endif } /// <summary> /// Gets a universally unique ID to represent the session. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public string GetSessionUUID() { #if !UNITY_FLASH return Guid.NewGuid().ToString(); #else string returnValue = ""; for (int i = 0; i < 12; i++) { returnValue += UnityEngine.Random.Range(0, 10).ToString(); } return returnValue; #endif } public void SetSessionUUID() { _sessionID = GetSessionUUID(); } /// <summary> /// Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method. /// </summary> /// <param name="customID"> /// The custom user ID - this should be unique for each user /// </param> public void SetCustomUserID(string customID) { _userID = customID; } #endregion #region private methods /// <summary> /// Adds detailed system specifications regarding the users/players device to the parameters. /// </summary> /// <param name="parameters"> /// The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/> /// </param> private Hashtable AddSystemSpecs(string key, string type, string message) { string addmessage = ""; if (message != "") addmessage = ": " + message; Hashtable parameters = new Hashtable() { { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.EventID], "system:" + key }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea } }; return parameters; } /// <summary> /// Gets the users system type /// </summary> /// <returns> /// String determining the system the user is currently running <see cref="System.String"/> /// </returns> public string GetSystem() { #if UNITY_STANDALONE_OSX return "MAC"; #elif UNITY_STANDALONE_WIN return "PC"; #elif UNITY_WEBPLAYER return "WEBPLAYER"; #elif UNITY_WII return "WII"; #elif UNITY_IPHONE return "IPHONE"; #elif UNITY_ANDROID return "ANDROID"; #elif UNITY_PS3 return "PS3"; #elif UNITY_XBOX360 return "XBOX"; #elif UNITY_FLASH return "FLASH"; #elif UNITY_STANDALONE_LINUX return "LINUX"; #elif UNITY_NACL return "NACL"; #elif UNITY_DASHBOARD_WIDGET return "DASHBOARD_WIDGET"; #elif UNITY_METRO return "WINDOWS_STORE_APP"; #elif UNITY_WP8 return "WINDOWS_PHONE_8"; #elif UNITY_BLACKBERRY return "BLACKBERRY"; #else return "UNKNOWN"; #endif } #endregion }
// Copyright 2014 Mario Guggenberger <mg@protyposis.net> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // UPnP .NET Framework Device Stack, Device Module // Device Builder Build#1.0.4561.18413 using System; using OpenSource.UPnP; using System.Web; using System.Net; using System.Net.Sockets; namespace LocalAudioBroadcast { /// <summary> /// Summary description for SampleDevice. /// </summary> class DirectoryServer { private UPnPDevice device; private IPEndPoint ipEndPoint; public DirectoryServer() { device = UPnPDevice.CreateRootDevice(1800,1.0,"\\"); device.FriendlyName = "Local Audio Broadcast @ " + System.Environment.MachineName; device.Manufacturer = "Mario Guggenberger / Protyposis"; device.ManufacturerURL = "http://protyposis.net"; device.ModelName = "LAB"; device.ModelDescription = "LAB"; device.ModelNumber = "1.0"; device.HasPresentation = false; device.DeviceURN = "urn:schemas-upnp-org:device:MediaServer:1"; DvX_MS_MediaReceiverRegistrar X_MS_MediaReceiverRegistrar = new DvX_MS_MediaReceiverRegistrar(); X_MS_MediaReceiverRegistrar.External_IsAuthorized = new DvX_MS_MediaReceiverRegistrar.Delegate_IsAuthorized(X_MS_MediaReceiverRegistrar_IsAuthorized); X_MS_MediaReceiverRegistrar.External_IsValidated = new DvX_MS_MediaReceiverRegistrar.Delegate_IsValidated(X_MS_MediaReceiverRegistrar_IsValidated); X_MS_MediaReceiverRegistrar.External_RegisterDevice = new DvX_MS_MediaReceiverRegistrar.Delegate_RegisterDevice(X_MS_MediaReceiverRegistrar_RegisterDevice); device.AddService(X_MS_MediaReceiverRegistrar); DvConnectionManager ConnectionManager = new DvConnectionManager(); ConnectionManager.External_GetCurrentConnectionIDs = new DvConnectionManager.Delegate_GetCurrentConnectionIDs(ConnectionManager_GetCurrentConnectionIDs); ConnectionManager.External_GetCurrentConnectionInfo = new DvConnectionManager.Delegate_GetCurrentConnectionInfo(ConnectionManager_GetCurrentConnectionInfo); ConnectionManager.External_GetProtocolInfo = new DvConnectionManager.Delegate_GetProtocolInfo(ConnectionManager_GetProtocolInfo); device.AddService(ConnectionManager); DvContentDirectory ContentDirectory = new DvContentDirectory(); ContentDirectory.External_Browse = new DvContentDirectory.Delegate_Browse(ContentDirectory_Browse); ContentDirectory.External_GetSearchCapabilities = new DvContentDirectory.Delegate_GetSearchCapabilities(ContentDirectory_GetSearchCapabilities); ContentDirectory.External_GetSortCapabilities = new DvContentDirectory.Delegate_GetSortCapabilities(ContentDirectory_GetSortCapabilities); ContentDirectory.External_GetSystemUpdateID = new DvContentDirectory.Delegate_GetSystemUpdateID(ContentDirectory_GetSystemUpdateID); ContentDirectory.External_Search = new DvContentDirectory.Delegate_Search(ContentDirectory_Search); device.AddService(ContentDirectory); // Setting the initial value of evented variables X_MS_MediaReceiverRegistrar.Evented_AuthorizationGrantedUpdateID = 0; X_MS_MediaReceiverRegistrar.Evented_ValidationRevokedUpdateID = 0; X_MS_MediaReceiverRegistrar.Evented_ValidationSucceededUpdateID = 0; X_MS_MediaReceiverRegistrar.Evented_AuthorizationDeniedUpdateID = 0; ConnectionManager.Evented_SourceProtocolInfo = "Sample String"; ConnectionManager.Evented_SinkProtocolInfo = "Sample String"; ConnectionManager.Evented_CurrentConnectionIDs = "Sample String"; ContentDirectory.Evented_ContainerUpdateIDs = "Sample String"; ContentDirectory.Evented_SystemUpdateID = 0; } // TODO: THESE STATIC VARS ARE AN UGLY HACK public static string S1; public static Directory Directory; public void Start() { device.StartDevice(); IPAddress ipAddress = null; foreach (IPEndPoint ipep in device.LocalIPEndPoints) { if (ipep.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { Console.WriteLine("DLNA server STARTED listening @ " + ipep.ToString()); // create HTTP resource server endpoint ipAddress = ipep.Address; break; } } // find a free port for the HTTP server: http://stackoverflow.com/a/9895416 Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Bind(new IPEndPoint(IPAddress.Any, 0)); // Pass 0 here. ipEndPoint = new IPEndPoint(ipAddress, ((IPEndPoint)sock.LocalEndPoint).Port); sock.Close(); S1 = HttpBaseURL + "capture"; Directory = new Directory(S1); } public void Stop() { device.StopDevice(); } public string HttpBaseURL { get { return "http://" + ipEndPoint.ToString() + "/"; } } public IPEndPoint IPEndPoint { get { return ipEndPoint; } } public void X_MS_MediaReceiverRegistrar_IsAuthorized(System.String DeviceID, out System.Int32 Result) { Result = 0; Console.WriteLine("X_MS_MediaReceiverRegistrar_IsAuthorized(" + DeviceID.ToString() + ")"); } public void X_MS_MediaReceiverRegistrar_IsValidated(System.String DeviceID, out System.Int32 Result) { Result = 0; Console.WriteLine("X_MS_MediaReceiverRegistrar_IsValidated(" + DeviceID.ToString() + ")"); } public void X_MS_MediaReceiverRegistrar_RegisterDevice(System.Byte[] RegistrationReqMsg, out System.Byte[] RegistrationRespMsg) { RegistrationRespMsg = null; // "Sample String"; Console.WriteLine("X_MS_MediaReceiverRegistrar_RegisterDevice(" + RegistrationReqMsg.ToString() + ")"); } public void ConnectionManager_GetCurrentConnectionIDs(out System.String ConnectionIDs) { ConnectionIDs = "Sample String"; Console.WriteLine("ConnectionManager_GetCurrentConnectionIDs(" + ")"); } public void ConnectionManager_GetCurrentConnectionInfo(System.Int32 ConnectionID, out System.Int32 RcsID, out System.Int32 AVTransportID, out System.String ProtocolInfo, out System.String PeerConnectionManager, out System.Int32 PeerConnectionID, out DvConnectionManager.Enum_A_ARG_TYPE_Direction Direction, out DvConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus Status) { RcsID = 0; AVTransportID = 0; ProtocolInfo = "Sample String"; PeerConnectionManager = "Sample String"; PeerConnectionID = 0; Direction = DvConnectionManager.Enum_A_ARG_TYPE_Direction.INPUT; Status = DvConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus.OK; Console.WriteLine("ConnectionManager_GetCurrentConnectionInfo(" + ConnectionID.ToString() + ")"); } public void ConnectionManager_GetProtocolInfo(out System.String Source, out System.String Sink) { Source = "Sample String"; Sink = "Sample String"; Console.WriteLine("ConnectionManager_GetProtocolInfo(" + ")"); } public void ContentDirectory_Browse(System.String ObjectID, DvContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID) { Console.WriteLine("DEVICE ContentDirectory_Browse(" + ObjectID.ToString() + BrowseFlag.ToString() + Filter.ToString() + StartingIndex.ToString() + RequestedCount.ToString() + SortCriteria.ToString() + ")"); Result = "Sample String"; NumberReturned = 0; TotalMatches = 0; UpdateID = 0; if (BrowseFlag == DvContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN) { switch (ObjectID) { case "0": // root NumberReturned = Directory.Count; TotalMatches = Directory.Count; Result = Directory.GetDirectoryDidl(); break; } } } public void ContentDirectory_GetSearchCapabilities(out System.String SearchCaps) { SearchCaps = "Sample String"; Console.WriteLine("ContentDirectory_GetSearchCapabilities(" + ")"); } public void ContentDirectory_GetSortCapabilities(out System.String SortCaps) { SortCaps = "Sample String"; Console.WriteLine("ContentDirectory_GetSortCapabilities(" + ")"); } public void ContentDirectory_GetSystemUpdateID(out System.UInt32 Id) { Id = 0; Console.WriteLine("ContentDirectory_GetSystemUpdateID(" + ")"); } public void ContentDirectory_Search(System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID) { Result = "Sample String"; NumberReturned = 0; TotalMatches = 0; UpdateID = 0; Console.WriteLine("ContentDirectory_Search(" + ContainerID.ToString() + SearchCriteria.ToString() + Filter.ToString() + StartingIndex.ToString() + RequestedCount.ToString() + SortCriteria.ToString() + ")"); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography; using System.Text; using System.Web.Script.Serialization; using WhatsAppApi.Helper; using WhatsAppApi.Parser; using WhatsAppApi.Response; using WhatsAppApi.Settings; namespace WhatsAppApi { /// <summary> /// Main api interface /// </summary> public class WhatsApp : WhatsSendBase { public WhatsApp(string phoneNum, string imei, string nick, bool debug = false, bool hidden = false) { this._constructBase(phoneNum, imei, nick, debug, hidden); } public string SendMessage(string to, string txt) { var tmpMessage = new FMessage(GetJID(to), true) { data = txt }; this.SendMessage(tmpMessage, this.hidden); return tmpMessage.identifier_key.ToString(); } public void SendMessageVcard(string to, string name, string vcard_data) { var tmpMessage = new FMessage(GetJID(to), true) { data = vcard_data, media_wa_type = FMessage.Type.Contact, media_name = name }; this.SendMessage(tmpMessage, this.hidden); } //BRIAN ADDED FOR LOCATION SHARING public string SendMessageLocation(string to, string name, double lat, double lon) { var tmpMessage = new FMessage(GetJID(to), true) { location_details = name, media_wa_type = FMessage.Type.Location, latitude = lat, longitude = lon }; this.SendMessage(tmpMessage, this.hidden); return tmpMessage.identifier_key.ToString(); } public void SendSync(string[] numbers, SyncMode mode = SyncMode.Delta, SyncContext context = SyncContext.Background, int index = 0, bool last = true) { List<ProtocolTreeNode> users = new List<ProtocolTreeNode>(); foreach (string number in numbers) { string _number = number; if (!_number.StartsWith("+", StringComparison.InvariantCulture)) _number = string.Format("+{0}", number); users.Add(new ProtocolTreeNode("user", null, System.Text.Encoding.UTF8.GetBytes(_number))); } ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("to", GetJID(this.phoneNumber)), new KeyValue("type", "get"), new KeyValue("id", TicketCounter.MakeId()), new KeyValue("xmlns", "urn:xmpp:whatsapp:sync") }, new ProtocolTreeNode("sync", new KeyValue[] { new KeyValue("mode", mode.ToString().ToLowerInvariant()), new KeyValue("context", context.ToString().ToLowerInvariant()), new KeyValue("sid", DateTime.Now.ToFileTimeUtc().ToString()), new KeyValue("index", index.ToString()), new KeyValue("last", last.ToString()) }, users.ToArray() ) ); this.SendNode(node); } // BRIAN modified added return string .. public string SendMessageImage(string to, byte[] ImageData, ImageType imgtype) { FMessage msg = this.getFmessageImage(to, ImageData, imgtype); if (msg != null) { this.SendMessage(msg); return msg.identifier_key.ToString(); } return ""; } protected FMessage getFmessageImage(string to, byte[] ImageData, ImageType imgtype) { to = GetJID(to); string type = string.Empty; string extension = string.Empty; switch (imgtype) { case ImageType.PNG: type = "image/png"; extension = "png"; break; case ImageType.GIF: type = "image/gif"; extension = "gif"; break; default: type = "image/jpeg"; extension = "jpg"; break; } //create hash string filehash = string.Empty; using(HashAlgorithm sha = HashAlgorithm.Create("sha256")) { byte[] raw = sha.ComputeHash(ImageData); filehash = Convert.ToBase64String(raw); } //request upload WaUploadResponse response = this.UploadFile(filehash, "image", ImageData.Length, ImageData, to, type, extension); if (response != null && !String.IsNullOrEmpty(response.url)) { //send message FMessage msg = new FMessage(to, true) { media_wa_type = FMessage.Type.Image, media_mime_type = response.mimetype, media_name = response.url.Split('/').Last(), media_size = response.size, media_url = response.url, binary_data = this.CreateThumbnail(ImageData) }; return msg; } return null; } // BRIAN MODIFIED FOR RETURN ID public string SendMessageVideo(string to, byte[] videoData, VideoType vidtype) { FMessage msg = this.getFmessageVideo(to, videoData, vidtype); if (msg != null) { this.SendMessage(msg); return msg.identifier_key.ToString(); } return ""; } protected FMessage getFmessageVideo(string to, byte[] videoData, VideoType vidtype) { to = GetJID(to); string type = string.Empty; string extension = string.Empty; switch (vidtype) { case VideoType.MOV: type = "video/quicktime"; extension = "mov"; break; case VideoType.AVI: type = "video/x-msvideo"; extension = "avi"; break; default: type = "video/mp4"; extension = "mp4"; break; } //create hash string filehash = string.Empty; using (HashAlgorithm sha = HashAlgorithm.Create("sha256")) { byte[] raw = sha.ComputeHash(videoData); filehash = Convert.ToBase64String(raw); } //request upload WaUploadResponse response = this.UploadFile(filehash, "video", videoData.Length, videoData, to, type, extension); if (response != null && !String.IsNullOrEmpty(response.url)) { //send message FMessage msg = new FMessage(to, true) { media_wa_type = FMessage.Type.Video, media_mime_type = response.mimetype, media_name = response.url.Split('/').Last(), media_size = response.size, media_url = response.url, media_duration_seconds = response.duration }; return msg; } return null; } public void SendMessageAudio(string to, byte[] audioData, AudioType audtype) { FMessage msg = this.getFmessageAudio(to, audioData, audtype); if (msg != null) { this.SendMessage(msg); } } protected FMessage getFmessageAudio(string to, byte[] audioData, AudioType audtype) { to = GetJID(to); string type = string.Empty; string extension = string.Empty; switch (audtype) { case AudioType.WAV: type = "audio/wav"; extension = "wav"; break; case AudioType.OGG: type = "audio/ogg"; extension = "ogg"; break; default: type = "audio/mpeg"; extension = "mp3"; break; } //create hash string filehash = string.Empty; using (HashAlgorithm sha = HashAlgorithm.Create("sha256")) { byte[] raw = sha.ComputeHash(audioData); filehash = Convert.ToBase64String(raw); } //request upload WaUploadResponse response = this.UploadFile(filehash, "audio", audioData.Length, audioData, to, type, extension); if (response != null && !String.IsNullOrEmpty(response.url)) { //send message FMessage msg = new FMessage(to, true) { media_wa_type = FMessage.Type.Audio, media_mime_type = response.mimetype, media_name = response.url.Split('/').Last(), media_size = response.size, media_url = response.url, media_duration_seconds = response.duration }; return msg; } return null; } protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension) { ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] { new KeyValue("hash", b64hash), new KeyValue("type", type), new KeyValue("size", size.ToString()) }); string id = TicketManager.GenerateId(); ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", to), new KeyValue("type", "set"), new KeyValue("xmlns", "w:m") }, media); this.uploadResponse = null; this.SendNode(node); int i = 0; while (this.uploadResponse == null && i <= 100) { if (m_usePoolMessages) System.Threading.Thread.Sleep(500); else this.pollMessage(); i++; } if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null) { WaUploadResponse res = new WaUploadResponse(this.uploadResponse); this.uploadResponse = null; return res; } else { try { string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url"); this.uploadResponse = null; Uri uri = new Uri(uploadUrl); string hashname = string.Empty; byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash)); StringBuilder sb = new StringBuilder(); foreach (byte b in buff) { sb.Append(b.ToString("X2")); } hashname = String.Format("{0}.{1}", sb.ToString(), extension); string boundary = "zzXXzzYYzzXXzzQQ"; sb = new StringBuilder(); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", to); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", this.phoneNumber); sb.AppendFormat("--{0}\r\n", boundary); sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname); sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype); string header = sb.ToString(); sb = new StringBuilder(); sb.AppendFormat("\r\n--{0}--\r\n", boundary); string footer = sb.ToString(); long clength = size + header.Length + footer.Length; sb = new StringBuilder(); sb.AppendFormat("POST {0}\r\n", uploadUrl); sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary); sb.AppendFormat("Host: {0}\r\n", uri.Host); sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgent); sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength); string post = sb.ToString(); TcpClient tc = new TcpClient(uri.Host, 443); SslStream ssl = new SslStream(tc.GetStream()); try { ssl.AuthenticateAsClient(uri.Host); } catch (Exception e) { throw e; } List<byte> buf = new List<byte>(); buf.AddRange(Encoding.UTF8.GetBytes(post)); buf.AddRange(Encoding.UTF8.GetBytes(header)); buf.AddRange(fileData); buf.AddRange(Encoding.UTF8.GetBytes(footer)); ssl.Write(buf.ToArray(), 0, buf.ToArray().Length); //moment of truth... buff = new byte[1024]; ssl.Read(buff, 0, 1024); string result = Encoding.UTF8.GetString(buff); foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("{")) { string fooo = line.TrimEnd(new char[] { (char)0 }); JavaScriptSerializer jss = new JavaScriptSerializer(); WaUploadResponse resp = jss.Deserialize<WaUploadResponse>(fooo); if (!String.IsNullOrEmpty(resp.url)) { return resp; } } } } catch (Exception) { } } return null; } protected void SendQrSync(byte[] qrkey, byte[] token = null) { string id = TicketCounter.MakeId(); List<ProtocolTreeNode> children = new List<ProtocolTreeNode>(); children.Add(new ProtocolTreeNode("sync", null, qrkey)); if (token != null) { children.Add(new ProtocolTreeNode("code", null, token)); } ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] { new KeyValue("type", "set"), new KeyValue("id", id), new KeyValue("xmlns", "w:web") }, children.ToArray()); this.SendNode(node); } public void SendActive() { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "active") }); this.SendNode(node); } public void SendAddParticipants(string gjid, IEnumerable<string> participants) { string id = TicketCounter.MakeId(); this.SendVerbParticipants(gjid, participants, id, "add"); } public void SendUnavailable() { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") }); this.SendNode(node); } public void SendClientConfig(string platform, string lg, string lc) { string v = TicketCounter.MakeId(); var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push"), new KeyValue("platform", platform), new KeyValue("lg", lg), new KeyValue("lc", lc) }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", v), new KeyValue("type", "set"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendClientConfig(string platform, string lg, string lc, Uri pushUri, bool preview, bool defaultSetting, bool groupsSetting, IEnumerable<GroupSetting> groups, Action onCompleted, Action<int> onError) { string id = TicketCounter.MakeId(); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("to", "") //this.Login.Domain) }, new ProtocolTreeNode[] { new ProtocolTreeNode("config", new[] { new KeyValue("xmlns","urn:xmpp:whatsapp:push"), new KeyValue("platform", platform), new KeyValue("lg", lg), new KeyValue("lc", lc), new KeyValue("clear", "0"), new KeyValue("id", pushUri.ToString()), new KeyValue("preview",preview ? "1" : "0"), new KeyValue("default",defaultSetting ? "1" : "0"), new KeyValue("groups",groupsSetting ? "1" : "0") }, this.ProcessGroupSettings(groups)) }); this.SendNode(node); } public void SendClose() { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unavailable") }); this.SendNode(node); } public void SendComposing(string to) { this.SendChatState(to, "composing"); } protected void SendChatState(string to, string type) { var node = new ProtocolTreeNode("chatstate", new[] { new KeyValue("to", WhatsApp.GetJID(to)) }, new[] { new ProtocolTreeNode(type, null) }); this.SendNode(node); } public void SendCreateGroupChat(string subject, IEnumerable<string> participants) { string id = TicketCounter.MakeId(); IEnumerable<ProtocolTreeNode> participant = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) }); var child = new ProtocolTreeNode("create", new[] { new KeyValue("subject", subject) }, new ProtocolTreeNode[] { (ProtocolTreeNode) participant }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendDeleteAccount() { string id = TicketCounter.MakeId(); var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net"), new KeyValue("xmlns", "urn:xmpp:whatsapp:account") }, new ProtocolTreeNode[] { new ProtocolTreeNode("remove", null ) }); this.SendNode(node); } public void SendDeleteFromRoster(string jid) { string v = TicketCounter.MakeId(); var innerChild = new ProtocolTreeNode("item", new[] { new KeyValue("jid", jid), new KeyValue("subscription", "remove") }); var child = new ProtocolTreeNode("query", new[] { new KeyValue("xmlns", "jabber:iq:roster") }, new ProtocolTreeNode[] { innerChild }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("type", "set"), new KeyValue("id", v) }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendEndGroupChat(string gjid) { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("group", new[] { new KeyValue("action", "delete") }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendGetClientConfig() { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("config", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:push") }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", WhatsConstants.WhatsAppRealm) }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendGetDirty() { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("status", new[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:dirty") }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendGetGroupInfo(string gjid) { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("query", null); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(gjid)) }, new ProtocolTreeNode[] { child }); this.SendNode(node); } public void SendGetGroups() { string id = TicketCounter.MakeId(); this.SendGetGroups(id, "participating"); } public void SendGetOwningGroups() { string id = TicketCounter.MakeId(); this.SendGetGroups(id, "owning"); } public void SendGetParticipants(string gjid) { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("list", null); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", WhatsApp.GetJID(gjid)) }, child); this.SendNode(node); } public string SendGetPhoto(string jid, string expectedPhotoId, bool largeFormat) { string id = TicketCounter.MakeId(); var attrList = new List<KeyValue>(); if (!largeFormat) { attrList.Add(new KeyValue("type", "preview")); } if (expectedPhotoId != null) { attrList.Add(new KeyValue("id", expectedPhotoId)); } var child = new ProtocolTreeNode("picture", attrList.ToArray()); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", WhatsAppApi.WhatsApp.GetJID(jid)) }, child); this.SendNode(node); return id; } public void SendGetPhotoIds(IEnumerable<string> jids) { string id = TicketCounter.MakeId(); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(this.phoneNumber)) }, new ProtocolTreeNode("list", new[] { new KeyValue("xmlns", "w:profile:picture") }, (from jid in jids select new ProtocolTreeNode("user", new[] { new KeyValue("jid", jid) })).ToArray<ProtocolTreeNode>())); this.SendNode(node); } public void SendGetPrivacyList() { string id = TicketCounter.MakeId(); var innerChild = new ProtocolTreeNode("list", new[] { new KeyValue("name", "default") }); var child = new ProtocolTreeNode("query", null, innerChild); var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "jabber:iq:privacy") }, child); this.SendNode(node); } public void SendGetServerProperties() { string id = TicketCounter.MakeId(); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w"), new KeyValue("to", "s.whatsapp.net") }, new ProtocolTreeNode("props", null)); this.SendNode(node); } public void SendGetStatuses(string[] jids) { List<ProtocolTreeNode> targets = new List<ProtocolTreeNode>(); foreach (string jid in jids) { targets.Add(new ProtocolTreeNode("user", new[] { new KeyValue("jid", GetJID(jid)) }, null, null)); } ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] { new KeyValue("to", "s.whatsapp.net"), new KeyValue("type", "get"), new KeyValue("xmlns", "status"), new KeyValue("id", TicketCounter.MakeId()) }, new[] { new ProtocolTreeNode("status", null, targets.ToArray(), null) }, null); this.SendNode(node); } public void SendInactive() { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "inactive") }); this.SendNode(node); } public void SendLeaveGroup(string gjid) { this.SendLeaveGroups(new string[] { gjid }); } public void SendLeaveGroups(IEnumerable<string> gjids) { string id = TicketCounter.MakeId(); IEnumerable<ProtocolTreeNode> innerChilds = from gjid in gjids select new ProtocolTreeNode("group", new[] { new KeyValue("id", gjid) }); var child = new ProtocolTreeNode("leave", null, innerChilds); var node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child); this.SendNode(node); } public void SendMessage(FMessage message, bool hidden = false) { if (message.media_wa_type != FMessage.Type.Undefined) { this.SendMessageWithMedia(message); } else { this.SendMessageWithBody(message, hidden); } } //BRIAN MODIFIED FOR RETURN ID public string SendMessageBroadcast(string[] to, string message) { var tmpMessage = new FMessage(string.Empty, true) { data = message, media_wa_type = FMessage.Type.Undefined }; this.SendMessageBroadcast(to, tmpMessage); return tmpMessage.identifier_key.ToString(); } //BRIAN MODIFIED FOR RETURN ID public string SendMessageBroadcastImage(string[] recipients, byte[] ImageData, ImageType imgtype) { string to; List<string> foo = new List<string>(); foreach (string s in recipients) { foo.Add(GetJID(s)); } to = string.Join(",", foo.ToArray()); FMessage msg = this.getFmessageImage(to, ImageData, imgtype); if (msg != null) { this.SendMessage(msg); return msg.identifier_key.ToString(); } return ""; } //BRIAN MODIFIED FOR RETURN ID public string SendMessageBroadcastAudio(string[] recipients, byte[] AudioData, AudioType audtype) { string to; List<string> foo = new List<string>(); foreach (string s in recipients) { foo.Add(GetJID(s)); } to = string.Join(",", foo.ToArray()); FMessage msg = this.getFmessageAudio(to, AudioData, audtype); if (msg != null) { this.SendMessage(msg); return msg.identifier_key.ToString(); } return ""; } //BRIAN MODIFIED FOR RETURN ID public string SendMessageBroadcastVideo(string[] recipients, byte[] VideoData, VideoType vidtype) { string to; List<string> foo = new List<string>(); foreach (string s in recipients) { foo.Add(GetJID(s)); } to = string.Join(",", foo.ToArray()); FMessage msg = this.getFmessageVideo(to, VideoData, vidtype); if (msg != null) { this.SendMessage(msg); return msg.identifier_key.ToString(); } return ""; } public void SendMessageBroadcast(string[] to, FMessage message) { if (to != null && to.Length > 0 && message != null && !string.IsNullOrEmpty(message.data)) { ProtocolTreeNode child; if (message.media_wa_type == FMessage.Type.Undefined) { //text broadcast child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data)); } else { throw new NotImplementedException(); } List<ProtocolTreeNode> toNodes = new List<ProtocolTreeNode>(); foreach (string target in to) { toNodes.Add(new ProtocolTreeNode("to", new KeyValue[] { new KeyValue("jid", WhatsAppApi.WhatsApp.GetJID(target)) })); } ProtocolTreeNode broadcastNode = new ProtocolTreeNode("broadcast", null, toNodes); Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; ProtocolTreeNode messageNode = new ProtocolTreeNode("message", new KeyValue[] { new KeyValue("to", unixTimestamp.ToString() + "@broadcast"), new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"), new KeyValue("id", message.identifier_key.id) }, new ProtocolTreeNode[] { broadcastNode, child }); this.SendNode(messageNode); } } public void SendNop() { this.SendNode(null); } public void SendPaused(string to) { this.SendChatState(to, "paused"); } public void SendPing() { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("ping", null); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("xmlns", "w:p"), new KeyValue("type", "get"), new KeyValue("to", "s.whatsapp.net") }, child); this.SendNode(node); } public void SendPresenceSubscriptionRequest(string to) { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "subscribe"), new KeyValue("to", GetJID(to)) }); this.SendNode(node); } public void SendQueryLastOnline(string jid) { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("query", null); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("to", GetJID(jid)), new KeyValue("xmlns", "jabber:iq:last") }, child); this.SendNode(node); } public void SendRemoveParticipants(string gjid, List<string> participants) { string id = TicketCounter.MakeId(); this.SendVerbParticipants(gjid, participants, id, "remove"); } public void SendSetGroupSubject(string gjid, string subject) { string id = TicketCounter.MakeId(); var child = new ProtocolTreeNode("subject", new[] { new KeyValue("value", subject) }); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", gjid) }, child); this.SendNode(node); } public void SendSetPhoto(string jid, byte[] bytes, byte[] thumbnailBytes = null) { string id = TicketCounter.MakeId(); bytes = this.ProcessProfilePicture(bytes); var list = new List<ProtocolTreeNode> { new ProtocolTreeNode("picture", null, null, bytes) }; if (thumbnailBytes == null) { //auto generate thumbnailBytes = this.CreateThumbnail(bytes); } //debug System.IO.File.WriteAllBytes("pic.jpg", bytes); System.IO.File.WriteAllBytes("picthumb.jpg", thumbnailBytes); if (thumbnailBytes != null) { list.Add(new ProtocolTreeNode("picture", new[] { new KeyValue("type", "preview") }, null, thumbnailBytes)); } var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:profile:picture"), new KeyValue("to", GetJID(jid)) }, list.ToArray()); this.SendNode(node); } public void SendSetPrivacyBlockedList(IEnumerable<string> jidSet) { string id = TicketCounter.MakeId(); ProtocolTreeNode[] nodeArray = Enumerable.Select<string, ProtocolTreeNode>(jidSet, (Func<string, int, ProtocolTreeNode>)((jid, index) => new ProtocolTreeNode("item", new KeyValue[] { new KeyValue("type", "jid"), new KeyValue("value", jid), new KeyValue("action", "deny"), new KeyValue("order", index.ToString(CultureInfo.InvariantCulture)) }))).ToArray<ProtocolTreeNode>(); var child = new ProtocolTreeNode("list", new KeyValue[] { new KeyValue("name", "default") }, (nodeArray.Length == 0) ? null : nodeArray); var node2 = new ProtocolTreeNode("query", null, child); var node3 = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "jabber:iq:privacy") }, node2); this.SendNode(node3); } public void SendStatusUpdate(string status) { string id = TicketCounter.MakeId(); ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("to", "s.whatsapp.net"), new KeyValue("type", "set"), new KeyValue("id", id), new KeyValue("xmlns", "status") }, new [] { new ProtocolTreeNode("status", null, System.Text.Encoding.UTF8.GetBytes(status)) }); this.SendNode(node); } public void SendSubjectReceived(string to, string id) { var child = new ProtocolTreeNode("received", new[] { new KeyValue("xmlns", "urn:xmpp:receipts") }); var node = GetSubjectMessage(to, id, child); this.SendNode(node); } public void SendUnsubscribeHim(string jid) { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribed"), new KeyValue("to", jid) }); this.SendNode(node); } public void SendUnsubscribeMe(string jid) { var node = new ProtocolTreeNode("presence", new[] { new KeyValue("type", "unsubscribe"), new KeyValue("to", jid) }); this.SendNode(node); } public void SendGetGroups(string id, string type) { var child = new ProtocolTreeNode(type, null); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "get"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", "g.us") }, child); this.SendNode(node); } protected void SendMessageWithBody(FMessage message, bool hidden = false) { var child = new ProtocolTreeNode("body", null, null, WhatsApp.SYSEncoding.GetBytes(message.data)); this.SendNode(GetMessageNode(message, child, hidden)); } protected void SendMessageWithMedia(FMessage message) { ProtocolTreeNode node; if (FMessage.Type.System == message.media_wa_type) { throw new SystemException("Cannot send system message over the network"); } List<KeyValue> list = new List<KeyValue>(new KeyValue[] { new KeyValue("xmlns", "urn:xmpp:whatsapp:mms"), new KeyValue("type", FMessage.GetMessage_WA_Type_StrValue(message.media_wa_type)) }); if (FMessage.Type.Location == message.media_wa_type) { list.AddRange(new KeyValue[] { new KeyValue("latitude", message.latitude.ToString(CultureInfo.InvariantCulture)), new KeyValue("longitude", message.longitude.ToString(CultureInfo.InvariantCulture)) }); if (message.location_details != null) { list.Add(new KeyValue("name", message.location_details)); } if (message.location_url != null) { list.Add(new KeyValue("url", message.location_url)); } } else if (((FMessage.Type.Contact != message.media_wa_type) && (message.media_name != null)) && ((message.media_url != null) && (message.media_size > 0L))) { list.AddRange(new KeyValue[] { new KeyValue("file", message.media_name), new KeyValue("size", message.media_size.ToString(CultureInfo.InvariantCulture)), new KeyValue("url", message.media_url) }); if (message.media_duration_seconds > 0) { list.Add(new KeyValue("seconds", message.media_duration_seconds.ToString(CultureInfo.InvariantCulture))); } } if ((FMessage.Type.Contact == message.media_wa_type) && (message.media_name != null)) { node = new ProtocolTreeNode("media", list.ToArray(), new ProtocolTreeNode("vcard", new KeyValue[] { new KeyValue("name", message.media_name) }, WhatsApp.SYSEncoding.GetBytes(message.data))); } else { byte[] data = message.binary_data; if ((data == null) && !string.IsNullOrEmpty(message.data)) { try { data = Convert.FromBase64String(message.data); } catch (Exception) { } } if (data != null) { list.Add(new KeyValue("encoding", "raw")); } node = new ProtocolTreeNode("media", list.ToArray(), null, data); } this.SendNode(GetMessageNode(message, node)); } protected void SendVerbParticipants(string gjid, IEnumerable<string> participants, string id, string inner_tag) { IEnumerable<ProtocolTreeNode> source = from jid in participants select new ProtocolTreeNode("participant", new[] { new KeyValue("jid", GetJID(jid)) }); var child = new ProtocolTreeNode(inner_tag, null, source); var node = new ProtocolTreeNode("iq", new[] { new KeyValue("id", id), new KeyValue("type", "set"), new KeyValue("xmlns", "w:g2"), new KeyValue("to", GetJID(gjid)) }, child); this.SendNode(node); } public void SendSetPrivacySetting(VisibilityCategory category, VisibilitySetting setting) { ProtocolTreeNode node = new ProtocolTreeNode("iq", new[] { new KeyValue("to", "s.whatsapp.net"), new KeyValue("id", TicketCounter.MakeId()), new KeyValue("type", "set"), new KeyValue("xmlns", "privacy") }, new ProtocolTreeNode[] { new ProtocolTreeNode("privacy", null, new ProtocolTreeNode[] { new ProtocolTreeNode("category", new [] { new KeyValue("name", this.privacyCategoryToString(category)), new KeyValue("value", this.privacySettingToString(setting)) }) }) }); this.SendNode(node); } public void SendGetPrivacySettings() { ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("to", "s.whatsapp.net"), new KeyValue("id", TicketCounter.MakeId()), new KeyValue("type", "get"), new KeyValue("xmlns", "privacy") }, new ProtocolTreeNode[] { new ProtocolTreeNode("privacy", null) }); this.SendNode(node); } protected IEnumerable<ProtocolTreeNode> ProcessGroupSettings(IEnumerable<GroupSetting> groups) { ProtocolTreeNode[] nodeArray = null; if ((groups != null) && groups.Any<GroupSetting>()) { DateTime now = DateTime.Now; nodeArray = (from @group in groups select new ProtocolTreeNode("item", new[] { new KeyValue("jid", @group.Jid), new KeyValue("notify", @group.Enabled ? "1" : "0"), new KeyValue("mute", string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}", new object[] { (!@group.MuteExpiry.HasValue || (@group.MuteExpiry.Value <= now)) ? 0 : ((int) (@group.MuteExpiry.Value - now).TotalSeconds) })) })).ToArray<ProtocolTreeNode>(); } return nodeArray; } protected static ProtocolTreeNode GetMessageNode(FMessage message, ProtocolTreeNode pNode, bool hidden = false) { Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; return new ProtocolTreeNode("message", new[] { new KeyValue("to", message.identifier_key.remote_jid), new KeyValue("type", message.media_wa_type == FMessage.Type.Undefined?"text":"media"), new KeyValue("id", message.identifier_key.id), new KeyValue("t",unixTimestamp.ToString()) }, new ProtocolTreeNode[] { pNode }); } protected static ProtocolTreeNode GetSubjectMessage(string to, string id, ProtocolTreeNode child) { return new ProtocolTreeNode("message", new[] { new KeyValue("to", to), new KeyValue("type", "subject"), new KeyValue("id", id) }, child); } } }
using System.Collections.Generic; using System; namespace ClickHouse.Ado.Impl.ATG.Insert { internal class Parser { public const int _EOF = 0; public const int _ident = 1; public const int _stringValue = 2; public const int _numValue = 3; public const int _insert = 4; public const int _values = 5; public const int _into = 6; public const int maxT = 13; const bool T = true; const bool x = false; const int minErrDist = 2; public Scanner scanner; public Errors errors; public Token t; // last recognized token public Token la; // lookahead token int errDist = minErrDist; public enum ConstType{String,Number,Parameter}; internal IEnumerable<string> fieldList; internal IEnumerable<Tuple<string,ConstType> > valueList; internal string oneParam,tableName; public Parser(Scanner scanner) { this.scanner = scanner; errors = new Errors(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (string msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } bool StartOf (int s) { return set[s, la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } bool WeakSeparator(int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) {Get(); return true;} else if (StartOf(repFol)) {return false;} else { SynErr(n); while (!(set[syFol, kind] || set[repFol, kind] || set[0, kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } void Field(out string name ) { Expect(1); name=t.val; } void FieldList(out IEnumerable<string> elements ) { var rv=new List<string>(); elements=rv; string elem; IEnumerable<string> inner; Field(out elem); rv.Add(elem); if (la.kind == 7) { Get(); FieldList(out inner); rv.AddRange(inner); } } void Parameter(out string name ) { if (la.kind == 8) { Get(); } else if (la.kind == 9) { Get(); } else SynErr(14); Expect(1); name=t.val; } void Value(out Tuple<string,ConstType> val ) { val = null; string paramName=null; if (la.kind == 2) { Get(); val=Tuple.Create(t.val,ConstType.String); } else if (la.kind == 8 || la.kind == 9) { Parameter(out paramName); val=Tuple.Create(paramName,ConstType.Parameter); } else if (la.kind == 3) { Get(); val=Tuple.Create(t.val,ConstType.Number); } else SynErr(15); } void ValueList(out IEnumerable<Tuple<string,ConstType> > elements ) { var rv=new List<Tuple<string,ConstType> >(); elements=rv; Tuple<string,ConstType> elem; IEnumerable<Tuple<string,ConstType> > inner; Value(out elem); rv.Add(elem); if (la.kind == 7) { Get(); ValueList(out inner); rv.AddRange(inner); } } void Insert() { Expect(4); Expect(6); Field(out tableName); Expect(10); FieldList(out fieldList); Expect(11); Expect(5); if (la.kind == 8 || la.kind == 9) { Parameter(out oneParam); } else if (la.kind == 10) { Get(); ValueList(out valueList); Expect(11); } else SynErr(16); while (la.kind == 12) { Get(); } } public void Parse() { la = new Token(); la.val = ""; Get(); Insert(); Expect(0); } static readonly bool[,] set = { {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x} }; } // end Parser internal class Errors { public int count = 0; // number of errors detected public System.IO.TextWriter errorStream = Console.Out; // error messages go to this stream public string errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text public virtual void SynErr (int line, int col, int n) { string s; switch (n) { case 0: s = "EOF expected"; break; case 1: s = "ident expected"; break; case 2: s = "stringValue expected"; break; case 3: s = "numValue expected"; break; case 4: s = "insert expected"; break; case 5: s = "values expected"; break; case 6: s = "into expected"; break; case 7: s = "\",\" expected"; break; case 8: s = "\"@\" expected"; break; case 9: s = "\":\" expected"; break; case 10: s = "\"(\" expected"; break; case 11: s = "\")\" expected"; break; case 12: s = "\";\" expected"; break; case 13: s = "??? expected"; break; case 14: s = "invalid Parameter"; break; case 15: s = "invalid Value"; break; case 16: s = "invalid Insert"; break; default: s = "error " + n; break; } errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); count++; } public virtual void SemErr (string s) { errorStream.WriteLine(s); count++; } public virtual void Warning (int line, int col, string s) { errorStream.WriteLine(errMsgFormat, line, col, s); } public virtual void Warning(string s) { errorStream.WriteLine(s); } } // Errors internal class FatalError: Exception { public FatalError(string m): base(m) {} } }
// // This file is part of the game Voxalia, created by FreneticXYZ. // This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license. // See README.md or LICENSE.txt for contents of the MIT license. // If these are not available, see https://opensource.org/licenses/MIT // using Voxalia.ServerGame.EntitySystem; using Voxalia.Shared; using Voxalia.ServerGame.JointSystem; using BEPUutilities; using BEPUphysics.CollisionRuleManagement; using Voxalia.Shared.Collision; namespace Voxalia.ServerGame.ItemSystem.CommonItems { class HookItem : BaseItemInfo { public HookItem() { Name = "hook"; } public override void Click(Entity entity, ItemStack item) { if (!(entity is PlayerEntity)) { // TODO: non-player support return; } PlayerEntity player = (PlayerEntity)entity; if (player.LastClick + 0.2 > player.TheRegion.GlobalTickTime) { return; } Location eye = player.GetEyePosition(); Location adj = player.ForwardVector() * 20f; CollisionResult cr = player.TheRegion.Collision.CuboidLineTrace(new Location(0.1f), eye, eye + adj, player.IgnoreThis); if (!cr.Hit) { return; } ApplyHook(player, item, cr.Position, cr.HitEnt); } public void ApplyHook(PlayerEntity player, ItemStack item, Location Position, BEPUphysics.Entities.Entity HitEnt) { RemoveHook(player); PhysicsEntity pe; double len = (double)(Position - player.GetCenter()).Length(); Location step = (player.GetCenter() - Position) / len; Location forw = Utilities.VectorToAngles(step); BEPUutilities.Quaternion quat = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), (double)(forw.Pitch * Utilities.PI180)) * Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), (double)(forw.Yaw * Utilities.PI180)); if (HitEnt == null) { ModelEntity mod = new ModelEntity("cube", player.TheRegion); mod.Mass = 0; mod.CanSave = false; mod.scale = new Location(0.023, 0.05, 0.05); mod.mode = ModelCollisionMode.AABB; mod.SetPosition(Position); mod.SetOrientation(quat); player.TheRegion.SpawnEntity(mod); pe = mod; player.Hooks.Add(new HookInfo() { Joint = null, Hit = pe, IsBar = true }); } else { pe = (PhysicsEntity)HitEnt.Tag; } JointDistance jd; //jd = new JointDistance(player, pe, 0.01f, len + 0.01f, player.GetCenter(), Position); //player.TheRegion.AddJoint(jd); //player.Hooks.Add(new HookInfo() { Joint = jd, Hit = pe, IsBar = false }); PhysicsEntity cent = pe; for (double f = 0; f < len - 1f; f += 0.5f) { Location cpos = Position + step * f; ModelEntity ce = new ModelEntity("cube", player.TheRegion); ce.Mass = 15; ce.CanSave = false; ce.scale = new Location(0.023, 0.05, 0.05); ce.mode = ModelCollisionMode.AABB; ce.SetPosition(cpos + step * 0.5); ce.SetOrientation(quat); player.TheRegion.SpawnEntity(ce); jd = new JointDistance(ce, cent, 0.01f, 0.5f, ce.GetPosition(), (ReferenceEquals(cent, pe) ? Position: cent.GetPosition())); CollisionRules.AddRule(player.Body, ce.Body, CollisionRule.NoBroadPhase); player.TheRegion.AddJoint(jd); player.Hooks.Add(new HookInfo() { Joint = jd, Hit = ce, IsBar = true }); cent = ce; } jd = new JointDistance(cent, player, 0.01f, 0.5f, cent.GetPosition(), player.GetCenter()); player.TheRegion.AddJoint(jd); player.Hooks.Add(new HookInfo() { Joint = jd, Hit = player, IsBar = false }); } public override void AltClick(Entity entity, ItemStack item) { if (!(entity is PlayerEntity)) { // TODO: non-player support return; } PlayerEntity player = (PlayerEntity)entity; if (player.LastAltClick + 0.2 > player.TheRegion.GlobalTickTime) { return; } RemoveHook(player); } public override void ReleaseClick(Entity entity, ItemStack item) { } public override void ReleaseAltClick(Entity entity, ItemStack item) { } public static void RemoveHook(PlayerEntity player) { if (player.Hooks.Count > 0) { for (int i = 0; i < player.Hooks.Count; i++) { if (player.Hooks[i].Joint != null) { player.TheRegion.DestroyJoint(player.Hooks[i].Joint); } } for (int i = 0; i < player.Hooks.Count; i++) { if (player.Hooks[i].IsBar) { player.Hooks[i].Hit.RemoveMe(); } } player.Hooks.Clear(); } } public override void PrepItem(Entity entity, ItemStack item) { } public override void SwitchFrom(Entity entity, ItemStack item) { } public override void SwitchTo(Entity entity, ItemStack item) { } public override void Use(Entity entity, ItemStack item) { } public void Shrink(PlayerEntity player) { for (int i = 0; i < player.Hooks.Count; i++) { if (player.Hooks[i].Joint != null) { if (player.Hooks[i].Joint.Max > 0.3f) { player.Hooks[i].Joint.Max *= 0.9f; // TODO: less lazy networking of this player.TheRegion.DestroyJoint(player.Hooks[i].Joint); player.TheRegion.AddJoint(player.Hooks[i].Joint); } } } } public void Extend(PlayerEntity player) { for (int i = 0; i < player.Hooks.Count; i++) { if (player.Hooks[i].Joint != null) { if (player.Hooks[i].Joint.Max < 3f) { player.Hooks[i].Joint.Max *= 1.1f; // TODO: less lazy networking of this player.TheRegion.DestroyJoint(player.Hooks[i].Joint); player.TheRegion.AddJoint(player.Hooks[i].Joint); } } } } public override void Tick(Entity entity, ItemStack item) { if (!(entity is PlayerEntity)) { // TODO: non-player support return; } PlayerEntity player = (PlayerEntity)entity; if (player.ItemLeft && !player.WasItemLefting && player.Hooks.Count > 0) { Extend(player); } if (player.ItemRight && !player.WasItemRighting && player.Hooks.Count > 0) { Shrink(player); } } } public class HookInfo { public PhysicsEntity Hit = null; public JointDistance Joint = null; public bool IsBar = false; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase { [Fact] public void CreateBuilderDefaultCapacity() { var builder = ImmutableArray.CreateBuilder<int>(); Assert.NotNull(builder); Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>()); } [Fact] public void CreateBuilderInvalidCapacity() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => ImmutableArray.CreateBuilder<int>(-1)); } [Fact] public void NormalConstructionValueType() { var builder = ImmutableArray.CreateBuilder<int>(3); Assert.Equal(0, builder.Count); Assert.False(((ICollection<int>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Equal(0, builder[i]); } builder.Add(5); builder.Add(6); builder.Add(7); Assert.Equal(5, builder[0]); Assert.Equal(6, builder[1]); Assert.Equal(7, builder[2]); } [Fact] public void NormalConstructionRefType() { var builder = new ImmutableArray<GenericParameterHelper>.Builder(3); Assert.Equal(0, builder.Count); Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Null(builder[i]); } builder.Add(new GenericParameterHelper(5)); builder.Add(new GenericParameterHelper(6)); builder.Add(new GenericParameterHelper(7)); Assert.Equal(5, builder[0].Data); Assert.Equal(6, builder[1].Data); Assert.Equal(7, builder[2].Data); } [Fact] public void AddRangeIEnumerable() { var builder = new ImmutableArray<int>.Builder(2); builder.AddRange((IEnumerable<int>)new[] { 1 }); Assert.Equal(1, builder.Count); builder.AddRange((IEnumerable<int>)new[] { 2 }); Assert.Equal(2, builder.Count); builder.AddRange((IEnumerable<int>)new int[0]); Assert.Equal(2, builder.Count); // Exceed capacity builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count Assert.Equal(4, builder.Count); Assert.Equal(Enumerable.Range(1, 4), builder); } [Fact] public void Add() { var builder = ImmutableArray.CreateBuilder<int>(0); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(1); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(2); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); } [Fact] public void AddRangeBuilder() { var builder1 = new ImmutableArray<int>.Builder(2); var builder2 = new ImmutableArray<int>.Builder(2); builder1.AddRange(builder2); Assert.Equal(0, builder1.Count); Assert.Equal(0, builder2.Count); builder2.Add(1); builder2.Add(2); builder1.AddRange(builder2); Assert.Equal(2, builder1.Count); Assert.Equal(2, builder2.Count); Assert.Equal(new[] { 1, 2 }, builder1); } [Fact] public void AddRangeImmutableArray() { var builder1 = new ImmutableArray<int>.Builder(2); var array = ImmutableArray.Create(1, 2, 3); builder1.AddRange(array); Assert.Equal(new[] { 1, 2, 3 }, builder1); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((int[])null)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange(null, 42)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], 42)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((ImmutableArray<int>.Builder)null)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((IEnumerable<int>)null)); Assert.Throws<NullReferenceException>(() => builder1.AddRange(default(ImmutableArray<int>))); builder1.AddRange(default(ImmutableArray<int>), 42); var builder2 = new ImmutableArray<object>.Builder(); builder2.AddRange(default(ImmutableArray<string>)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder2.AddRange((ImmutableArray<string>.Builder)null)); } [Fact] public void AddRangeDerivedArray() { var builder = new ImmutableArray<object>.Builder(); builder.AddRange(new[] { "a", "b" }); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedImmutableArray() { var builder = new ImmutableArray<object>.Builder(); builder.AddRange(new[] { "a", "b" }.ToImmutableArray()); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedBuilder() { var builder = new ImmutableArray<string>.Builder(); builder.AddRange(new[] { "a", "b" }); var builderBase = new ImmutableArray<object>.Builder(); builderBase.AddRange(builder); Assert.Equal(new[] { "a", "b" }, builderBase); } [Fact] public void Contains() { var builder = new ImmutableArray<int>.Builder(); Assert.False(builder.Contains(1)); builder.Add(1); Assert.True(builder.Contains(1)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Insert() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3); builder.Insert(1, 4); builder.Insert(4, 5); Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Count + 1, 0)); } [Fact] public void Remove() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); Assert.True(builder.Remove(1)); Assert.False(builder.Remove(6)); Assert.Equal(new[] { 2, 3, 4 }, builder); Assert.True(builder.Remove(3)); Assert.Equal(new[] { 2, 4 }, builder); Assert.True(builder.Remove(4)); Assert.Equal(new[] { 2 }, builder); Assert.True(builder.Remove(2)); Assert.Equal(0, builder.Count); } [Fact] public void RemoveAt() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); builder.RemoveAt(0); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(3)); Assert.Equal(new[] { 2, 3, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); Assert.Equal(0, builder.Count); } [Fact] public void ReverseContents() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); builder.Reverse(); Assert.Equal(new[] { 4, 3, 2, 1 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 1, 2, 3 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 3, 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new int[0], builder); } [Fact] public void Sort() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(2, 4, 1, 3); builder.Sort(); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void Sort_Comparison() { var builder = new ImmutableArray<int>.Builder(4); builder.Sort((x, y) => y.CompareTo(x)); Assert.Equal(Array.Empty<int>(), builder); builder.AddRange(2, 4, 1, 3); builder.Sort((x, y) => y.CompareTo(x)); Assert.Equal(new[] { 4, 3, 2, 1 }, builder); builder.Add(5); builder.Sort((x, y) => x.CompareTo(y)); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, builder); } [Fact] public void Sort_NullComparison_Throws() { AssertExtensions.Throws<ArgumentNullException>("comparison", () => ImmutableArray.CreateBuilder<int>().Sort((Comparison<int>)null)); } [Fact] public void SortNullComparer() { var template = ImmutableArray.Create(2, 4, 1, 3); var builder = template.ToBuilder(); builder.Sort((IComparer<int>)null); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); builder = template.ToBuilder(); builder.Sort(1, 2, null); Assert.Equal(new[] { 2, 1, 4, 3 }, builder); } [Fact] public void SortOneElementArray() { int[] resultantArray = new[] { 4 }; var builder1 = new ImmutableArray<int>.Builder(); builder1.Add(4); builder1.Sort(); Assert.Equal(resultantArray, builder1); var builder2 = new ImmutableArray<int>.Builder(); builder2.Add(4); builder2.Sort(Comparer<int>.Default); Assert.Equal(resultantArray, builder2); var builder3 = new ImmutableArray<int>.Builder(); builder3.Add(4); builder3.Sort(0, 1, Comparer<int>.Default); Assert.Equal(resultantArray, builder3); } [Fact] public void SortRange() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(2, 4, 1, 3); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Sort(-1, 2, Comparer<int>.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(1, 4, Comparer<int>.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(0, -1, Comparer<int>.Default)); builder.Sort(builder.Count, 0, Comparer<int>.Default); Assert.Equal(new int[] { 2, 4, 1, 3 }, builder); builder.Sort(1, 2, Comparer<int>.Default); Assert.Equal(new[] { 2, 1, 4, 3 }, builder); } [Fact] public void SortComparer() { var builder1 = new ImmutableArray<string>.Builder(); var builder2 = new ImmutableArray<string>.Builder(); builder1.AddRange("c", "B", "a"); builder2.AddRange("c", "B", "a"); builder1.Sort(StringComparer.OrdinalIgnoreCase); builder2.Sort(StringComparer.Ordinal); Assert.Equal(new[] { "a", "B", "c" }, builder1); Assert.Equal(new[] { "B", "a", "c" }, builder2); } [Fact] public void Count() { var builder = new ImmutableArray<int>.Builder(3); // Initial count is at zero, which is less than capacity. Assert.Equal(0, builder.Count); // Expand the accessible region of the array by increasing the count, but still below capacity. builder.Count = 2; Assert.Equal(2, builder.Count); Assert.Equal(2, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); // Expand the accessible region of the array beyond the current capacity. builder.Count = 4; Assert.Equal(4, builder.Count); Assert.Equal(4, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Equal(0, builder[2]); Assert.Equal(0, builder[3]); Assert.Throws<IndexOutOfRangeException>(() => builder[4]); } [Fact] public void CountContract() { var builder = new ImmutableArray<int>.Builder(100); builder.AddRange(Enumerable.Range(1, 100)); builder.Count = 10; Assert.Equal(Enumerable.Range(1, 10), builder); builder.Count = 100; Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder); } [Fact] public void IndexSetter() { var builder = new ImmutableArray<int>.Builder(); Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1); Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1); builder.Count = 1; builder[0] = 2; Assert.Equal(2, builder[0]); builder.Count = 10; builder[9] = 3; Assert.Equal(3, builder[9]); builder.Count = 2; Assert.Equal(2, builder[0]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); } [Fact] public void ToImmutable() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3); ImmutableArray<int> array = builder.ToImmutable(); Assert.Equal(1, array[0]); Assert.Equal(2, array[1]); Assert.Equal(3, array[2]); // Make sure that subsequent mutation doesn't impact the immutable array. builder[1] = 5; Assert.Equal(5, builder[1]); Assert.Equal(2, array[1]); builder.Clear(); Assert.True(builder.ToImmutable().IsEmpty); } [Fact] public void CopyTo() { var builder = ImmutableArray.Create(1, 2, 3).ToBuilder(); var target = new int[4]; builder.CopyTo(target, 1); Assert.Equal(new[] { 0, 1, 2, 3 }, target); AssertExtensions.Throws<ArgumentNullException>("array", () => builder.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, 2)); } [Fact] public void Clear() { var builder = new ImmutableArray<int>.Builder(2); builder.Add(1); builder.Add(1); builder.Clear(); Assert.Equal(0, builder.Count); Assert.Throws<IndexOutOfRangeException>(() => builder[0]); } [Fact] public void MutationsSucceedAfterToImmutable() { var builder = new ImmutableArray<int>.Builder(1); builder.Add(1); var immutable = builder.ToImmutable(); builder[0] = 0; Assert.Equal(0, builder[0]); Assert.Equal(1, immutable[0]); } [Fact] public void Enumerator() { var empty = new ImmutableArray<int>.Builder(0); var enumerator = empty.GetEnumerator(); Assert.False(enumerator.MoveNext()); var manyElements = new ImmutableArray<int>.Builder(3); manyElements.AddRange(1, 2, 3); enumerator = manyElements.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void IEnumerator() { var empty = new ImmutableArray<int>.Builder(0); var enumerator = ((IEnumerable<int>)empty).GetEnumerator(); Assert.False(enumerator.MoveNext()); var manyElements = new ImmutableArray<int>.Builder(3); manyElements.AddRange(1, 2, 3); enumerator = ((IEnumerable<int>)manyElements).GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void MoveToImmutableNormal() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.Count); Assert.Equal(2, builder.Capacity); builder[1] = "b"; builder[0] = "a"; var array = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array); Assert.Equal(0, builder.Count); Assert.Equal(0, builder.Capacity); } [Fact] public void MoveToImmutableRepeat() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; var array1 = builder.MoveToImmutable(); var array2 = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array1); Assert.Equal(0, array2.Length); } [Fact] public void MoveToImmutablePartialFill() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable()); } [Fact] public void MoveToImmutablePartialFillWithCountUpdate() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); builder.Count = builder.Capacity; var array = builder.MoveToImmutable(); Assert.Equal(new[] { 42, 13, 0, 0 }, array); } [Fact] public void MoveToImmutableThenUse() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.MoveToImmutable().Length); Assert.Equal(0, builder.Capacity); builder.Add("a"); builder.Add("b"); Assert.Equal(2, builder.Count); Assert.True(builder.Capacity >= 2); Assert.Equal(new[] { "a", "b" }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAfterClear() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; builder.Clear(); Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableInsertToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Insert(i, i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRangeToCapcity() { var array = new[] { 1, 2, 3, 4, 5 }; var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: array.Length); builder.AddRange(array); Assert.Equal(array, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRemoveAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); builder.RemoveAt(i); builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void CapacitySetToZero() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Capacity = 0; Assert.Equal(0, builder.Capacity); Assert.Equal(new int[] { }, builder.ToArray()); } [Fact] public void CapacitySetToLessThanCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(1); Assert.Throws(typeof(ArgumentException), () => builder.Capacity = 1); } [Fact] public void CapacitySetToCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Count; Assert.Equal(2, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Capacity; Assert.Equal(10, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToBiggerCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = 20; Assert.Equal(20, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.CreateBuilder<int>()); ImmutableArray<string>.Builder builder = ImmutableArray.CreateBuilder<string>(4); builder.AddRange("One", "Two", "Three", "Four"); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); string[] items = itemProperty.GetValue(info.Instance) as string[]; Assert.Equal(builder, items); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableArray.CreateBuilder<string>(4)); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } [Fact] public void ItemRef() { var builder = new ImmutableArray<int>.Builder(); builder.Add(1); builder.Add(2); builder.Add(3); ref readonly var safeRef = ref builder.ItemRef(1); ref var unsafeRef = ref Unsafe.AsRef(safeRef); Assert.Equal(2, builder.ItemRef(1)); unsafeRef = 4; Assert.Equal(4, builder.ItemRef(1)); } [Fact] public void ItemRef_OutOfBounds() { var builder = new ImmutableArray<int>.Builder(); builder.Add(1); builder.Add(2); builder.Add(3); Assert.Throws<IndexOutOfRangeException>(() => builder.ItemRef(5)); } private static ImmutableArray<T>.Builder CreateBuilderWithCount<T>(int count) { var builder = ImmutableArray.CreateBuilder<T>(count); builder.Count = count; return builder; } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { var builder = new ImmutableArray<T>.Builder(contents.Length); builder.AddRange(contents); return builder; } } }
// 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. using Google.Cloud.Spanner.NHibernate.IntegrationTests.InterleavedTableTests.Entities; using Xunit; namespace Google.Cloud.Spanner.NHibernate.IntegrationTests.InterleavedTableTests { [Collection(nameof(NonParallelTestCollection))] public class InterleavedTableTests : IClassFixture<SpannerInterleavedTableFixture> { private readonly SpannerInterleavedTableFixture _fixture; public InterleavedTableTests(SpannerInterleavedTableFixture fixture) => _fixture = fixture; [Fact] public void CanDropAndRecreateSchema() { var initialSchema = SchemaTests.GetCurrentSchema(_fixture); var exporter = new SpannerSchemaExport(_fixture.Configuration); exporter.Execute(false, true, false); SchemaTests.VerifySchemaEquality(initialSchema, _fixture); } [InlineData(MutationUsage.Never)] [InlineData(MutationUsage.Always)] [Theory] public void CanCreateRows(MutationUsage mutationUsage) { using var session = _fixture.SessionFactory.OpenSession(); using var transaction = session.BeginTransaction(mutationUsage); var singer = new Singer { FirstName = "Pete", LastName = "Allison", }; var singerId = session.Save(singer); var album = new Album { AlbumIdentifier = new AlbumIdentifier(singer), Title = "My first album" }; var albumId = session.Save(album); var track = new Track { TrackIdentifier = new TrackIdentifier(album), Title = "My first track", }; var trackId = session.Save(track); transaction.Commit(); session.Clear(); singer = session.Load<Singer>(singerId); album = session.Load<Album>(albumId); track = session.Load<Track>(trackId); Assert.Equal(singerId, singer.SingerId); Assert.Equal("Pete", singer.FirstName); Assert.Equal("Allison", singer.LastName); Assert.Equal("My first album", album.Title); Assert.Equal(albumId, album.AlbumIdentifier); Assert.Equal("My first album", album.Title); Assert.Equal(trackId, track.TrackIdentifier); Assert.Equal("My first track", track.Title); Assert.Equal(singer.SingerId, album.Singer.SingerId); Assert.Equal(singer.FirstName, album.Singer.FirstName); Assert.Equal(singer.LastName, album.Singer.LastName); Assert.Equal(album.AlbumIdentifier, track.Album.AlbumIdentifier); Assert.Equal(singer.SingerId, track.Album.Singer.SingerId); Assert.Equal(singer.FirstName, track.Album.Singer.FirstName); Assert.Equal(singer.LastName, track.Album.Singer.LastName); Assert.Collection(singer.Albums, album => Assert.Equal("My first album", album.Title)); Assert.Collection(album.Tracks, track => Assert.Equal("My first track", track.Title)); } [InlineData(MutationUsage.Never)] [InlineData(MutationUsage.Always)] [Theory] public void CanUpdateRows(MutationUsage mutationUsage) { object singerId, albumId, trackId; using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var singer = new Singer { FirstName = "Pete", LastName = "Allison", }; singerId = session.Save(singer); var album = new Album { AlbumIdentifier = new AlbumIdentifier(singer), Title = "My first album" }; albumId = session.Save(album); trackId = session.Save(new Track { TrackIdentifier = new TrackIdentifier(album), Title = "My first track", }); transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var singer = session.Load<Singer>(singerId); var album = session.Load<Album>(albumId); var track = session.Load<Track>(trackId); singer.LastName = "Allison-Peterson"; album.Title = "My second album"; track.Title = "My second track"; transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { var singer = session.Load<Singer>(singerId); var album = session.Load<Album>(albumId); var track = session.Load<Track>(trackId); Assert.Equal("Pete", singer.FirstName); Assert.Equal("Allison-Peterson", singer.LastName); Assert.Equal("My second album", album.Title); Assert.Equal("My second track", track.Title); } } [InlineData(MutationUsage.Never)] [InlineData(MutationUsage.Always)] [Theory] public void CanDeleteRows(MutationUsage mutationUsage) { object singerId, albumId, trackId; using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var singer = new Singer { FirstName = "Pete", LastName = "Allison", }; singerId = session.Save(singer); var album = new Album { AlbumIdentifier = new AlbumIdentifier(singer), Title = "My first album" }; albumId = session.Save(album); trackId = session.Save(new Track { TrackIdentifier = new TrackIdentifier(album), Title = "My first track", }); transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var singer = session.Load<Singer>(singerId); var album = session.Load<Album>(albumId); var track = session.Load<Track>(trackId); session.Delete(track); session.Delete(album); session.Delete(singer); transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { var singer = session.Get<Singer>(singerId); var album = session.Get<Album>(albumId); var track = session.Get<Track>(trackId); Assert.Null(singer); Assert.Null(album); Assert.Null(track); } } [InlineData(MutationUsage.Never)] [InlineData(MutationUsage.Always)] [Theory] public void CanUseCascadeDelete(MutationUsage mutationUsage) { object singerId, albumId, trackId; using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var singer = new Singer { FirstName = "Pete", LastName = "Allison", }; singerId = session.Save(singer); var album = new Album { AlbumIdentifier = new AlbumIdentifier(singer), Title = "My first album" }; albumId = session.Save(album); trackId = session.Save(new Track { TrackIdentifier = new TrackIdentifier(album), Title = "My first track", }); transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { using var transaction = session.BeginTransaction(mutationUsage); var album = session.Load<Album>(albumId); // We can delete an album without first deleting its tracks, as the INTERLEAVE IN relationship has been // created with ON DELETE CASCADE. session.Delete(album); transaction.Commit(); } using (var session = _fixture.SessionFactory.OpenSession()) { var singer = session.Get<Singer>(singerId); var album = session.Get<Album>(albumId); var track = session.Get<Track>(trackId); Assert.NotNull(singer); Assert.Null(album); Assert.Null(track); } } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using FarseerPhysics.Common; using FarseerPhysics.Common.Decomposition; using Microsoft.Xna.Framework; namespace FarseerPhysics.Collision.Shapes { /// <summary> /// Represents a simple non-selfintersecting convex polygon. /// If you want to have concave polygons, you will have to use the <see cref="BayazitDecomposer"/> or the <see cref="EarclipDecomposer"/> /// to decompose the concave polygon into 2 or more convex polygons. /// </summary> public class PolygonShape : Shape { public Vertices Normals; public Vertices Vertices; /// <summary> /// Initializes a new instance of the <see cref="PolygonShape"/> class. /// </summary> /// <param name="vertices">The vertices.</param> /// <param name="density">The density.</param> public PolygonShape(Vertices vertices, float density) : base(density) { ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; Set(vertices); } public PolygonShape(float density) : base(density) { ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; Normals = new Vertices(); Vertices = new Vertices(); } internal PolygonShape() : base(0) { ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; Normals = new Vertices(); Vertices = new Vertices(); } public override int ChildCount { get { return 1; } } public override Shape Clone() { PolygonShape clone = new PolygonShape(); clone.ShapeType = ShapeType; clone._radius = _radius; clone._density = _density; if (Settings.ConserveMemory) { #pragma warning disable 162 clone.Vertices = Vertices; clone.Normals = Normals; #pragma warning restore 162 } else { clone.Vertices = new Vertices(Vertices); clone.Normals = new Vertices(Normals); } clone.MassData = MassData; return clone; } /// <summary> /// Copy vertices. This assumes the vertices define a convex polygon. /// It is assumed that the exterior is the the right of each edge. /// </summary> /// <param name="vertices">The vertices.</param> public void Set(Vertices vertices) { Debug.Assert(vertices.Count >= 3 && vertices.Count <= Settings.MaxPolygonVertices); #pragma warning disable 162 if (Settings.ConserveMemory) Vertices = vertices; else // Copy vertices. Vertices = new Vertices(vertices); #pragma warning restore 162 Normals = new Vertices(vertices.Count); // Compute normals. Ensure the edges have non-zero length. for (int i = 0; i < vertices.Count; ++i) { int i1 = i; int i2 = i + 1 < vertices.Count ? i + 1 : 0; Vector2 edge = Vertices[i2] - Vertices[i1]; Debug.Assert(edge.LengthSquared() > Settings.Epsilon * Settings.Epsilon); Vector2 temp = new Vector2(edge.Y, -edge.X); temp.Normalize(); Normals.Add(temp); } #if DEBUG // Ensure the polygon is convex and the interior // is to the left of each edge. for (int i = 0; i < Vertices.Count; ++i) { int i1 = i; int i2 = i + 1 < Vertices.Count ? i + 1 : 0; Vector2 edge = Vertices[i2] - Vertices[i1]; for (int j = 0; j < vertices.Count; ++j) { // Don't check vertices on the current edge. if (j == i1 || j == i2) { continue; } Vector2 r = Vertices[j] - Vertices[i1]; // Your polygon is non-convex (it has an indentation) or // has colinear edges. float s = edge.X * r.Y - edge.Y * r.X; Debug.Assert(s > 0.0f); } } #endif // Compute the polygon mass data ComputeProperties(); } /// <summary> /// Compute the mass properties of this shape using its dimensions and density. /// The inertia tensor is computed about the local origin, not the centroid. /// </summary> public override void ComputeProperties() { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.X = (1/mass) * rho * int(x * dA) // centroid.Y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. Debug.Assert(Vertices.Count >= 3); if (_density <= 0) return; Vector2 center = Vector2.Zero; float area = 0.0f; float I = 0.0f; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). Vector2 pRef = Vector2.Zero; #if false // This code would put the reference point inside the polygon. for (int i = 0; i < count; ++i) { pRef += vs[i]; } pRef *= 1.0f / count; #endif const float inv3 = 1.0f / 3.0f; for (int i = 0; i < Vertices.Count; ++i) { // Triangle vertices. Vector2 p1 = pRef; Vector2 p2 = Vertices[i]; Vector2 p3 = i + 1 < Vertices.Count ? Vertices[i + 1] : Vertices[0]; Vector2 e1 = p2 - p1; Vector2 e2 = p3 - p1; float d; MathUtils.Cross(ref e1, ref e2, out d); float triangleArea = 0.5f * d; area += triangleArea; // Area weighted centroid center += triangleArea * inv3 * (p1 + p2 + p3); float px = p1.X, py = p1.Y; float ex1 = e1.X, ey1 = e1.Y; float ex2 = e2.X, ey2 = e2.Y; float intx2 = inv3 * (0.25f * (ex1 * ex1 + ex2 * ex1 + ex2 * ex2) + (px * ex1 + px * ex2)) + 0.5f * px * px; float inty2 = inv3 * (0.25f * (ey1 * ey1 + ey2 * ey1 + ey2 * ey2) + (py * ey1 + py * ey2)) + 0.5f * py * py; I += d * (intx2 + inty2); } //The area is too small for the engine to handle. Debug.Assert(area > Settings.Epsilon); // We save the area MassData.Area = area; // Total mass MassData.Mass = _density * area; // Center of mass center *= 1.0f / area; MassData.Centroid = center; // Inertia tensor relative to the local origin. MassData.Inertia = _density * I; } /// <summary> /// Build vertices to represent an axis-aligned box. /// </summary> /// <param name="halfWidth">The half-width.</param> /// <param name="halfHeight">The half-height.</param> public void SetAsBox(float halfWidth, float halfHeight) { Set(PolygonTools.CreateRectangle(halfWidth, halfHeight)); } /// <summary> /// Build vertices to represent an oriented box. /// </summary> /// <param name="halfWidth">The half-width..</param> /// <param name="halfHeight">The half-height.</param> /// <param name="center">The center of the box in local coordinates.</param> /// <param name="angle">The rotation of the box in local coordinates.</param> public void SetAsBox(float halfWidth, float halfHeight, Vector2 center, float angle) { Set(PolygonTools.CreateRectangle(halfWidth, halfHeight, center, angle)); } /// <summary> /// Test a point for containment in this shape. This only works for convex shapes. /// </summary> /// <param name="transform">The shape world transform.</param> /// <param name="point">a point in world coordinates.</param> /// <returns>True if the point is inside the shape</returns> public override bool TestPoint(ref Transform transform, ref Vector2 point) { Vector2 pLocal = MathUtils.MultiplyT(ref transform.R, point - transform.Position); for (int i = 0; i < Vertices.Count; ++i) { float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]); if (dot > 0.0f) { return false; } } return true; } /// <summary> /// Cast a ray against a child shape. /// </summary> /// <param name="output">The ray-cast results.</param> /// <param name="input">The ray-cast input parameters.</param> /// <param name="transform">The transform to be applied to the shape.</param> /// <param name="childIndex">The child shape index.</param> /// <returns>True if the ray-cast hits the shape</returns> public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex) { output = new RayCastOutput(); // Put the ray into the polygon's frame of reference. Vector2 p1 = MathUtils.MultiplyT(ref transform.R, input.Point1 - transform.Position); Vector2 p2 = MathUtils.MultiplyT(ref transform.R, input.Point2 - transform.Position); Vector2 d = p2 - p1; float lower = 0.0f, upper = input.MaxFraction; int index = -1; for (int i = 0; i < Vertices.Count; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1); float denominator = Vector2.Dot(Normals[i], d); if (denominator == 0.0f) { if (numerator < 0.0f) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0.0f && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0.0f && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. //if (upper < lower - b2_epsilon) if (upper < lower) { return false; } } Debug.Assert(0.0f <= lower && lower <= input.MaxFraction); if (index >= 0) { output.Fraction = lower; output.Normal = MathUtils.Multiply(ref transform.R, Normals[index]); return true; } return false; } /// <summary> /// Given a transform, compute the associated axis aligned bounding box for a child shape. /// </summary> /// <param name="aabb">The aabb results.</param> /// <param name="transform">The world transform of the shape.</param> /// <param name="childIndex">The child shape index.</param> public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex) { Vector2 lower = MathUtils.Multiply(ref transform, Vertices[0]); Vector2 upper = lower; for (int i = 1; i < Vertices.Count; ++i) { Vector2 v = MathUtils.Multiply(ref transform, Vertices[i]); lower = Vector2.Min(lower, v); upper = Vector2.Max(upper, v); } Vector2 r = new Vector2(Radius, Radius); aabb.LowerBound = lower - r; aabb.UpperBound = upper + r; } public bool CompareTo(PolygonShape shape) { if (Vertices.Count != shape.Vertices.Count) return false; for (int i = 0; i < Vertices.Count; i++) { if (Vertices[i] != shape.Vertices[i]) return false; } return (Radius == shape.Radius && MassData == shape.MassData); } public override float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc) { sc = Vector2.Zero; //Transform plane into shape co-ordinates Vector2 normalL = MathUtils.MultiplyT(ref xf.R, normal); float offsetL = offset - Vector2.Dot(normal, xf.Position); float[] depths = new float[Settings.MaxPolygonVertices]; int diveCount = 0; int intoIndex = -1; int outoIndex = -1; bool lastSubmerged = false; int i; for (i = 0; i < Vertices.Count; i++) { depths[i] = Vector2.Dot(normalL, Vertices[i]) - offsetL; bool isSubmerged = depths[i] < -Settings.Epsilon; if (i > 0) { if (isSubmerged) { if (!lastSubmerged) { intoIndex = i - 1; diveCount++; } } else { if (lastSubmerged) { outoIndex = i - 1; diveCount++; } } } lastSubmerged = isSubmerged; } switch (diveCount) { case 0: if (lastSubmerged) { //Completely submerged sc = MathUtils.Multiply(ref xf, MassData.Centroid); return MassData.Mass / Density; } else { //Completely dry return 0; } #pragma warning disable 162 break; #pragma warning restore 162 case 1: if (intoIndex == -1) { intoIndex = Vertices.Count - 1; } else { outoIndex = Vertices.Count - 1; } break; } int intoIndex2 = (intoIndex + 1) % Vertices.Count; int outoIndex2 = (outoIndex + 1) % Vertices.Count; float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); Vector2 intoVec = new Vector2( Vertices[intoIndex].X * (1 - intoLambda) + Vertices[intoIndex2].X * intoLambda, Vertices[intoIndex].Y * (1 - intoLambda) + Vertices[intoIndex2].Y * intoLambda); Vector2 outoVec = new Vector2( Vertices[outoIndex].X * (1 - outoLambda) + Vertices[outoIndex2].X * outoLambda, Vertices[outoIndex].Y * (1 - outoLambda) + Vertices[outoIndex2].Y * outoLambda); //Initialize accumulator float area = 0; Vector2 center = new Vector2(0, 0); Vector2 p2 = Vertices[intoIndex2]; Vector2 p3; float k_inv3 = 1.0f / 3.0f; //An awkward loop from intoIndex2+1 to outIndex2 i = intoIndex2; while (i != outoIndex2) { i = (i + 1) % Vertices.Count; if (i == outoIndex2) p3 = outoVec; else p3 = Vertices[i]; //Add the triangle formed by intoVec,p2,p3 { Vector2 e1 = p2 - intoVec; Vector2 e2 = p3 - intoVec; float D = MathUtils.Cross(e1, e2); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid center += triangleArea * k_inv3 * (intoVec + p2 + p3); } // p2 = p3; } //Normalize and transform centroid center *= 1.0f / area; sc = MathUtils.Multiply(ref xf, center); return area; } } }
/* Based on "Subkismet - The Cure For Comment Spam" v1.0: http://subkismet.codeplex.com/ * * License: New BSD License * ------------------------------------- * Copyright (c) 2007-2008, Phil Haack * All rights reserved. * Modified by Jaben Cargman for YAF in 2010 * * 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 Subkismet nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.* */ namespace YAF.Core.Services.CheckForSpam { #region Using using System; using System.Globalization; using System.Net; using System.Text; using System.Web; using YAF.Types; using YAF.Types.Extensions; #endregion /// <summary> /// The client class used to communicate with the spam service. /// </summary> [Serializable] public abstract class CheckForSpamClientBase : ICheckForSpamClient { #region Constants and Fields /// <summary> /// The http client. /// </summary> [NonSerialized] protected readonly HttpClient httpClient; /// <summary> /// The api key. /// </summary> protected string apiKey; /// <summary> /// The proxy. /// </summary> protected IWebProxy proxy; /// <summary> /// The root url. /// </summary> protected Uri rootUrl; /// <summary> /// The check url. /// </summary> protected Uri submitCheckUrl; /// <summary> /// The submit ham url. /// </summary> protected Uri submitHamUrl; /// <summary> /// The submit spam url. /// </summary> protected Uri submitSpamUrl; /// <summary> /// The timeout. /// </summary> protected int timeout = 5000; /// <summary> /// The user agent. /// </summary> protected string userAgent; /// <summary> /// The verify url. /// </summary> protected Uri verifyUrl; /// <summary> /// The version. /// </summary> private static readonly string version = typeof(HttpClient).Assembly.GetName().Version.ToString(); #endregion #region Constructors and Destructors /// <summary> /// Initializes a new instance of the <see cref="CheckForSpamClientBase"/> class. /// </summary> /// <remarks> /// This constructor takes in all the dependencies to allow for /// dependency injection and unit testing. Seems like overkill, /// but it's worth it. /// </remarks> /// <param name="apiKey"> /// The Akismet API key. /// </param> /// <param name="blogUrl"> /// The root url of the blog. /// </param> /// <param name="httpClient"> /// Client class used to make the underlying requests. /// </param> protected CheckForSpamClientBase( [NotNull] string apiKey, [NotNull] Uri blogUrl, [NotNull] HttpClient httpClient) { CodeContracts.VerifyNotNull(apiKey, "apiKey"); CodeContracts.VerifyNotNull(blogUrl, "blogUrl"); CodeContracts.VerifyNotNull(httpClient, "httpClient"); this.apiKey = apiKey; this.rootUrl = blogUrl; this.httpClient = httpClient; this.SetServiceUrls(); } /// <summary> /// Initializes a new instance of the <see cref="CheckForSpamClientBase"/> class. /// </summary> /// <param name="apiKey"> /// The Akismet API key. /// </param> /// <param name="rootUrl"> /// The root url of the site using Akismet. /// </param> protected CheckForSpamClientBase([NotNull] string apiKey, [NotNull] Uri rootUrl) : this(apiKey, rootUrl, new HttpClient()) { } #endregion #region Properties /// <summary> /// Gets or sets the Akismet API key. /// </summary> /// <value>The API key.</value> [NotNull] public string ApiKey { get { return this.apiKey ?? string.Empty; } set { this.apiKey = value ?? string.Empty; this.SetServiceUrls(); } } /// <summary> /// Gets or sets the proxy to use. /// </summary> /// <value>The proxy.</value> public IWebProxy Proxy { get { return this.proxy; } set { this.proxy = value; } } /// <summary> /// Gets or sets the root URL to the blog. /// </summary> /// <value>The blog URL.</value> public Uri RootUrl { get { return this.rootUrl; } set { this.rootUrl = value; } } /// <summary> /// Gets or sets the timeout in milliseconds for the http request to Akismet. /// By default 5000 (5 seconds). /// </summary> /// <value>The timeout.</value> public int Timeout { get { return this.timeout; } set { this.timeout = value; } } /// <summary> /// Gets or sets the Usera Agent for the Akismet Client. /// Do not confuse this with the user agent for the comment /// being checked. /// </summary> /// <value>The API key.</value> [NotNull] public string UserAgent { get { return this.userAgent ?? BuildUserAgent("Subkismet"); } set { this.userAgent = value; } } /// <summary> /// Gets CheckUrlFormat. /// </summary> protected abstract string CheckUrlFormat { get; } /// <summary> /// Gets SubmitHamUrlFormat. /// </summary> protected abstract string SubmitHamUrlFormat { get; } /// <summary> /// Gets SubmitSpamUrlFormat. /// </summary> protected abstract string SubmitSpamUrlFormat { get; } /// <summary> /// Gets SubmitVerifyKeyFormat. /// </summary> protected abstract string SubmitVerifyKeyFormat { get; } #endregion #region Public Methods /// <summary> /// Helper method for building a user agent string in the format /// preferred by Akismet. /// </summary> /// <param name="applicationName"> /// Name of the application. /// </param> /// <returns> /// The build user agent. /// </returns> [NotNull] public static string BuildUserAgent([NotNull] string applicationName) { CodeContracts.VerifyNotNull(applicationName, "applicationName"); return string.Format(CultureInfo.InvariantCulture, "{0}/{1} | Akismet/1.11", applicationName, version); } #endregion #region Implemented Interfaces #region ICheckForSpamClient /// <summary> /// Checks the comment and returns true if it is spam, otherwise false. /// </summary> /// <param name="comment">The comment.</param> /// <param name="result">The result.</param> /// <returns> /// The check comment for spam. /// </returns> /// <exception cref="InvalidResponseException">Akismet returned an empty response /// or</exception> /// <exception cref="InvalidResponseException">Akismet returned an empty response</exception> public bool CheckCommentForSpam(IComment comment, out string result) { CodeContracts.VerifyNotNull(comment, "comment"); result = this.SubmitComment(comment, this.submitCheckUrl); if (result.IsNotSet()) { throw new InvalidResponseException("Akismet returned an empty response"); } if (result != "true" && result != "false") { throw new InvalidResponseException( string.Format( CultureInfo.InvariantCulture, "Received the response '{0}' from Akismet. Probably a bad API key.", result)); } return bool.Parse(result); } /// <summary> /// Submits a comment to Akismet that should not have been /// flagged as SPAM (a false positive). /// </summary> /// <param name="comment"> /// </param> public void SubmitHam(IComment comment) { this.SubmitComment(comment, this.submitHamUrl); } /// <summary> /// Submits a comment to Akismet that should have been /// flagged as SPAM, but was not flagged by Akismet. /// </summary> /// <param name="comment"> /// </param> public void SubmitSpam(IComment comment) { this.SubmitComment(comment, this.submitSpamUrl); } /// <summary> /// Verifies the API key. You really only need to /// call this once, perhaps at startup. /// </summary> /// <returns> /// The verify api key. /// </returns> /// <exception type="Sytsem.Web.WebException"> /// If it cannot make a request of Akismet. /// </exception> /// <exception cref="InvalidResponseException"> /// Akismet returned an empty response /// </exception> public bool VerifyApiKey() { string parameters = "key=" + HttpUtility.UrlEncode(this.ApiKey) + "&blog=" + HttpUtility.UrlEncode(this.RootUrl.ToString()); string result = this.httpClient.PostRequest( this.verifyUrl, this.UserAgent, this.Timeout, parameters, this.proxy); if (result.IsNotSet()) { throw new InvalidResponseException("Akismet returned an empty response"); } return String.Equals("valid", result, StringComparison.InvariantCultureIgnoreCase); } #endregion #endregion #region Methods /// <summary> /// The set service urls. /// </summary> protected void SetServiceUrls() { this.submitHamUrl = new Uri(String.Format(CultureInfo.InvariantCulture, this.SubmitHamUrlFormat, this.apiKey)); this.submitSpamUrl = new Uri(String.Format(CultureInfo.InvariantCulture, this.SubmitSpamUrlFormat, this.apiKey)); this.submitCheckUrl = new Uri(String.Format(CultureInfo.InvariantCulture, this.CheckUrlFormat, this.apiKey)); this.verifyUrl = new Uri(String.Format(CultureInfo.InvariantCulture, this.SubmitVerifyKeyFormat, this.apiKey)); } /// <summary> /// The submit comment. /// </summary> /// <param name="comment"> /// The comment. /// </param> /// <param name="url"> /// The url. /// </param> /// <returns> /// The submit comment. /// </returns> private string SubmitComment([NotNull] IComment comment, [NotNull] Uri url) { // Not too many concatenations. Might not need a string builder. CodeContracts.VerifyNotNull(comment, "comment"); CodeContracts.VerifyNotNull(url, "url"); var parameters = new StringBuilder(); parameters.AppendFormat( "blog={0}&user_ip={1}&user_agent={2}", HttpUtility.UrlEncode(this.rootUrl.ToString()), comment.IPAddress, HttpUtility.UrlEncode(comment.UserAgent)); if (comment.Referrer.IsSet()) { parameters.AppendFormat("&referer={0}", HttpUtility.UrlEncode(comment.Referrer)); } if (comment.Permalink != null) { parameters.AppendFormat("&permalink={0}", HttpUtility.UrlEncode(comment.Permalink.ToString())); } if (comment.CommentType.IsSet()) { parameters.AppendFormat("&comment_type={0}", HttpUtility.UrlEncode(comment.CommentType)); } if (comment.Author.IsSet()) { parameters.AppendFormat("&comment_author={0}", HttpUtility.UrlEncode(comment.Author)); } if (comment.AuthorEmail.IsSet()) { parameters.AppendFormat("&comment_author_email={0}", HttpUtility.UrlEncode(comment.AuthorEmail)); } if (comment.AuthorUrl != null) { parameters.AppendFormat("&comment_author_url={0}", HttpUtility.UrlEncode(comment.AuthorUrl.ToString())); } if (comment.Content.IsSet()) { parameters.AppendFormat("&comment_content={0}", HttpUtility.UrlEncode(comment.Content)); } if (comment.ServerEnvironmentVariables != null) { foreach (string s in comment.ServerEnvironmentVariables) { parameters.AppendFormat("&{0}={1}", s, HttpUtility.UrlEncode(comment.ServerEnvironmentVariables[s])); } } string response = this.httpClient.PostRequest( url, this.UserAgent, this.Timeout, parameters.ToString(), this.proxy); return response == null ? string.Empty : response.ToLower(CultureInfo.InvariantCulture); } #endregion } }
using System.Linq; using Toggl.Networking.Sync.Push; using Toggl.Networking.Serialization; using Toggl.Shared.Models; using Xunit; using FluentAssertions; namespace Toggl.Networking.Tests.Sync.Push { public sealed class ResponseTests { string json = @" { ""clients"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Client A"", ""workspace_id"": 789 } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Client A"", ""workspace_id"": 789 } } }, { ""type"": ""delete"", ""meta"": {""id"": ""789""}, ""payload"": { ""success"": true } } ], ""projects"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Project A"", ""workspace_id"": 789 } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Project A"", ""workspace_id"": 789 } } }, { ""type"": ""delete"", ""meta"": {""id"": ""789""}, ""payload"": { ""success"": true } } ], ""tags"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Tag A"", ""workspace_id"": 789 } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Tag A"", ""workspace_id"": 789 } } }, { ""type"": ""delete"", ""meta"": {""id"": ""789""}, ""payload"": { ""success"": true } } ], ""tasks"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Task A"", ""workspace_id"": 789, ""project_id"": 123, } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Task A"", ""workspace_id"": 789, ""project_id"": 123, } } }, { ""type"": ""delete"", ""meta"": {""id"": ""789""}, ""payload"": { ""success"": true } } ], ""time_entries"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""description"": ""Time Entry A"", ""workspace_id"": 789 } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""description"": ""Time Entry A"", ""workspace_id"": 789 } } }, { ""type"": ""delete"", ""meta"": {""id"": ""789""}, ""payload"": { ""success"": true } } ], ""workspaces"": [ { ""type"": ""create"", ""meta"": {""client_assigned_id"": ""-123""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Workspace A"" } } }, { ""type"": ""update"", ""meta"": {""id"": ""456""}, ""payload"": { ""success"": true, ""result"": { ""id"": 456, ""name"": ""Workspace A"" } } } ], ""user"": { ""success"": true, ""result"": { ""fullname"": ""User A"" } }, ""preferences"": { ""success"": true, ""result"": { ""duration_format"": ""classic"" } } }"; [Fact, LogIfTooSlow] public void CanDeserializeACompleteResponse() { var serializer = new JsonSerializer(); IResponse response = serializer.Deserialize<Response>(json); response.Clients.Should().HaveCount(3); response.Clients[0].Result.Success.Should().BeTrue(); response.Clients[1].Result.Success.Should().BeTrue(); response.Clients[2].Result.Success.Should().BeTrue(); response.Projects.Should().HaveCount(3); response.Projects[0].Result.Success.Should().BeTrue(); response.Projects[1].Result.Success.Should().BeTrue(); response.Projects[2].Result.Success.Should().BeTrue(); response.Tags.Should().HaveCount(3); response.Tags[0].Result.Success.Should().BeTrue(); response.Tags[1].Result.Success.Should().BeTrue(); response.Tags[2].Result.Success.Should().BeTrue(); response.Tasks.Should().HaveCount(3); response.Tasks[0].Result.Success.Should().BeTrue(); response.Tasks[1].Result.Success.Should().BeTrue(); response.Tasks[2].Result.Success.Should().BeTrue(); response.TimeEntries.Should().HaveCount(3); response.TimeEntries[0].Result.Success.Should().BeTrue(); response.TimeEntries[1].Result.Success.Should().BeTrue(); response.TimeEntries[2].Result.Success.Should().BeTrue(); response.Workspaces.Should().HaveCount(2); response.Workspaces[0].Result.Success.Should().BeTrue(); response.Workspaces[1].Result.Success.Should().BeTrue(); response.User.Success.Should().BeTrue(); response.Preferences.Success.Should().BeTrue(); } } }
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs) //#define ProfileAstar //#define UNITY_PRO_PROFILER //Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler. using System.Collections.Generic; using System; using UnityEngine; using Pathfinding; namespace Pathfinding { public class AstarProfiler { public class ProfilePoint { //public DateTime lastRecorded; //public TimeSpan totalTime; public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); public int totalCalls; public long tmpBytes; public long totalBytes; } private static Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>(); private static DateTime startTime = DateTime.UtcNow; public static ProfilePoint[] fastProfiles; public static string[] fastProfileNames; private AstarProfiler() { } [System.Diagnostics.Conditional ("ProfileAstar")] public static void InitializeFastProfile (string[] profileNames) { fastProfileNames = new string[profileNames.Length+2]; Array.Copy (profileNames,fastProfileNames, profileNames.Length); fastProfileNames[fastProfileNames.Length-2] = "__Control1__"; fastProfileNames[fastProfileNames.Length-1] = "__Control2__"; fastProfiles = new ProfilePoint[fastProfileNames.Length]; for (int i=0;i<fastProfiles.Length;i++) fastProfiles[i] = new ProfilePoint(); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartFastProfile(int tag) { //profiles.TryGetValue(tag, out point); fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow; } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndFastProfile(int tag) { /*if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; }*/ ProfilePoint point = fastProfiles[tag]; point.totalCalls++; point.watch.Stop (); //DateTime now = DateTime.UtcNow; //point.totalTime += now - point.lastRecorded; //fastProfiles[tag] = point; } [System.Diagnostics.Conditional ("UNITY_PRO_PROFILER")] public static void EndProfile () { Profiler.EndSample (); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartProfile(string tag) { #if UNITY_PRO_PROFILER Profiler.BeginSample (tag); #else //Console.WriteLine ("Profile Start - " + tag); ProfilePoint point; profiles.TryGetValue(tag, out point); if (point == null) { point = new ProfilePoint(); profiles[tag] = point; } point.tmpBytes = System.GC.GetTotalMemory (false); point.watch.Start(); //point.lastRecorded = DateTime.UtcNow; //Debug.Log ("Starting " + tag); #endif } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndProfile(string tag) { #if !UNITY_PRO_PROFILER if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; } //Console.WriteLine ("Profile End - " + tag); //DateTime now = DateTime.UtcNow; ProfilePoint point = profiles[tag]; //point.totalTime += now - point.lastRecorded; ++point.totalCalls; point.watch.Stop(); point.totalBytes += System.GC.GetTotalMemory (false) - point.tmpBytes; //profiles[tag] = point; //Debug.Log ("Ending " + tag); #else EndProfile (); #endif } [System.Diagnostics.Conditional ("ProfileAstar")] public static void Reset() { profiles.Clear(); startTime = DateTime.UtcNow; if (fastProfiles != null) { for (int i=0;i<fastProfiles.Length;i++) { fastProfiles[i] = new ProfilePoint (); } } } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintFastResults() { StartFastProfile (fastProfiles.Length-2); for (int i=0;i<1000;i++) { StartFastProfile (fastProfiles.Length-1); EndFastProfile (fastProfiles.Length-1); } EndFastProfile (fastProfiles.Length-2); double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0; TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); output.Append ("Name | Total Time | Total Calls | Avg/Call | Bytes"); //foreach(KeyValuePair<string, ProfilePoint> pair in profiles) for (int i=0;i<fastProfiles.Length;i++) { string name = fastProfileNames[i]; ProfilePoint value = fastProfiles[i]; int totalCalls = value.totalCalls; double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls; if (totalCalls < 1) continue; output.Append ("\n").Append(name.PadLeft(10)).Append("| "); output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("| "); output.Append (totalCalls.ToString().PadLeft (10)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10)); /* output.Append("\nProfile"); output.Append(name); output.Append(" took \t"); output.Append(totalTime.ToString("0.0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging \t"); output.Append((totalTime / totalCalls).ToString("0.000")); output.Append(" ms per call"); */ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintResults() { TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); int maxLength = 5; foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { maxLength = Math.Max (pair.Key.Length,maxLength); } output.Append (" Name ".PadRight (maxLength)). Append("|").Append(" Total Time ".PadRight(20)). Append("|").Append(" Total Calls ".PadRight(20)). Append("|").Append(" Avg/Call ".PadRight(20)); foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds; int totalCalls = pair.Value.totalCalls; if (totalCalls < 1) continue; string name = pair.Key; output.Append ("\n").Append(name.PadRight(maxLength)).Append("| "); output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| "); output.Append (totalCalls.ToString().PadRight (20)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20)); output.Append (Pathfinding.AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10)); /*output.Append("\nProfile "); output.Append(pair.Key); output.Append(" took "); output.Append(totalTime.ToString("0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging "); output.Append((totalTime / totalCalls).ToString("0.0")); output.Append(" ms per call");*/ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } } }
//============================================================================= // System : Sandcastle Help File Builder MSBuild Tasks // File : Build1xHelpFile.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 10/05/2008 // Note : Copyright 2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the MSBuild task used to run HHC.EXE which is used to // compile a Help 1 (CHM) help file. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.8.0.0 07/11/2008 EFW Created the code // ============================================================================ using System; using System.Globalization; using System.IO; using System.Text; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.BuildEngine; namespace SandcastleBuilder.Utils.MSBuild { /// <summary> /// This task is used to run HHC.EXE which is used to compile a Help 1 /// (CHM) help file. /// </summary> /// <remarks>Support is provided for wrapping the tool in a call to an /// application such as SBAppLocale.exe to workaround encoding issues with /// the Help 1 compiler.</remarks> public class Build1xHelpFile : ToolTask { #region Private data members //===================================================================== private const string HelpCompilerName = "HHC.EXE"; private string workingFolder, helpCompilerFolder, helpProjectName, localizeApp; private int langId; #endregion #region Properties //===================================================================== /// <summary> /// This read-only property returns the tool name (HHC.EXE or the /// value of <see cref="LocalizeApp" /> if specified). /// </summary> protected override string ToolName { get { if(!String.IsNullOrEmpty(localizeApp)) return localizeApp; return HelpCompilerName; } } /// <summary> /// This is overridden to force all standard error info to be logged /// </summary> protected override MessageImportance StandardErrorLoggingImportance { get { return MessageImportance.High; } } /// <summary> /// This is overridden to force all standard output info to be logged /// </summary> protected override MessageImportance StandardOutputLoggingImportance { get { return MessageImportance.High; } } /// <summary> /// This is used to pass in the working folder where the files are /// located. /// </summary> [Required] public string WorkingFolder { get { return workingFolder; } set { workingFolder = value; } } /// <summary> /// This is used to pass in the path to the help compiler /// </summary> [Required] public string HelpCompilerFolder { get { return helpCompilerFolder; } set { helpCompilerFolder = value; } } /// <summary> /// This is used to pass in the help project filename /// </summary> [Required] public string HelpProjectName { get { return helpProjectName; } set { helpProjectName = value; } } /// <summary> /// This is used to pass in the name of the application to use as the /// localization wrapper. /// </summary> /// <remarks>This is optional. If specified, it will be used to run /// the help compiler to work around encoding issues.</remarks> public string LocalizeApp { get { return localizeApp; } set { localizeApp = value; } } /// <summary> /// This is used to get or set the language ID for the localization /// tool (see cref="LocalizeApp" />). /// </summary> /// <remarks>This is optional. If not specified, it defaults to 1033. /// It is ignored if <see cref="LocalizeApp" /> is not set.</remarks> public int LanguageId { get { return langId; } set { langId = value; } } #endregion #region Method overrides //===================================================================== /// <summary> /// Validate the parameters /// </summary> /// <returns>True if the parameters are valid, false if not</returns> protected override bool ValidateParameters() { if(String.IsNullOrEmpty(helpCompilerFolder)) { Log.LogError(null, "B1X0001", "B1X0001", "SHFB", 0, 0, 0, 0, "A help compiler path must be specified"); return false; } if(String.IsNullOrEmpty(helpProjectName) || !File.Exists(helpProjectName)) { Log.LogError(null, "B1X0002", "B1X0002", "SHFB", 0, 0, 0, 0, "A help project file must be specified and it must exist"); return false; } return true; } /// <summary> /// This returns the full path to the tool /// </summary> /// <returns>The full path to the tool</returns> protected override string GenerateFullPathToTool() { if(!String.IsNullOrEmpty(localizeApp)) return localizeApp; return Path.Combine(helpCompilerFolder, HelpCompilerName); } /// <summary> /// Generate the command line parameters /// </summary> /// <returns>The command line parameters</returns> protected override string GenerateCommandLineCommands() { if(!String.IsNullOrEmpty(localizeApp)) { if(langId == 0) langId = 1033; return String.Format(CultureInfo.InvariantCulture, "{0} \"{1}\" \"{2}\"", langId, Path.Combine(helpCompilerFolder, HelpCompilerName), helpProjectName); } return "\"" + helpProjectName + "\""; } /// <summary> /// This is overridden to set the working folder before executing /// the task and to invert the result returned from the help compiler. /// </summary> /// <returns>True if successful or false on failure</returns> public override bool Execute() { Directory.SetCurrentDirectory(workingFolder); // HHC is backwards and returns zero on failure and non-zero // on success. if(base.Execute() && base.ExitCode == 0 && String.IsNullOrEmpty(localizeApp)) return base.HandleTaskExecutionErrors(); return true; } /// <summary> /// This is overridden to invert the result of the HHC exit code /// </summary> /// <returns>True on success, false on failure. HXCOMP is backwards /// and returns 0 on failures and 1 on success. We invert the result /// to be consistent with other tasks.</returns> protected override bool HandleTaskExecutionErrors() { if(String.IsNullOrEmpty(localizeApp) && base.ExitCode == 1) return true; return base.HandleTaskExecutionErrors(); } #endregion } }
using System; using System.Data; using System.Text; using System.Drawing; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; namespace liquicode.AppTools { public partial class MessageWindow : Form { //-------------------------------------------------------------------- public class MessageWindowParameters { public IWin32Window Owner = null; public string Text = ""; public string Caption = "Message"; public MessageBoxButtons Buttons = MessageBoxButtons.OK; public MessageBoxIcon Icon = MessageBoxIcon.None; public MessageBoxDefaultButton DefaultButton = MessageBoxDefaultButton.Button1; public MessageBoxOptions Options = MessageBoxOptions.ServiceNotification; public Exception Exception = null; public bool GetUserInput = false; public string[] UserChoices = { }; } //-------------------------------------------------------------------- private MessageWindowParameters _Parameters = null; //-------------------------------------------------------------------- public MessageWindow() { InitializeComponent(); return; } //-------------------------------------------------------------------- public DialogResult Show( MessageWindowParameters Parameters ) { this._Parameters = Parameters; // Set Window Title if( Parameters.Caption.Length == 0 ) { if( Parameters.Icon.Equals( MessageBoxIcon.None ) ) { this.Text = "Message"; } else { this.Text = Parameters.Icon.ToString(); } } else { this.Text = Parameters.Caption; } // Set Text string text = Parameters.Text; if( string.IsNullOrEmpty( text ) ) { text = ""; } text = text.Replace( "\r\n", "\n" ); text = text.Replace( "\n", "\r\n" ); this.lblMessage.Text = text; this.txtMessage.Text = text; // Get Client Size Size ClientSize = this.lblMessage.GetPreferredSize( this.lblMessage.Size ); int ButtonWidth = this.cmdOK.Width + this.cmdOK.Margin.Horizontal; int IconHeight = this.picIcon.Size.Height + this.picIcon.Margin.Vertical; if( Parameters.GetUserInput ) { this.pnlUserInput.Visible = true; ClientSize.Height += this.pnlUserInput.Height; if( Parameters.UserChoices.Length == 0 ) { this.txtUserInput.Dock = DockStyle.Fill; this.txtUserInput.Visible = true; this.cboUserInput.Dock = DockStyle.None; this.cboUserInput.Visible = false; } else { this.txtUserInput.Dock = DockStyle.None; this.txtUserInput.Visible = false; this.cboUserInput.Dock = DockStyle.Fill; this.cboUserInput.Visible = true; this.cboUserInput.Items.AddRange( Parameters.UserChoices ); } } ClientSize.Height += this.CommandPanel.Height + this.CommandPanel.Margin.Vertical; ClientSize.Height += 50; // Fudge factor. // Get minimum size. int min_width = (3 * ButtonWidth); if( Parameters.Icon == MessageBoxIcon.None ) { this.picIcon.Visible = false; } else { this.picIcon.Visible = true; min_width += this.picIcon.Width + this.picIcon.Margin.Horizontal; } if( ClientSize.Width < min_width ) { ClientSize.Width = min_width; } // Set Window Size int max_width = (int)(Screen.PrimaryScreen.Bounds.Width * 0.5); int max_height = (int)(Screen.PrimaryScreen.Bounds.Height * 0.75); Size WindowSize = this.SizeFromClientSize( ClientSize ); if( WindowSize.Width > max_width ) { WindowSize.Width = max_width; } if( WindowSize.Height > max_height ) { WindowSize.Height = max_height; } this.Size = WindowSize; // Set Buttons int X = this.CommandPanel.Width; int Y = Convert.ToInt32( (this.CommandPanel.Height / 2) - (this.cmdOK.Height / 2) ); switch( Parameters.Buttons ) { case MessageBoxButtons.OK: X -= ButtonWidth; this.cmdOK.Location = new Point( X, Y ); this.cmdOK.Visible = true; this.AcceptButton = this.cmdOK; break; case MessageBoxButtons.OKCancel: X -= ButtonWidth; this.cmdCancel.Location = new Point( X, Y ); this.cmdCancel.Visible = true; X -= ButtonWidth; this.cmdOK.Location = new Point( X, Y ); this.cmdOK.Visible = true; this.AcceptButton = this.cmdOK; this.CancelButton = this.cmdCancel; break; case MessageBoxButtons.AbortRetryIgnore: X -= ButtonWidth; this.cmdIgnore.Location = new Point( X, Y ); this.cmdIgnore.Visible = true; X -= ButtonWidth; this.cmdRetry.Location = new Point( X, Y ); this.cmdRetry.Visible = true; X -= ButtonWidth; this.cmdAbort.Location = new Point( X, Y ); this.cmdAbort.Visible = true; if( Parameters.DefaultButton == MessageBoxDefaultButton.Button1 ) { this.AcceptButton = this.cmdAbort; this.CancelButton = this.cmdIgnore; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button2 ) { this.AcceptButton = this.cmdRetry; this.CancelButton = this.cmdIgnore; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button3 ) { this.AcceptButton = this.cmdIgnore; } break; case MessageBoxButtons.YesNoCancel: X -= ButtonWidth; this.cmdCancel.Location = new Point( X, Y ); this.cmdCancel.Visible = true; X -= ButtonWidth; this.cmdNo.Location = new Point( X, Y ); this.cmdNo.Visible = true; X -= ButtonWidth; this.cmdYes.Location = new Point( X, Y ); this.cmdYes.Visible = true; if( Parameters.DefaultButton == MessageBoxDefaultButton.Button1 ) { this.AcceptButton = this.cmdYes; this.CancelButton = this.cmdCancel; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button2 ) { this.AcceptButton = this.cmdNo; this.CancelButton = this.cmdCancel; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button3 ) { this.AcceptButton = this.cmdCancel; } break; case MessageBoxButtons.YesNo: X -= ButtonWidth; this.cmdNo.Location = new Point( X, Y ); this.cmdNo.Visible = true; X -= ButtonWidth; this.cmdYes.Location = new Point( X, Y ); this.cmdYes.Visible = true; if( Parameters.DefaultButton == MessageBoxDefaultButton.Button1 ) { this.AcceptButton = this.cmdYes; this.CancelButton = this.cmdNo; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button2 ) { this.AcceptButton = this.cmdNo; this.CancelButton = this.cmdYes; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button3 ) { this.AcceptButton = this.cmdYes; this.CancelButton = this.cmdNo; } break; case MessageBoxButtons.RetryCancel: X -= ButtonWidth; this.cmdCancel.Location = new Point( X, Y ); this.cmdCancel.Visible = true; X -= ButtonWidth; this.cmdRetry.Location = new Point( X, Y ); this.cmdRetry.Visible = true; if( Parameters.DefaultButton == MessageBoxDefaultButton.Button1 ) { this.AcceptButton = this.cmdRetry; this.CancelButton = this.cmdCancel; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button2 ) { this.AcceptButton = this.cmdCancel; this.CancelButton = this.cmdRetry; } else if( Parameters.DefaultButton == MessageBoxDefaultButton.Button3 ) { this.AcceptButton = this.cmdRetry; this.CancelButton = this.cmdCancel; } break; } if( Parameters.Exception != null ) { X -= ButtonWidth; this.cmdMoreInfo.Location = new Point( X, Y ); this.cmdMoreInfo.Visible = true; } // Set Icon System.IO.MemoryStream ms = null; switch( Parameters.Icon ) { case MessageBoxIcon.None: // 0 break; case MessageBoxIcon.Error: // 16 ms = new System.IO.MemoryStream( System.Convert.FromBase64String( this.lblIconError.Text ) ); break; case MessageBoxIcon.Question: // 32 ms = new System.IO.MemoryStream( System.Convert.FromBase64String( this.lblIconQuestion.Text ) ); break; case MessageBoxIcon.Exclamation: // 48 ms = new System.IO.MemoryStream( System.Convert.FromBase64String( this.lblIconWarning.Text ) ); break; case MessageBoxIcon.Asterisk: // 64 ms = new System.IO.MemoryStream( System.Convert.FromBase64String( this.lblIconInformation.Text ) ); break; } if( ms != null ) { try { this.picIcon.Image = Image.FromStream( ms ); } catch( Exception ) { } } // Set window icon. if( Parameters.Owner != null ) { try { Form form = (Form)Parameters.Owner; this.Icon = form.Icon; } catch { } } // Show Window DialogResult result = DialogResult.Cancel; try { result = this.ShowDialog( Parameters.Owner ); } catch { } //catch( Exception exception ) //{ // SystemLog.LogError( "Exception during MessageWindow.ShowDialog(). Message text = '" + Parameters.Text + "'.", exception ); //} return result; } //-------------------------------------------------------------------- public static DialogResult ShowMessage( IWin32Window Owner, string Text ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Text = Text; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); return result; } //-------------------------------------------------------------------- public static DialogResult ShowInformation( IWin32Window Owner, string Text ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Text = Text; Parameters.Icon = MessageBoxIcon.Information; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); return result; } //-------------------------------------------------------------------- public static DialogResult ShowQuestion( IWin32Window Owner, string Text, MessageBoxButtons Buttons ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Text = Text; Parameters.Buttons = Buttons; Parameters.Icon = MessageBoxIcon.Question; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); return result; } //-------------------------------------------------------------------- public static string GetUserInput( IWin32Window Owner, string Prompt, string DefaultValue ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Caption = "User Input"; Parameters.Text = Prompt; Parameters.Buttons = MessageBoxButtons.OKCancel; Parameters.Icon = MessageBoxIcon.Question; Parameters.GetUserInput = true; MessageWindow frm = new MessageWindow(); frm.txtUserInput.Text = DefaultValue; DialogResult result = frm.Show( Parameters ); if( result == DialogResult.Cancel ) { return ""; } return frm.txtUserInput.Text; } //-------------------------------------------------------------------- public static string GetUserInput( IWin32Window Owner, string Prompt, string[] Choices ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Caption = "User Input"; Parameters.Text = Prompt; Parameters.Buttons = MessageBoxButtons.OKCancel; Parameters.Icon = MessageBoxIcon.Question; Parameters.GetUserInput = true; Parameters.UserChoices = Choices; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); if( result == DialogResult.Cancel ) { return ""; } if( frm.cboUserInput.SelectedItem == null ) { return ""; } string value = frm.cboUserInput.SelectedItem.ToString(); return value; } //-------------------------------------------------------------------- public static DialogResult ShowError( IWin32Window Owner, Exception Exception ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = Owner; Parameters.Text = Exception.Message; Parameters.Icon = MessageBoxIcon.Error; Parameters.Exception = Exception; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); return result; } //-------------------------------------------------------------------- public static DialogResult ShowError( IWin32Window Owner, string Text, Exception Exception ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Text = Text; Parameters.Owner = Owner; if( Exception != null ) { Parameters.Text += "\r\n" + Exception.Message; } Parameters.Icon = MessageBoxIcon.Error; Parameters.Exception = Exception; MessageWindow frm = new MessageWindow(); DialogResult result = frm.Show( Parameters ); return result; } //-------------------------------------------------------------------- public static DialogResult ShowError( IWin32Window Owner, string Text ) { return ShowError( Owner, Text, null ); } //--------------------------------------------------------------------- public static string Exception2String( System.Exception Exception, bool IncludeStackTrace ) { if( Exception == null ) { return ""; } System.Text.StringBuilder builder = new System.Text.StringBuilder(); int i = 0; Exception ex = Exception; while( ex != null ) { i++; builder.AppendLine( string.Format( "Message {0}: {1}\n", i.ToString( "000" ), ex.Message ) ); ex = ex.InnerException; } if( IncludeStackTrace ) { builder.AppendLine( "---------------------------------------------------------------------" ); builder.AppendLine( "Stack Trace:" ); builder.AppendLine( Exception.StackTrace ); } return builder.ToString(); } public static string Exception2String( System.Exception Exception ) { return Exception2String( Exception, true ); } //-------------------------------------------------------------------- private void cmdOK_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.OK; this.Close(); return; } private void cmdNo_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.No; this.Close(); return; } private void cmdYes_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.Yes; this.Close(); return; } private void cmdIgnore_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.Ignore; this.Close(); return; } private void cmdRetry_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.Retry; this.Close(); return; } private void cmdAbort_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.Abort; this.Close(); return; } private void cmdCancel_Click( System.Object sender, System.EventArgs e ) { this.DialogResult = DialogResult.Cancel; this.Close(); return; } private void cmdMoreInfo_Click( object sender, EventArgs e ) { MessageWindowParameters Parameters = new MessageWindowParameters(); Parameters.Owner = this; string exception_text = Exception2String( this._Parameters.Exception ); Parameters.Text = string.Format( "{0}\r\n{1}", this._Parameters.Text, exception_text ); Parameters.Icon = MessageBoxIcon.Error; MessageWindow frm = new MessageWindow(); frm.Show( Parameters ); return; } } }
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Orleans; using Orleans.Configuration; using Orleans.Internal; using Orleans.Runtime; using Orleans.Runtime.Scheduler; using Orleans.Runtime.TestHooks; using Orleans.Statistics; using TestExtensions; using UnitTests.Grains; using UnitTests.TesterInternal; using Xunit; using Xunit.Abstractions; namespace UnitTests.SchedulerTests { public class OrleansTaskSchedulerAdvancedTests_Set2 : IDisposable { private static readonly object Lockable = new object(); private static readonly int WaitFactor = Debugger.IsAttached ? 100 : 1; private static readonly SafeRandom Random = new SafeRandom(); private readonly ITestOutputHelper output; private readonly OrleansTaskScheduler masterScheduler; private readonly UnitTestSchedulingContext context; private readonly IHostEnvironmentStatistics performanceMetrics; private readonly ILoggerFactory loggerFactory; public OrleansTaskSchedulerAdvancedTests_Set2(ITestOutputHelper output) { this.output = output; this.loggerFactory = OrleansTaskSchedulerBasicTests.InitSchedulerLogging(); this.context = new UnitTestSchedulingContext(); this.performanceMetrics = new TestHooksHostEnvironmentStatistics(); this.masterScheduler = TestInternalHelper.InitializeSchedulerForTesting(this.context, this.loggerFactory); } public void Dispose() { this.masterScheduler.Stop(); this.loggerFactory.Dispose(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_SimpleFifoTest() { // This is not a great test because there's a 50/50 shot that it will work even if the scheduling // is completely and thoroughly broken and both closures are executed "simultaneously" TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; int n = 0; // ReSharper disable AccessToModifiedClosure Task task1 = new Task(() => { Thread.Sleep(1000); n = n + 5; }); Task task2 = new Task(() => { n = n * 3; }); // ReSharper restore AccessToModifiedClosure task1.Start(scheduler); task2.Start(scheduler); // Pause to let things run Thread.Sleep(1500); // N should be 15, because the two tasks should execute in order Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(15, n); // "Work items executed out of order" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_NewTask_ContinueWith_Wrapped() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; Task<Task> wrapped = new Task<Task>(() => { this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Task t0 = new Task(() => { this.output.WriteLine("#1 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #1" }); Task t1 = t0.ContinueWith(task => { Assert.False(task.IsFaulted, "Task #1 Faulted=" + task.Exception); this.output.WriteLine("#2 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current #2" }); t0.Start(scheduler); return t1; }); wrapped.Start(scheduler); bool ok = wrapped.Unwrap().Wait(TimeSpan.FromSeconds(2)); Assert.True(ok, "Finished OK"); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public void ActivationSched_SubTaskExecutionSequencing() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; LogContext("Main-task " + Task.CurrentId); int n = 0; Action action = () => { LogContext("WorkItem-task " + Task.CurrentId); for (int i = 0; i < 10; i++) { int id = -1; Task.Factory.StartNew(() => { id = Task.CurrentId.HasValue ? (int)Task.CurrentId : -1; // ReSharper disable AccessToModifiedClosure LogContext("Sub-task " + id + " n=" + n); int k = n; this.output.WriteLine("Sub-task " + id + " sleeping"); Thread.Sleep(100); this.output.WriteLine("Sub-task " + id + " awake"); n = k + 1; // ReSharper restore AccessToModifiedClosure }) .ContinueWith(tsk => { LogContext("Sub-task " + id + "-ContinueWith"); this.output.WriteLine("Sub-task " + id + " Done"); }); } }; Task t = new Task(action); t.Start(scheduler); // Pause to let things run this.output.WriteLine("Main-task sleeping"); Thread.Sleep(TimeSpan.FromSeconds(2)); this.output.WriteLine("Main-task awake"); // N should be 10, because all tasks should execute serially Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(10, n); // "Work items executed concurrently" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_ContinueWith_1_Test() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; var result = new TaskCompletionSource<bool>(); int n = 0; Task wrapper = new Task(() => { // ReSharper disable AccessToModifiedClosure Task task1 = Task.Factory.StartNew(() => { this.output.WriteLine("===> 1a"); Thread.Sleep(1000); n = n + 3; this.output.WriteLine("===> 1b"); }); Task task2 = task1.ContinueWith(task => { n = n * 5; this.output.WriteLine("===> 2"); }); Task task3 = task2.ContinueWith(task => { n = n / 5; this.output.WriteLine("===> 3"); }); Task task4 = task3.ContinueWith(task => { n = n - 2; this.output.WriteLine("===> 4"); result.SetResult(true); }); // ReSharper restore AccessToModifiedClosure task4.ContinueWith(task => { this.output.WriteLine("Done Faulted={0}", task.IsFaulted); Assert.False(task.IsFaulted, "Faulted with Exception=" + task.Exception); }); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(2); try { await result.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.True(n != 0, "Work items did not get executed"); Assert.Equal(1, n); // "Work items executed out of order" } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); // "TaskScheduler.Current=" + TaskScheduler.Current pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.True(task1.IsCompleted || task2.IsCompleted, "Task-1 Status = " + task1.Status + " Task-2 Status = " + task2.Status); pause2.Set(); task2.Ignore(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny_Timeout() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.NotNull(join); await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status); pause1.Set(); task1.Ignore(); pause2.Set(); task2.Ignore(); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_WhenAny_Busy_Timeout() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; var pause1 = new TaskCompletionSource<bool>(); var pause2 = new TaskCompletionSource<bool>(); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-1 Started"); Assert.Equal(scheduler, TaskScheduler.Current); int num1 = 1; while (!pause1.Task.Result) // Infinite busy loop { num1 = Random.Next(); } this.output.WriteLine("Task-1 Done"); return num1; }); task2 = Task<int>.Factory.StartNew(() => { this.output.WriteLine("Task-2 Started"); Assert.Equal(scheduler, TaskScheduler.Current); int num2 = 2; while (!pause2.Task.Result) // Infinite busy loop { num2 = Random.Next(); } this.output.WriteLine("Task-2 Done"); return num2; }); join = Task.WhenAny(task1, task2, Task.Delay(TimeSpan.FromSeconds(2))); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join.Status); Assert.False(task1.IsFaulted, "Task-1 Faulted " + task1.Exception); Assert.False(task1.IsCompleted, "Task-1 Status " + task1.Status); Assert.False(task2.IsFaulted, "Task-2 Faulted " + task2.Exception); Assert.False(task2.IsCompleted, "Task-2 Status " + task2.Status); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Run() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task.Run(() => { this.output.WriteLine("Task-1 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task.Run(() => { this.output.WriteLine("Task-2 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAll(task1, task2).ContinueWith(t => { this.output.WriteLine("Join Started"); if (t.IsFaulted) throw t.Exception; Assert.Equal(scheduler, TaskScheduler.Current); this.output.WriteLine("Join Done"); }); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); pause2.Set(); Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join); Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1); Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Run_Delay() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; ManualResetEvent pause1 = new ManualResetEvent(false); ManualResetEvent pause2 = new ManualResetEvent(false); var finish = new TaskCompletionSource<bool>(); Task<int> task1 = null; Task<int> task2 = null; Task join = null; Task wrapper = new Task(() => { task1 = Task.Run(() => { this.output.WriteLine("Task-1 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); Task.Delay(1); Assert.NotEqual(scheduler, TaskScheduler.Current); pause1.WaitOne(); this.output.WriteLine("Task-1 Done"); return 1; }); task2 = Task.Run(() => { this.output.WriteLine("Task-2 Started"); Assert.NotEqual(scheduler, TaskScheduler.Current); Task.Delay(1); Assert.NotEqual(scheduler, TaskScheduler.Current); pause2.WaitOne(); this.output.WriteLine("Task-2 Done"); return 2; }); join = Task.WhenAll(task1, task2).ContinueWith(t => { this.output.WriteLine("Join Started"); if (t.IsFaulted) throw t.Exception; Assert.Equal(scheduler, TaskScheduler.Current); this.output.WriteLine("Join Done"); }); finish.SetResult(true); }); wrapper.Start(scheduler); var timeoutLimit = TimeSpan.FromSeconds(1); try { await finish.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } pause1.Set(); pause2.Set(); Assert.NotNull(join); // Joined promise assigned await join; Assert.True(join.IsCompleted && !join.IsFaulted, "Join Status " + join); Assert.True(task1.IsCompleted && !task1.IsFaulted, "Task-1 Status " + task1); Assert.True(task2.IsCompleted && !task2.IsFaulted, "Task-2 Status " + task2); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Task_Delay() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; Task wrapper = new Task(async () => { Assert.Equal(scheduler, TaskScheduler.Current); await DoDelay(1); Assert.Equal(scheduler, TaskScheduler.Current); await DoDelay(2); Assert.Equal(scheduler, TaskScheduler.Current); }); wrapper.Start(scheduler); await wrapper; } private async Task DoDelay(int i) { try { this.output.WriteLine("Before Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current); await Task.Delay(1); this.output.WriteLine("After Task.Delay #{0} TaskScheduler.Current={1}", i, TaskScheduler.Current); } catch (ObjectDisposedException) { // Ignore any problems with ObjectDisposedException if console output stream has already been closed } } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Turn_Execution_Order_Loop() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; const int NumChains = 100; const int ChainLength = 3; // Can we add a unit test that basicaly checks that any turn is indeed run till completion before any other turn? // For example, you have a long running main turn and in the middle it spawns a lot of short CWs (on Done promise) and StartNew. // You test that no CW/StartNew runs until the main turn is fully done. And run in stress. var resultHandles = new TaskCompletionSource<bool>[NumChains]; Task[] taskChains = new Task[NumChains]; Task[] taskChainEnds = new Task[NumChains]; bool[] executingChain = new bool[NumChains]; int[] stageComplete = new int[NumChains]; int executingGlobal = -1; for (int i = 0; i < NumChains; i++) { int chainNum = i; // Capture int sleepTime = TestConstants.random.Next(100); resultHandles[i] = new TaskCompletionSource<bool>(); taskChains[i] = new Task(() => { const int taskNum = 0; try { Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum); executingGlobal = chainNum; executingChain[chainNum] = true; Thread.Sleep(sleepTime); } finally { stageComplete[chainNum] = taskNum; executingChain[chainNum] = false; executingGlobal = -1; } }); Task task = taskChains[i]; for (int j = 1; j < ChainLength; j++) { int taskNum = j; // Capture task = task.ContinueWith(t => { if (t.IsFaulted) throw t.Exception; this.output.WriteLine("Inside Chain {0} Task {1}", chainNum, taskNum); try { Assert.Equal(-1, executingGlobal); // "Detected unexpected other execution in chain " + chainNum + " Task " + taskNum Assert.False(executingChain[chainNum], "Detected unexpected other execution on chain " + chainNum + " Task " + taskNum); Assert.Equal(taskNum - 1, stageComplete[chainNum]); // "Detected unexpected execution stage on chain " + chainNum + " Task " + taskNum executingGlobal = chainNum; executingChain[chainNum] = true; Thread.Sleep(sleepTime); } finally { stageComplete[chainNum] = taskNum; executingChain[chainNum] = false; executingGlobal = -1; } }, scheduler); } taskChainEnds[chainNum] = task.ContinueWith(t => { if (t.IsFaulted) throw t.Exception; this.output.WriteLine("Inside Chain {0} Final Task", chainNum); resultHandles[chainNum].SetResult(true); }, scheduler); } for (int i = 0; i < NumChains; i++) { taskChains[i].Start(scheduler); } for (int i = 0; i < NumChains; i++) { TimeSpan waitCheckTime = TimeSpan.FromMilliseconds(150 * ChainLength * NumChains * WaitFactor); try { await resultHandles[i].Task.WithTimeout(waitCheckTime); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + waitCheckTime); } bool ok = resultHandles[i].Task.Result; try { // since resultHandle being complete doesn't directly imply that the final chain was completed (there's a chance for a race condition), give a small chance for it to complete. await taskChainEnds[i].WithTimeout(TimeSpan.FromMilliseconds(10)); } catch (TimeoutException) { Assert.True(false, $"Task chain end {i} should complete very shortly after after its resultHandle"); } Assert.True(taskChainEnds[i].IsCompleted, "Task chain " + i + " should be completed"); Assert.False(taskChainEnds[i].IsFaulted, "Task chain " + i + " should not be Faulted: " + taskChainEnds[i].Exception); Assert.Equal(ChainLength - 1, stageComplete[i]); // "Task chain " + i + " should have completed all stages" Assert.True(ok, "Successfully waited for ResultHandle for Task chain " + i); } } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Test1() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; await Run_ActivationSched_Test1(scheduler, false); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task ActivationSched_Test1_Bounce() { TaskScheduler scheduler = this.masterScheduler.GetWorkItemGroup(this.context).TaskScheduler; await Run_ActivationSched_Test1(scheduler, true); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task OrleansSched_Test1() { UnitTestSchedulingContext context = new UnitTestSchedulingContext(); OrleansTaskScheduler orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.loggerFactory); ActivationTaskScheduler scheduler = orleansTaskScheduler.GetWorkItemGroup(context).TaskScheduler; await Run_ActivationSched_Test1(scheduler, false); } [Fact, TestCategory("Functional"), TestCategory("Scheduler")] public async Task OrleansSched_Test1_Bounce() { UnitTestSchedulingContext context = new UnitTestSchedulingContext(); OrleansTaskScheduler orleansTaskScheduler = TestInternalHelper.InitializeSchedulerForTesting(context, this.loggerFactory); ActivationTaskScheduler scheduler = orleansTaskScheduler.GetWorkItemGroup(context).TaskScheduler; await Run_ActivationSched_Test1(scheduler, true); } internal async Task Run_ActivationSched_Test1(TaskScheduler scheduler, bool bounceToThreadPool) { var grainId = GrainId.GetGrainId(0, Guid.NewGuid()); var silo = new MockSiloDetails { SiloAddress = SiloAddressUtils.NewLocalSiloAddress(23) }; var grain = NonReentrentStressGrainWithoutState.Create(grainId, new GrainRuntime(Options.Create(new ClusterOptions()), silo, null, null, null, null, null, NullLoggerFactory.Instance)); await Task.Factory.StartNew(() => grain.OnActivateAsync(), CancellationToken.None, TaskCreationOptions.None, scheduler).Unwrap(); Task wrapped = null; var wrapperDone = new TaskCompletionSource<bool>(); var wrappedDone = new TaskCompletionSource<bool>(); Task<Task> wrapper = new Task<Task>(() => { this.output.WriteLine("#0 - new Task - SynchronizationContext.Current={0} TaskScheduler.Current={1}", SynchronizationContext.Current, TaskScheduler.Current); Task t1 = grain.Test1(); Action wrappedDoneAction = () => { wrappedDone.SetResult(true); }; if (bounceToThreadPool) { wrapped = t1.ContinueWith(_ => wrappedDoneAction(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } else { wrapped = t1.ContinueWith(_ => wrappedDoneAction()); } wrapperDone.SetResult(true); return wrapped; }); wrapper.Start(scheduler); await wrapper; var timeoutLimit = TimeSpan.FromSeconds(1); try { await wrapperDone.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } bool done = wrapperDone.Task.Result; Assert.True(done, "Wrapper Task finished"); Assert.True(wrapper.IsCompleted, "Wrapper Task completed"); //done = wrapped.Wait(TimeSpan.FromSeconds(12)); //Assert.True(done, "Wrapped Task not timeout"); await wrapped; try { await wrappedDone.Task.WithTimeout(timeoutLimit); } catch (TimeoutException) { Assert.True(false, "Result did not arrive before timeout " + timeoutLimit); } done = wrappedDone.Task.Result; Assert.True(done, "Wrapped Task should be finished"); Assert.True(wrapped.IsCompleted, "Wrapped Task completed"); } private void LogContext(string what) { lock (Lockable) { this.output.WriteLine( "{0}\n" + " TaskScheduler.Current={1}\n" + " Task.Factory.Scheduler={2}\n" + " SynchronizationContext.Current={3}", what, (TaskScheduler.Current == null ? "null" : TaskScheduler.Current.ToString()), (Task.Factory.Scheduler == null ? "null" : Task.Factory.Scheduler.ToString()), (SynchronizationContext.Current == null ? "null" : SynchronizationContext.Current.ToString()) ); //var st = new StackTrace(); //output.WriteLine(st.ToString()); } } private class MockSiloDetails : ILocalSiloDetails { public string DnsHostName { get; } public SiloAddress SiloAddress { get; set; } public SiloAddress GatewayAddress { get; } public string Name { get; set; } = Guid.NewGuid().ToString(); public string ClusterId { get; } } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2014 Oleg Shilo 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 IO = System.IO; using System.Linq; using System.Collections.Generic; using System; using System.Xml.Linq; namespace WixSharp { /// <summary> /// Defines file to be installed. /// </summary> /// ///<example>The following is an example of installing <c>MyApp.exe</c> file. ///<code> /// var project = /// new Project("My Product", /// /// new Dir(@"%ProgramFiles%\My Company\My Product", /// /// new File(binaries, @"AppFiles\MyApp.exe", /// new WixSharp.Shortcut("MyApp", @"%ProgramMenu%\My Company\My Product"), /// new WixSharp.Shortcut("MyApp", @"%Desktop%")), /// /// ... /// /// Compiler.BuildMsi(project); /// </code> /// </example> public partial class File : WixEntity { /// <summary> /// Returns a <see cref="T:System.String"/> that represents the <see cref="File"/>. /// <para>This property is designed to produce a friendlier string representation of the <see cref="File"/> /// for debugging purposes.</para> /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the <see cref="File"/>. /// </returns> public new string ToString() { return IO.Path.GetFileName(Name) + "; " + Name; } /// <summary> /// Initializes a new instance of the <see cref="File"/> class. /// </summary> public File() { } /// <summary> /// Creates instance of the <see cref="File"></see> class with properties initialized with specified parameters. /// </summary> /// <param name="feature"><see cref="Feature"></see> the file should be included in.</param> /// <param name="sourcePath">Relative path to the file to be taken for building the MSI.</param> /// <param name="items">Optional <see cref="FileShortcut"/> parameters defining shortcuts to the file to be created /// during the installation.</param> public File(Feature feature, string sourcePath, params WixEntity[] items) { Name = sourcePath; Feature = feature; AddItems(items); } /// <summary> /// Creates instance of the <see cref="File"></see> class with properties initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="File"/> instance.</param> /// <param name="feature"><see cref="Feature"></see> the file should be included in.</param> /// <param name="sourcePath">Relative path to the file to be taken for building the MSI.</param> /// <param name="items">Optional <see cref="FileShortcut"/> parameters defining shortcuts to the file to be created /// during the installation.</param> public File(Id id, Feature feature, string sourcePath, params WixEntity[] items) { Id = id.Value; Name = sourcePath; Feature = feature; AddItems(items); } /// <summary> /// Creates instance of the <see cref="File"></see> class with properties initialized with specified parameters. /// </summary> /// <param name="sourcePath">Relative path to the file to be taken for building the MSI.</param> /// <param name="items">Optional <see cref="FileShortcut"/> parameters defining shortcuts to the file to be created /// during the installation.</param> public File(string sourcePath, params WixEntity[] items) { Name = sourcePath; AddItems(items); } /// <summary> /// Creates instance of the <see cref="File"></see> class with properties initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="File"/> instance.</param> /// <param name="sourcePath">Relative path to the file to be taken for building the MSI.</param> /// <param name="items">Optional <see cref="FileShortcut"/> parameters defining shortcuts to the file to be created /// during the installation.</param> public File(Id id, string sourcePath, params WixEntity[] items) { Id = id.Value; Name = sourcePath; AddItems(items); } void AddItems(WixEntity[] items) { Shortcuts = items.OfType<FileShortcut>().ToArray(); Associations = items.OfType<FileAssociation>().ToArray(); IISVirtualDirs = items.OfType<IISVirtualDir>().ToArray(); ServiceInstaller = items.OfType<ServiceInstaller>().FirstOrDefault(); DriverInstaller = items.OfType<DriverInstaller>().FirstOrDefault(); Permissions = items.OfType<FilePermission>().ToArray(); var firstUnExpectedItem = items.Except(Shortcuts) .Except(Associations) .Except(IISVirtualDirs) .Except(Permissions) .Where(x => x != ServiceInstaller) .Where(x => x != DriverInstaller) .ToArray(); if (firstUnExpectedItem.Any()) throw new ApplicationException("{0} is unexpected. Only {1}, {2}, {3}, {4}, and {5} items can be added to {6}".FormatInline( firstUnExpectedItem.First().GetType(), typeof(FileShortcut), typeof(FileAssociation), typeof(ServiceInstaller), typeof(FilePermission), typeof(DriverInstaller), this.GetType())); } /// <summary> /// Collection of the <see cref="FileAssociation"/>s associated with the file. /// </summary> public FileAssociation[] Associations = new FileAssociation[0]; /// <summary> /// The service installer associated with the file. /// Set this field to the properly initialized instance of <see cref="ServiceInstaller"/> if the file is a windows service module. /// </summary> public ServiceInstaller ServiceInstaller = null; /// <summary> /// The driver installer associated with the file. Set this field to the properly initialized /// instance of <see cref="DriverInstaller"/> if the file is a windows driver. /// </summary> public DriverInstaller DriverInstaller = null; /// <summary> /// Collection of the contained <see cref="IISVirtualDir"/>s. /// </summary> public IISVirtualDir[] IISVirtualDirs = new IISVirtualDir[0]; /// <summary> /// Collection of the <see cref="Shortcut"/>s associated with the file. /// </summary> public FileShortcut[] Shortcuts = new FileShortcut[0]; /// <summary> /// <see cref="Feature"></see> the file belongs to. /// </summary> public Feature Feature; /// <summary> /// Defines the installation <see cref="Condition"/>, which is to be checked during the installation to /// determine if the file should be installed on the target system. /// </summary> public Condition Condition; /// <summary> /// COllection of <see cref="T:WixSharp.FilePermission" /> to be applied to the file. /// </summary> public FilePermission[] Permissions = new FilePermission[0]; /// <summary> /// Gets or sets the NeverOverwrite attribute of the associated WiX component. /// <para>If this attribute is set to 'true', the installer does not install or reinstall the component /// if a key path file for the component already exists. </para> /// </summary> /// <value> /// The never overwrite. /// </value> public bool? NeverOverwrite { get { var value = GetAttributeDefinition("Component:NeverOverwrite"); if (value == null) return null; else return (value == "yes"); } set { if (value.HasValue) SetAttributeDefinition("Component:NeverOverwrite", value.Value.ToYesNo()); else SetAttributeDefinition("Component:NeverOverwrite", null); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using NUnit.Framework; using StructureMap.Pipeline; using System.Linq; namespace StructureMap.Testing.Graph { [TestFixture] public class TestExplicitArguments { #region Setup/Teardown [SetUp] public void SetUp() { ObjectFactory.Initialize(x => { }); } #endregion public interface IExplicitTarget { } public class RedTarget : IExplicitTarget { } public class GreenTarget : IExplicitTarget { } public class ExplicitTarget : IExplicitTarget { private readonly string _name; private readonly IProvider _provider; public ExplicitTarget(string name, IProvider provider) { _name = name; _provider = provider; } public string Name { get { return _name; } } public IProvider Provider { get { return _provider; } } } public interface IProvider { } public class RedProvider : IProvider { } public class BlueProvider : IProvider { } public class ClassWithNoArgs { public Address TheAddress { get; set; } } public class Address { } public class SpecialInstance : Instance { protected override string getDescription() { return string.Empty; } protected override object build(Type pluginType, BuildSession session) { return new ClassWithNoArgs { TheAddress = (Address) session.GetInstance(typeof (Address)) }; } } public class SpecialNode : Node { } [Test] public void can_build_a_concrete_class_with_constructor_args_that_is_not_previously_registered() { var container = new Container(); container.With("name").EqualTo("Jeremy").GetInstance<ConcreteThatNeedsString>() .Name.ShouldEqual("Jeremy"); } [Test] public void can_build_a_concrete_class_with_constructor_args_that_is_not_previously_registered_2() { var container = new Container(); container.With(x => { x.With("name").EqualTo("Jeremy"); }).GetInstance<ConcreteThatNeedsString>().Name. ShouldEqual("Jeremy"); } [Test] public void can_build_a_concrete_type_from_explicit_args_passed_into_a_named_instance() { var container = new Container(x => { x.For<ColorWithLump>().AddInstances(o => { o.Type<ColorWithLump>().Ctor<string>("color").Is("red").Named("red"); o.Type<ColorWithLump>().Ctor<string>("color").Is("green").Named("green"); o.Type<ColorWithLump>().Ctor<string>("color").Is("blue").Named("blue"); }); }); var lump = new Lump(); var colorLump = container.With(lump).GetInstance<ColorWithLump>("red"); colorLump.Lump.ShouldBeTheSameAs(lump); colorLump.Color.ShouldEqual("red"); } [Test] public void Example() { IContainer container = new Container(); var theTrade = new Trade(); var view = container.With(theTrade).GetInstance<TradeView>(); view.Trade.ShouldBeTheSameAs(theTrade); } [Test] public void Explicit_services_are_used_throughout_the_object_graph() { var theTrade = new Trade(); IContainer container = new Container(r => { r.For<IView>().Use<TradeView>(); r.For<Node>().Use<TradeNode>(); }); var command = container.With(theTrade).GetInstance<Command>(); command.Trade.ShouldBeTheSameAs(theTrade); command.Node.IsType<TradeNode>().Trade.ShouldBeTheSameAs(theTrade); command.View.IsType<TradeView>().Trade.ShouldBeTheSameAs(theTrade); } [Test] public void ExplicitArguments_can_return_child_by_name() { var theNode = new Node(); var container = new Container(x => { x.For<IView>().Use<View>(); }); container.With("node").EqualTo(theNode).GetInstance<Command>().Node.ShouldBeTheSameAs(theNode); } [Test] public void Fill_in_argument_by_name() { var container = new Container(x => { x.For<IView>().Use<View>(); }); var theNode = new Node(); var theTrade = new Trade(); var command = container .With("node").EqualTo(theNode) .With(theTrade) .GetInstance<Command>(); command.View.ShouldBeOfType<View>(); theNode.ShouldBeTheSameAs(command.Node); theTrade.ShouldBeTheSameAs(command.Trade); } [Test] public void Fill_in_argument_by_type() { var container = new Container(x => { x.For<IView>().Use<View>(); }); var theNode = new SpecialNode(); var theTrade = new Trade(); var command = container .With(typeof (Node), theNode) .With(theTrade) .GetInstance<Command>(); command.View.ShouldBeOfType<View>(); theNode.ShouldBeTheSameAs(command.Node); theTrade.ShouldBeTheSameAs(command.Trade); } [Test] public void Fill_in_argument_by_type_with_ObjectFactory() { ObjectFactory.Initialize(x => { x.For<IView>().Use<View>(); }); var theNode = new SpecialNode(); var theTrade = new Trade(); var command = ObjectFactory.Container .With(typeof (Node), theNode) .With(theTrade) .GetInstance<Command>(); command.View.ShouldBeOfType<View>(); theNode.ShouldBeTheSameAs(command.Node); theTrade.ShouldBeTheSameAs(command.Trade); } [Test] public void NowDoItWithObjectFactoryItself() { ObjectFactory.Initialize(x => { x.ForConcreteType<ExplicitTarget>().Configure .Ctor<IProvider>().Is<RedProvider>() .Ctor<string>("name").Is("Jeremy"); }); // Get the ExplicitTarget without setting an explicit arg for IProvider var firstTarget = ObjectFactory.GetInstance<ExplicitTarget>(); firstTarget.Provider.ShouldBeOfType<RedProvider>(); // Now, set the explicit arg for IProvider var theBlueProvider = new BlueProvider(); var secondTarget = ObjectFactory.Container.With<IProvider>(theBlueProvider).GetInstance<ExplicitTarget>(); Assert.AreSame(theBlueProvider, secondTarget.Provider); } [Test] public void NowDoItWithObjectFactoryItself_with_new_API() { ObjectFactory.Initialize(x => { x.For<ExplicitTarget>().Use<ExplicitTarget>() .Ctor<IProvider>().Is(child => child.Type<RedProvider>()) .Ctor<string>("name").Is("Jeremy"); }); // Get the ExplicitTarget without setting an explicit arg for IProvider ObjectFactory.GetInstance<ExplicitTarget>().Provider.IsType<RedProvider>(); // Now, set the explicit arg for IProvider var theBlueProvider = new BlueProvider(); ObjectFactory.Container.With<IProvider>(theBlueProvider).GetInstance<ExplicitTarget>() .Provider.ShouldBeTheSameAs(theBlueProvider); } [Test] public void OverrideAPrimitiveWithObjectFactory() { ObjectFactory.Initialize(x => { x.ForConcreteType<ExplicitTarget>().Configure .Ctor<IProvider>().Is<RedProvider>() .Ctor<string>("name").Is("Jeremy"); }); // Get the ExplicitTarget without setting an explicit arg for IProvider var firstTarget = ObjectFactory.GetInstance<ExplicitTarget>(); Assert.AreEqual("Jeremy", firstTarget.Name); // Now, set the explicit arg for IProvider var secondTarget = ObjectFactory.Container.With("name").EqualTo("Julia").GetInstance<ExplicitTarget>(); Assert.AreEqual("Julia", secondTarget.Name); } [Test] public void pass_explicit_service_into_all_instances() { // The Container is constructed with 2 instances // of TradeView var container = new Container(r => { r.For<TradeView>().Use<TradeView>(); r.For<TradeView>().Add<SecuredTradeView>(); }); var theTrade = new Trade(); var views = container.With(theTrade).GetAllInstances<TradeView>(); views.ElementAt(0).Trade.ShouldBeTheSameAs(theTrade); views.ElementAt(1).Trade.ShouldBeTheSameAs(theTrade); } [Test] public void pass_explicit_service_into_all_instances_and_retrieve_without_generics() { // The Container is constructed with 2 instances // of TradeView var container = new Container(r => { r.For<TradeView>().Use<TradeView>(); r.For<TradeView>().Add<SecuredTradeView>(); }); var theTrade = new Trade(); var views = container.With(theTrade).GetAllInstances(typeof (TradeView)) .OfType<TradeView>(); views.ElementAt(0).Trade.ShouldBeTheSameAs(theTrade); views.ElementAt(1).Trade.ShouldBeTheSameAs(theTrade); } [Test] public void Pass_in_arguments_as_dictionary() { var container = new Container(x => { x.For<IView>().Use<View>(); }); var theNode = new Node(); var theTrade = new Trade(); var args = new ExplicitArguments(); args.Set(theNode); args.SetArg("trade", theTrade); var command = container.GetInstance<Command>(args); command.View.ShouldBeOfType<View>(); theNode.ShouldBeTheSameAs(command.Node); theTrade.ShouldBeTheSameAs(command.Trade); } [Test] public void PassAnArgumentIntoExplicitArgumentsForARequestedInterface() { IContainer manager = new Container( registry => registry.For<IProvider>().Use<LumpProvider>()); var args = new ExplicitArguments(); var theLump = new Lump(); args.Set(theLump); var instance = (LumpProvider) manager.GetInstance<IProvider>(args); Assert.AreSame(theLump, instance.Lump); } [Test] public void PassAnArgumentIntoExplicitArgumentsForARequestedInterfaceUsingObjectFactory() { ObjectFactory.Initialize(x => { x.For<IProvider>().Use<LumpProvider>(); }); var theLump = new Lump(); var provider = (LumpProvider)ObjectFactory.Container.With(theLump).GetInstance<IProvider>(); Assert.AreSame(theLump, provider.Lump); } [Test] public void PassAnArgumentIntoExplicitArgumentsThatMightNotAlreadyBeRegistered() { var theLump = new Lump(); var provider = ObjectFactory.Container.With(theLump).GetInstance<LumpProvider>(); Assert.AreSame(theLump, provider.Lump); } [Test] public void PassExplicitArgsIntoInstanceManager() { var container = new Container(r => { r.ForConcreteType<ExplicitTarget>().Configure .Ctor<IProvider>().Is<RedProvider>() .Ctor<string>("name").Is("Jeremy"); }); var args = new ExplicitArguments(); // Get the ExplicitTarget without setting an explicit arg for IProvider var firstTarget = container.GetInstance<ExplicitTarget>(args); firstTarget.Provider.ShouldBeOfType<RedProvider>(); // Now, set the explicit arg for IProvider args.Set<IProvider>(new BlueProvider()); var secondTarget = container.GetInstance<ExplicitTarget>(args); secondTarget.Provider.ShouldBeOfType<BlueProvider>(); } [Test] public void RegisterAndFindServicesOnTheExplicitArgument() { var args = new ExplicitArguments(); Assert.IsNull(args.Get<IProvider>()); var red = new RedProvider(); args.Set<IProvider>(red); Assert.AreSame(red, args.Get<IProvider>()); args.Set<IExplicitTarget>(new RedTarget()); args.Get<IExplicitTarget>().ShouldBeOfType<RedTarget>(); } [Test] public void RegisterAndRetrieveArgs() { var args = new ExplicitArguments(); Assert.IsNull(args.GetArg("name")); args.SetArg("name", "Jeremy"); Assert.AreEqual("Jeremy", args.GetArg("name")); args.SetArg("age", 34); Assert.AreEqual(34, args.GetArg("age")); } [Test] public void use_a_type_that_is_not_part_of_the_constructor_in_the_with() { var container = new Container(); container.With(new Address()).GetInstance<ClassWithNoArgs>() .ShouldBeOfType<ClassWithNoArgs>(); } [Test] public void use_explicit_type_arguments_with_custom_instance() { var container = new Container(x => { x.For<ClassWithNoArgs>().Use(new SpecialInstance()); }); var address = new Address(); container.With(address).GetInstance<ClassWithNoArgs>() .TheAddress.ShouldBeTheSameAs(address); } } public class Lump { } public class ColorWithLump { private readonly string _color; private readonly Lump _lump; public ColorWithLump(string color, Lump lump) { _color = color; _lump = lump; } public string Color { get { return _color; } } public Lump Lump { get { return _lump; } } } public class LumpProvider : TestExplicitArguments.IProvider { private readonly Lump _lump; public LumpProvider(Lump lump) { _lump = lump; } public Lump Lump { get { return _lump; } } } public class Trade { } public class TradeView : IView { private readonly Trade _trade; public TradeView(Trade trade) { _trade = trade; } public Trade Trade { get { return _trade; } } } public class SecuredTradeView : TradeView { public SecuredTradeView(Trade trade) : base(trade) { } } public class Node { } public interface IView { } public class View : IView { } public class Command { private readonly Node _node; private readonly Trade _trade; private readonly IView _view; public Command(Trade trade, Node node, IView view) { _trade = trade; _node = node; _view = view; } public Trade Trade { get { return _trade; } } public Node Node { get { return _node; } } public IView View { get { return _view; } } } public class TradeNode : Node { private readonly Trade _trade; public TradeNode(Trade trade) { _trade = trade; } public Trade Trade { get { return _trade; } } } public class ConcreteThatNeedsString { private readonly string _name; public ConcreteThatNeedsString(string name) { _name = name; } public string Name { get { return _name; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // 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.Data.Common; using Xunit; namespace System.Data.Tests.Common { public class DbDataAdapterTest { [Fact] public void UpdateBatchSize() { MyAdapter da = new MyAdapter(); try { da.UpdateBatchSize = 0; Assert.False(true); } catch (NotSupportedException ex) { // Specified method is not supported Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } Assert.Equal(1, da.UpdateBatchSize); try { da.UpdateBatchSize = int.MaxValue; Assert.False(true); } catch (NotSupportedException ex) { // Specified method is not supported Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } Assert.Equal(1, da.UpdateBatchSize); da.UpdateBatchSize = 1; Assert.Equal(1, da.UpdateBatchSize); } [Fact] public void UpdateBatchSize_Negative() { MyAdapter da = new MyAdapter(); try { da.UpdateBatchSize = -1; Assert.False(true); } catch (NotSupportedException ex) { // Specified method is not supported Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] public void ClearBatch() { MyAdapter da = new MyAdapter(); try { da.ClearBatch(); Assert.False(true); } catch (NotSupportedException ex) { Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] public void ExecuteBatch() { MyAdapter da = new MyAdapter(); try { da.ExecuteBatch(); Assert.False(true); } catch (NotSupportedException ex) { Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] public void GetBatchedParameter() { MyAdapter da = new MyAdapter(); try { da.GetBatchedParameter(1, 1); Assert.False(true); } catch (NotSupportedException ex) { Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] public void GetBatchedRecordsAffected() { MyAdapter da = new MyAdapter(); int recordsAffected = 0; Exception error = null; Assert.True(da.GetBatchedRecordsAffected(int.MinValue, out recordsAffected, out error)); Assert.Equal(1, recordsAffected); Assert.Null(error); } [Fact] public void InitializeBatching() { MyAdapter da = new MyAdapter(); try { da.InitializeBatching(); Assert.False(true); } catch (NotSupportedException ex) { Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] public void TerminateBatching() { MyAdapter da = new MyAdapter(); try { da.TerminateBatching(); Assert.False(true); } catch (NotSupportedException ex) { Assert.Equal(typeof(NotSupportedException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } private class MyAdapter : DbDataAdapter { public new int AddToBatch(IDbCommand command) { return base.AddToBatch(command); } public new void ClearBatch() { base.ClearBatch(); } public new void ExecuteBatch() { base.ClearBatch(); } public new IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex) { return base.GetBatchedParameter(commandIdentifier, parameterIndex); } public new bool GetBatchedRecordsAffected(int commandIdentifier, out int recordsAffected, out Exception error) { return base.GetBatchedRecordsAffected(commandIdentifier, out recordsAffected, out error); } public new void InitializeBatching() { base.InitializeBatching(); } public new void TerminateBatching() { base.TerminateBatching(); } } } }
using Microsoft.DirectX.Direct3D; using System; using System.Drawing; using System.Windows.Forms; using TGC.Core.UserControls; using TGC.Core.UserControls.Modifier; using TGC.Examples.Example; namespace Examples.Shaders { public class EjemploGPUAttack6 : TGCExampleViewer { private string MyMediaDir; private string MyShaderDir; private Effect effect; private Texture g_pRenderTarget, g_pTempData; private Surface g_pDepthStencil; // Depth-stencil buffer private VertexBuffer g_pVB; private static int MAX_DS = 1024; public int a = 33; public int c = 213; public int m = 251; public int[] hash = new int[6]; public bool found = false; public int prefix_x = 0; public int prefix_y = 0; public EjemploGPUAttack6(string mediaDir, string shadersDir, TgcUserVars userVars, TgcModifiers modifiers) : base(mediaDir, shadersDir, userVars, modifiers) { Category = "Shaders"; Name = "Workshop-GPUAttack6"; Description = "GPUAttack6"; } public unsafe override void Init() { Device d3dDevice = GuiController.Instance.D3dDevice; GuiController.Instance.CustomRenderEnabled = true; MyMediaDir = MediaDir + "\\WorkshopShaders\\"; MyShaderDir = ShadersDir + "\\WorkshopShaders\\"; //Cargar Shader string compilationErrors; effect = Effect.FromFile(d3dDevice, MyShaderDir + "GPUAttack.fx", null, null, ShaderFlags.None, null, out compilationErrors); if (effect == null) { throw new Exception("Error al cargar shader. Errores: " + compilationErrors); } // inicializo el render target g_pRenderTarget = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, Usage.RenderTarget, Format.A8R8G8B8, Pool.Default); effect.SetValue("g_RenderTarget", g_pRenderTarget); // temporaria para recuperar los valores g_pTempData = new Texture(d3dDevice, MAX_DS, MAX_DS, 1, 0, Format.A8R8G8B8, Pool.SystemMemory); // stencil g_pDepthStencil = d3dDevice.CreateDepthStencilSurface(MAX_DS, MAX_DS, DepthFormat.D24S8, MultiSampleType.None, 0, true); //Se crean 2 triangulos con las dimensiones de la pantalla con sus posiciones ya transformadas // x = -1 es el extremo izquiedo de la pantalla, x=1 es el extremo derecho // Lo mismo para la Y con arriba y abajo // la Z en 1 simpre CustomVertex.PositionTextured[] vertices = new CustomVertex.PositionTextured[] { new CustomVertex.PositionTextured( -1, 1, 1, 0,0), new CustomVertex.PositionTextured(1, 1, 1, 1,0), new CustomVertex.PositionTextured(-1, -1, 1, 0,1), new CustomVertex.PositionTextured(1,-1, 1, 1,1) }; //vertex buffer de los triangulos g_pVB = new VertexBuffer(typeof(CustomVertex.PositionTextured), 4, d3dDevice, Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default); g_pVB.SetData(vertices, 0, LockFlags.None); string input = InputBox("Ingrese la Clave de 6 letras (A..Z)", "Clave", "CHARLY"); int[] clave = new int[6]; for (int i = 0; i < 6; ++i) clave[i] = input[i]; Hash(clave, hash); effect.SetValue("hash_buscado6", hash); char[] buffer = new char[7]; for (int i = 0; i < 6; ++i) buffer[i] = (char)hash[i]; buffer[6] = (char)0; string msg = new string(buffer); msg = "El hash es " + msg + "\n"; MessageBox.Show(msg); } public override void Update() { PreUpdate(); } public unsafe override void Render() { if (found) return; Device device = GuiController.Instance.D3dDevice; Control panel3d = GuiController.Instance.Panel3d; Surface pOldRT = device.GetRenderTarget(0); Surface pSurf = g_pRenderTarget.GetSurfaceLevel(0); device.SetRenderTarget(0, pSurf); Surface pOldDS = device.DepthStencilSurface; device.DepthStencilSurface = g_pDepthStencil; effect.SetValue("prefix_x", prefix_x); effect.SetValue("prefix_y", prefix_y); device.RenderState.ZBufferEnable = false; device.Clear(ClearFlags.Target, Color.Black, 1.0f, 0); device.BeginScene(); effect.Technique = "ComputeHash6"; device.VertexFormat = CustomVertex.PositionTextured.Format; device.SetStreamSource(0, g_pVB, 0); effect.Begin(FX.None); effect.BeginPass(0); device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2); effect.EndPass(); effect.End(); device.EndScene(); device.SetRenderTarget(0, pOldRT); device.DepthStencilSurface = pOldDS; // leo los datos de la textura // ---------------------------------------------------------------------- Surface pDestSurf = g_pTempData.GetSurfaceLevel(0); device.GetRenderTargetData(pSurf, pDestSurf); Byte* pData = (Byte*)pDestSurf.LockRectangle(LockFlags.None).InternalData.ToPointer(); string msg = ""; for (int i = 0; i < MAX_DS; i++) { for (int j = 0; j < MAX_DS; j++) { Byte A = *pData++; Byte R = *pData++; Byte G = *pData++; Byte B = *pData++; if (R == 255 && G == 255 && B == 255) { int group_x = j / 32; int x = j % 32; int group_y = i / 32; int y = i % 32; int[] clave = new int[6]; clave[0] = 'A' + prefix_x; clave[1] = 'A' + prefix_y; clave[2] = 'A' + group_x; clave[3] = 'A' + group_y; clave[4] = 'A' + x; clave[5] = 'A' + y; Hash(clave, hash); char[] buffer = new char[7]; for (int t = 0; t < 6; ++t) buffer[t] = (char)clave[t]; buffer[6] = (char)0; msg = new string(buffer); msg = "La clave que elegiste es " + msg; found = true; i = j = MAX_DS; } /* int group_x = j / 32; int x = j % 32; int group_y = i/ 32; int y = i % 32; int[] clave = new int[6]; clave[0] = 'A' + prefix_x; clave[1] = 'A' + prefix_y; clave[2] = 'A' + group_x; clave[3] = 'A' + group_y; clave[4] = 'A' + x; clave[5] = 'A' + y; Hash(clave, hash); if (hash[0] != G || hash[1] != R || hash[2] != A || hash[3] != B) { int a = 0; } */ } } pDestSurf.UnlockRectangle(); pSurf.Dispose(); if (found) MessageBox.Show(msg); char[] saux = new char[3]; saux[0] = (char)('A' + prefix_x); saux[1] = (char)('A' + prefix_y); saux[2] = (char)0; string s = new string(saux); s = "Hacking " + s + "AAAA - " + s + "ZZZZ"; device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0); device.BeginScene(); GuiController.Instance.Text3d.drawText(s, 100, 300, Color.Yellow); device.EndScene(); if (++prefix_x == 32) { prefix_x = 0; ++prefix_y; } } public void Hash(int[] clave, int[] buffer) { int k = (clave[0] + clave[1] + clave[2] + clave[3] + clave[4] + clave[5]) % 256; for (int i = 0; i < 6; ++i) { k = (a * k + c) % m; buffer[i] = k; k += clave[i]; } } public override void Dispose() { effect.Dispose(); g_pRenderTarget.Dispose(); g_pDepthStencil.Dispose(); g_pVB.Dispose(); g_pTempData.Dispose(); } public static String InputBox(String caption, String prompt, String defaultText) { String localInputText = defaultText; if (InputQuery(caption, prompt, ref localInputText)) { return localInputText; } else { return ""; } } public static int MulDiv(int a, float b, int c) { return (int)((float)a * b / (float)c); } public static Boolean InputQuery(String caption, String prompt, ref String value) { Form form; form = new Form(); form.AutoScaleMode = AutoScaleMode.Font; form.Font = SystemFonts.IconTitleFont; SizeF dialogUnits; dialogUnits = form.AutoScaleDimensions; form.FormBorderStyle = FormBorderStyle.FixedDialog; form.MinimizeBox = false; form.MaximizeBox = false; form.Text = caption; form.ClientSize = new Size( MulDiv(180, dialogUnits.Width, 4), MulDiv(63, dialogUnits.Height, 8)); form.StartPosition = FormStartPosition.CenterScreen; System.Windows.Forms.Label lblPrompt; lblPrompt = new System.Windows.Forms.Label(); lblPrompt.Parent = form; lblPrompt.AutoSize = true; lblPrompt.Left = MulDiv(8, dialogUnits.Width, 4); lblPrompt.Top = MulDiv(8, dialogUnits.Height, 8); lblPrompt.Text = prompt; System.Windows.Forms.TextBox edInput; edInput = new System.Windows.Forms.TextBox(); edInput.Parent = form; edInput.Left = lblPrompt.Left; edInput.Top = MulDiv(19, dialogUnits.Height, 8); edInput.Width = MulDiv(164, dialogUnits.Width, 4); edInput.Text = value; edInput.SelectAll(); int buttonTop = MulDiv(41, dialogUnits.Height, 8); Size buttonSize = new Size(MulDiv(50, dialogUnits.Width, 4), MulDiv(14, dialogUnits.Height, 8)); System.Windows.Forms.Button bbOk = new System.Windows.Forms.Button(); bbOk.Parent = form; bbOk.Text = "OK"; bbOk.DialogResult = DialogResult.OK; form.AcceptButton = bbOk; bbOk.Location = new Point(MulDiv(38, dialogUnits.Width, 4), buttonTop); bbOk.Size = buttonSize; System.Windows.Forms.Button bbCancel = new System.Windows.Forms.Button(); bbCancel.Parent = form; bbCancel.Text = "Cancel"; bbCancel.DialogResult = DialogResult.Cancel; form.CancelButton = bbCancel; bbCancel.Location = new Point(MulDiv(92, dialogUnits.Width, 4), buttonTop); bbCancel.Size = buttonSize; if (form.ShowDialog() == DialogResult.OK) { value = edInput.Text; return true; } else { return false; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests; using ObjectFormatterFixtures; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.Hosting.CSharp.UnitTests { public class ObjectFormatterTests : ObjectFormatterTestBase { [Fact] public void Objects() { string str; object nested = new Outer.Nested<int>(); str = CSharpObjectFormatter.Instance.FormatObject(nested, s_inline); Assert.Equal(@"Outer.Nested<int> { A=1, B=2 }", str); str = CSharpObjectFormatter.Instance.FormatObject(nested, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"Outer.Nested<int>", str); str = CSharpObjectFormatter.Instance.FormatObject(A<int>.X, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"A<int>.B<int>", str); object obj = new A<int>.B<bool>.C.D<string, double>.E(); str = CSharpObjectFormatter.Instance.FormatObject(obj, new ObjectFormattingOptions(memberFormat: MemberDisplayFormat.NoMembers)); Assert.Equal(@"A<int>.B<bool>.C.D<string, double>.E", str); var sort = new Sort(); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 51, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, a ...", str); Assert.Equal(51, str.Length); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 5, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"S ...", str); Assert.Equal(5, str.Length); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 4, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 3, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 2, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 1, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"...", str); str = CSharpObjectFormatter.Instance.FormatObject(sort, new ObjectFormattingOptions(maxLineLength: 80, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal(@"Sort { aB=-1, ab=1, Ac=-1, Ad=1, ad=-1, aE=1, aF=-1, AG=1 }", str); } [Fact] public void ArrayOtInt32_NoMembers() { CSharpObjectFormatter formatter = CSharpObjectFormatter.Instance; object o = new int[4] { 3, 4, 5, 6 }; var str = formatter.FormatObject(o); Assert.Equal("int[4] { 3, 4, 5, 6 }", str); } #region DANGER: Debugging this method under VS2010 might freeze your machine. [Fact] public void RecursiveRootHidden() { var DO_NOT_ADD_TO_WATCH_WINDOW = new RecursiveRootHidden(); DO_NOT_ADD_TO_WATCH_WINDOW.C = DO_NOT_ADD_TO_WATCH_WINDOW; string str = CSharpObjectFormatter.Instance.FormatObject(DO_NOT_ADD_TO_WATCH_WINDOW, s_inline); Assert.Equal(@"RecursiveRootHidden { A=0, B=0 }", str); } #endregion [Fact] public void DebuggerDisplay_ParseSimpleMemberName() { Test_ParseSimpleMemberName("foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName(" foo ", name: "foo", callable: false, nq: false); Test_ParseSimpleMemberName("foo()", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("\nfoo (\r\n)", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName(" foo ( \t) ", name: "foo", callable: true, nq: false); Test_ParseSimpleMemberName("foo,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo ,nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(),nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) ,nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName(" foo \t( ) , nq", name: "foo", callable: true, nq: true); Test_ParseSimpleMemberName("foo, nq", name: "foo", callable: false, nq: true); Test_ParseSimpleMemberName("foo(,nq", name: "foo(", callable: false, nq: true); Test_ParseSimpleMemberName("foo),nq", name: "foo)", callable: false, nq: true); Test_ParseSimpleMemberName("foo ( ,nq", name: "foo (", callable: false, nq: true); Test_ParseSimpleMemberName("foo ) ,nq", name: "foo )", callable: false, nq: true); Test_ParseSimpleMemberName(",nq", name: "", callable: false, nq: true); Test_ParseSimpleMemberName(" ,nq", name: "", callable: false, nq: true); } private void Test_ParseSimpleMemberName(string value, string name, bool callable, bool nq) { bool actualNoQuotes, actualIsCallable; string actualName = CSharpObjectFormatter.Formatter.ParseSimpleMemberName(value, 0, value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); actualName = CSharpObjectFormatter.Formatter.ParseSimpleMemberName("---" + value + "-", 3, 3 + value.Length, out actualNoQuotes, out actualIsCallable); Assert.Equal(name, actualName); Assert.Equal(nq, actualNoQuotes); Assert.Equal(callable, actualIsCallable); } [Fact] public void DebuggerDisplay() { string str; var a = new ComplexProxy(); str = CSharpObjectFormatter.Instance.FormatObject(a, s_memberList); AssertMembers(str, @"[AStr]", @"_02_public_property_dd: *1", @"_03_private_property_dd: *2", @"_04_protected_property_dd: *3", @"_05_internal_property_dd: *4", @"_07_private_field_dd: +2", @"_08_protected_field_dd: +3", @"_09_internal_field_dd: +4", @"_10_private_collapsed: 0", @"_12_public: 0", @"_13_private: 0", @"_14_protected: 0", @"_15_internal: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_33: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1", @"_40_private_get_private_set: 1" ); var b = new TypeWithComplexProxy(); str = CSharpObjectFormatter.Instance.FormatObject(b, s_memberList); AssertMembers(str, @"[BStr]", @"_02_public_property_dd: *1", @"_04_protected_property_dd: *3", @"_08_protected_field_dd: +3", @"_10_private_collapsed: 0", @"_12_public: 0", @"_14_protected: 0", "_16_eolns: ==\r\n=\r\n=", @"_17_braces_0: =={==", @"_17_braces_1: =={{==", @"_17_braces_2: ==!<Member ''{'' not found>==", @"_17_braces_3: ==!<Member ''\{'' not found>==", @"_17_braces_4: ==!<Member '1/*{*/' not found>==", @"_17_braces_5: ==!<Member ''{'/*\' not found>*/}==", @"_17_braces_6: ==!<Member ''{'/*' not found>*/}==", @"_19_escapes: ==\{\x\t==", @"_21: !<Member '1+1' not found>", @"_22: !<Member '""xxx""' not found>", @"_23: !<Member '""xxx""' not found>", @"_24: !<Member ''x'' not found>", @"_25: !<Member ''x'' not found>", @"_26_0: !<Method 'new B' not found>", @"_26_1: !<Method 'new D' not found>", @"_26_2: !<Method 'new E' not found>", @"_26_3: ", @"_26_4: !<Member 'F1(1)' not found>", @"_26_5: 1", @"_26_6: 2", @"A: 1", @"B: 2", @"_28: [CStr]", @"_29_collapsed: [CStr]", @"_31: 0", @"_32: 0", @"_34_Exception: !<Exception>", @"_35_Exception: -!-", @"_36: !<MyException>", @"_38_private_get_public_set: 1", @"_39_public_get_private_set: 1" ); } [Fact] public void DebuggerDisplay_Inherited() { var obj = new InheritedDebuggerDisplay(); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("InheritedDebuggerDisplay(DebuggerDisplayValue)", str); } [Fact] public void DebuggerProxy_DebuggerDisplayAndProxy() { var obj = new TypeWithDebuggerDisplayAndProxy(); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("TypeWithDebuggerDisplayAndProxy(DD) { A=0, B=0 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "TypeWithDebuggerDisplayAndProxy(DD)", "A: 0", "B: 0" ); } [Fact] public void DebuggerProxy_Recursive() { string str; object obj = new RecursiveProxy.Node(0); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Node", "x: 0", "y: Node { x=1, y=Node { x=2, y=Node { x=3, y=Node { x=4, y=Node { x=5, y=null } } } } }" ); obj = new InvalidRecursiveProxy.Node(); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); // TODO: better overflow handling Assert.Equal("!<Stack overflow while evaluating object>", str); } [Fact] public void Array_Recursive() { string str; ListNode n2; ListNode n1 = new ListNode(); object[] obj = new object[5]; obj[0] = 1; obj[1] = obj; obj[2] = n2 = new ListNode() { data = obj, next = n1 }; obj[3] = new object[] { 4, 5, obj, 6, new ListNode() }; obj[4] = 3; n1.next = n2; n1.data = new object[] { 7, n2, 8, obj }; str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "object[5]", "1", "{ ... }", "ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }", "object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }", "3" ); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal(str, "object[5] { 1, { ... }, ListNode { data={ ... }, next=ListNode { data=object[4] { 7, ListNode { ... }, 8, { ... } }, next=ListNode { ... } } }, object[5] { 4, 5, { ... }, 6, ListNode { data=null, next=null } }, 3 }"); } [Fact] public void LargeGraph() { var list = new LinkedList<object>(); object obj = list; for (int i = 0; i < 10000; i++) { var node = list.AddFirst(i); var newList = new LinkedList<object>(); list.AddAfter(node, newList); list = newList; } string output = "LinkedList<object>(2) { 0, LinkedList<object>(2) { 1, LinkedList<object>(2) { 2, LinkedList<object>(2) {"; for (int i = 100; i > 4; i--) { var options = new ObjectFormattingOptions(maxOutputLength: i, memberFormat: MemberDisplayFormat.Inline); var str = CSharpObjectFormatter.Instance.FormatObject(obj, options); var expected = output.Substring(0, i - " ...".Length); if (!expected.EndsWith(" ", StringComparison.Ordinal)) { expected += " "; } expected += "..."; Assert.Equal(expected, str); } } [Fact] public void LongMembers() { object obj = new LongMembers(); var options = new ObjectFormattingOptions(maxLineLength: 20, memberFormat: MemberDisplayFormat.Inline); //str = ObjectFormatter.Instance.FormatObject(obj, options); //Assert.Equal("LongMembers { Lo ...", str); options = new ObjectFormattingOptions(maxLineLength: 20, memberFormat: MemberDisplayFormat.List); var str = CSharpObjectFormatter.Instance.FormatObject(obj, options); Assert.Equal("LongMembers {\r\n LongName012345 ...\r\n LongValue: \"01 ...\r\n}\r\n", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Array() { var obj = new Object[] { new C(), 1, "str", 'c', true, null, new bool[] { true, false, true, false } }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "object[7]", "[CStr]", "1", "\"str\"", "'c'", "true", "null", "bool[4] { true, false, true, false }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_MdArray() { string str; int[,,] a = new int[2, 3, 4] { { { 000, 001, 002, 003 }, { 010, 011, 012, 013 }, { 020, 021, 022, 023 }, }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 }, } }; str = CSharpObjectFormatter.Instance.FormatObject(a, s_inline); Assert.Equal("int[2, 3, 4] { { { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }, { { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } } }", str); str = CSharpObjectFormatter.Instance.FormatObject(a, s_memberList); AssertMembers(str, "int[2, 3, 4]", "{ { 0, 1, 2, 3 }, { 10, 11, 12, 13 }, { 20, 21, 22, 23 } }", "{ { 100, 101, 102, 103 }, { 110, 111, 112, 113 }, { 120, 121, 122, 123 } }" ); int[][,][,,,] obj = new int[2][,][,,,]; obj[0] = new int[1, 2][,,,]; obj[0][0, 0] = new int[1, 2, 3, 4]; str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("int[2][,][,,,] { int[1, 2][,,,] { { int[1, 2, 3, 4] { { { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } } } }, null } }, null }", str); Array x = Array.CreateInstance(typeof(Object), lengths: new int[] { 2, 3 }, lowerBounds: new int[] { 2, 9 }); str = CSharpObjectFormatter.Instance.FormatObject(x, s_inline); Assert.Equal("object[2..4, 9..12] { { null, null, null }, { null, null, null } }", str); Array y = Array.CreateInstance(typeof(Object), lengths: new int[] { 1, 1 }, lowerBounds: new int[] { 0, 0 }); str = CSharpObjectFormatter.Instance.FormatObject(y, s_inline); Assert.Equal("object[1, 1] { { null } }", str); Array z = Array.CreateInstance(typeof(Object), lengths: new int[] { 0, 0 }, lowerBounds: new int[] { 0, 0 }); str = CSharpObjectFormatter.Instance.FormatObject(z, s_inline); Assert.Equal("object[0, 0] { }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable() { string str; object obj; obj = Enumerable.Range(0, 10); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("RangeIterator { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IEnumerable_Exception() { string str; object obj; obj = Enumerable.Range(0, 10).Where(i => { if (i == 5) throw new Exception("xxx"); return i < 7; }); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Enumerable.WhereEnumerableIterator<int> { 0, 1, 2, 3, 4, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary() { string str; object obj; obj = new ThrowingDictionary(throwAt: -1); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, { 3, 3 }, { 4, 4 } }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "ThrowingDictionary(10)", "{ 1, 1 }", "{ 2, 2 }", "{ 3, 3 }", "{ 4, 4 }" ); } [Fact] public void DebuggerProxy_FrameworkTypes_IDictionary_Exception() { string str; object obj; obj = new ThrowingDictionary(throwAt: 3); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ThrowingDictionary(10) { { 1, 1 }, { 2, 2 }, !<Exception> ... }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BitArray() { // BitArray doesn't have debugger proxy/display var obj = new System.Collections.BitArray(new int[] { 1 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("BitArray(32) { true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Queue() { var obj = new Queue<int>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Queue<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Stack() { var obj = new Stack<int>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Stack<int>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Dictionary() { var obj = new Dictionary<string, int> { { "x", 1 }, }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Dictionary<string, int>(1)", "{ \"x\", 1 }" ); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Dictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_KeyValuePair() { var obj = new KeyValuePair<int, string>(1, "x"); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("KeyValuePair<int, string> { 1, \"x\" }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_List() { var obj = new List<object> { 1, 2, 'c' }; var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("List<object>(3) { 1, 2, 'c' }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_LinkedList() { var obj = new LinkedList<int>(); obj.AddLast(1); obj.AddLast(2); obj.AddLast(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("LinkedList<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedList() { var obj = new SortedList<int, int>(); obj.Add(3, 4); obj.Add(1, 5); obj.Add(2, 6); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SortedList<int, int>(3) { { 1, 5 }, { 2, 6 }, { 3, 4 } }", str); var obj2 = new SortedList<int[], int[]>(); obj2.Add(new[] { 3 }, new int[] { 4 }); str = CSharpObjectFormatter.Instance.FormatObject(obj2, s_inline); Assert.Equal("SortedList<int[], int[]>(1) { { int[1] { 3 }, int[1] { 4 } } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedDictionary() { var obj = new SortedDictionary<int, int>(); obj.Add(1, 0x1a); obj.Add(3, 0x3c); obj.Add(2, 0x2b); var str = CSharpObjectFormatter.Instance. FormatObject(obj, new ObjectFormattingOptions(useHexadecimalNumbers: true, memberFormat: MemberDisplayFormat.Inline)); Assert.Equal("SortedDictionary<int, int>(3) { { 0x00000001, 0x0000001a }, { 0x00000002, 0x0000002b }, { 0x00000003, 0x0000003c } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_HashSet() { var obj = new HashSet<int>(); obj.Add(1); obj.Add(2); // HashSet doesn't implement ICollection (it only implements ICollection<T>) so we don't call Count, // instead a DebuggerDisplay.Value is used. var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("HashSet<int>(Count = 2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_SortedSet() { var obj = new SortedSet<int>(); obj.Add(1); obj.Add(2); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SortedSet<int>(2) { 1, 2 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentDictionary() { var obj = new ConcurrentDictionary<string, int>(); obj.AddOrUpdate("x", 1, (k, v) => v); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentDictionary<string, int>(1) { { \"x\", 1 } }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentQueue() { var obj = new ConcurrentQueue<object>(); obj.Enqueue(1); obj.Enqueue(2); obj.Enqueue(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentQueue<object>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_ConcurrentStack() { var obj = new ConcurrentStack<object>(); obj.Push(1); obj.Push(2); obj.Push(3); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ConcurrentStack<object>(3) { 3, 2, 1 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_BlockingCollection() { var obj = new BlockingCollection<int>(); obj.Add(1); obj.Add(2, new CancellationToken()); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("BlockingCollection<int>(2) { 1, 2 }", str); } // TODO(tomat): this only works with System.dll file version 30319.16644 (Win8 build) //[Fact] //public void DebuggerProxy_FrameworkTypes_ConcurrentBag() //{ // var obj = new ConcurrentBag<int>(); // obj.Add(1); // var str = ObjectFormatter.Instance.FormatObject(obj, quoteStrings: true, memberFormat: MemberDisplayFormat.Inline); // Assert.Equal("ConcurrentBag<int>(1) { 1 }", str); //} [Fact] public void DebuggerProxy_FrameworkTypes_ReadOnlyCollection() { var obj = new System.Collections.ObjectModel.ReadOnlyCollection<int>(new[] { 1, 2, 3 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ReadOnlyCollection<int>(3) { 1, 2, 3 }", str); } [Fact] public void DebuggerProxy_FrameworkTypes_Lazy() { var obj = new Lazy<int[]>(() => new int[] { 1, 2 }, LazyThreadSafetyMode.None); // Lazy<T> has both DebuggerDisplay and DebuggerProxy attributes and both display the same information. var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null) { IsValueCreated=false, IsValueFaulted=false, Mode=None, Value=null }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=false, IsValueFaulted=false, Value=null)", "IsValueCreated: false", "IsValueFaulted: false", "Mode: None", "Value: null" ); Assert.NotNull(obj.Value); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 }) { IsValueCreated=true, IsValueFaulted=false, Mode=None, Value=int[2] { 1, 2 } }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "Lazy<int[]>(ThreadSafetyMode=None, IsValueCreated=true, IsValueFaulted=false, Value=int[2] { 1, 2 })", "IsValueCreated: true", "IsValueFaulted: false", "Mode: None", "Value: int[2] { 1, 2 }" ); } public void TaskMethod() { } [Fact] public void DebuggerProxy_FrameworkTypes_Task() { var obj = new System.Threading.Tasks.Task(TaskMethod); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal( @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"") { AsyncState=null, CancellationPending=false, CreationOptions=None, Exception=null, Id=*, Status=Created }", FilterDisplayString(str)); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(FilterDisplayString(str), @"Task(Id = *, Status = Created, Method = ""Void TaskMethod()"")", "AsyncState: null", "CancellationPending: false", "CreationOptions: None", "Exception: null", "Id: *", "Status: Created" ); } [Fact] public void DebuggerProxy_FrameworkTypes_SpinLock() { var obj = new SpinLock(); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("SpinLock(IsHeld = false) { IsHeld=false, IsHeldByCurrentThread=false, OwnerThreadID=0 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "SpinLock(IsHeld = false)", "IsHeld: false", "IsHeldByCurrentThread: false", "OwnerThreadID: 0" ); } [Fact] public void DebuggerProxy_DiagnosticBag() { var obj = new DiagnosticBag(); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_AbstractAndExtern, "bar"), NoLocation.Singleton); obj.Add(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_BadExternIdentifier, "foo"), NoLocation.Singleton); using (new EnsureEnglishUICulture()) { var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("DiagnosticBag(Count = 2) { =error CS0180: 'bar' cannot be both extern and abstract, =error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "DiagnosticBag(Count = 2)", ": error CS0180: 'bar' cannot be both extern and abstract", ": error CS1679: Invalid extern alias for '/reference'; 'foo' is not a valid identifier" ); } } [Fact] public void DebuggerProxy_ArrayBuilder() { var obj = new ArrayBuilder<int>(); obj.AddRange(new[] { 1, 2, 3, 4, 5 }); var str = CSharpObjectFormatter.Instance.FormatObject(obj, s_inline); Assert.Equal("ArrayBuilder<int>(Count = 5) { 1, 2, 3, 4, 5 }", str); str = CSharpObjectFormatter.Instance.FormatObject(obj, s_memberList); AssertMembers(str, "ArrayBuilder<int>(Count = 5)", "1", "2", "3", "4", "5" ); } } }
// // ImageIO.cs : Constants // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2012, 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 MonoMac.ObjCRuntime; using MonoMac.Foundation; using MonoMac.CoreFoundation; using System; using System.Drawing; namespace MonoMac.ImageIO { [Since (4,0)] [Static] // Bad name should end with Keys interface CGImageProperties { // Format-Specific Dictionaries [Field ("kCGImagePropertyTIFFDictionary")] NSString TIFFDictionary { get; } [Field ("kCGImagePropertyGIFDictionary")] NSString GIFDictionary { get; } [Field ("kCGImagePropertyJFIFDictionary")] NSString JFIFDictionary { get; } [Field ("kCGImagePropertyExifDictionary")] NSString ExifDictionary { get; } [Field ("kCGImagePropertyPNGDictionary")] NSString PNGDictionary { get; } [Field ("kCGImagePropertyIPTCDictionary")] NSString IPTCDictionary { get; } [Field ("kCGImagePropertyGPSDictionary")] NSString GPSDictionary { get; } [Field ("kCGImagePropertyRawDictionary")] NSString RawDictionary { get; } [Field ("kCGImagePropertyCIFFDictionary")] NSString CIFFDictionary { get; } [Field ("kCGImageProperty8BIMDictionary")] NSString EightBIMDictionary { get; } [Field ("kCGImagePropertyDNGDictionary")] NSString DNGDictionary { get; } [Field ("kCGImagePropertyExifAuxDictionary")] NSString ExifAuxDictionary { get; } // Camera-Maker Dictionaries [Field ("kCGImagePropertyMakerCanonDictionary")] NSString MakerCanonDictionary { get; } [Field ("kCGImagePropertyMakerNikonDictionary")] NSString MakerNikonDictionary { get; } [Field ("kCGImagePropertyMakerMinoltaDictionary")] NSString MakerMinoltaDictionary { get; } [Field ("kCGImagePropertyMakerFujiDictionary")] NSString MakerFujiDictionary { get; } [Field ("kCGImagePropertyMakerOlympusDictionary")] NSString MakerOlympusDictionary { get; } [Field ("kCGImagePropertyMakerPentaxDictionary")] NSString MakerPentaxDictionary { get; } // Image Source Container Properties [Field ("kCGImagePropertyFileSize")] NSString FileSize { get; } // Individual Image Properties [Field ("kCGImagePropertyDPIHeight")] NSString DPIHeight { get; } [Field ("kCGImagePropertyDPIWidth")] NSString DPIWidth { get; } [Field ("kCGImagePropertyPixelWidth")] NSString PixelWidth { get; } [Field ("kCGImagePropertyPixelHeight")] NSString PixelHeight { get; } [Field ("kCGImagePropertyDepth")] NSString Depth { get; } [Field ("kCGImagePropertyOrientation")] NSString Orientation { get; } [Field ("kCGImagePropertyIsFloat")] NSString IsFloat { get; } [Field ("kCGImagePropertyIsIndexed")] NSString IsIndexed { get; } [Field ("kCGImagePropertyHasAlpha")] NSString HasAlpha { get; } [Field ("kCGImagePropertyColorModel")] NSString ColorModel { get; } [Field ("kCGImagePropertyProfileName")] NSString ProfileName { get; } // Color Model Values [Field ("kCGImagePropertyColorModelRGB")] NSString ColorModelRGB { get; } [Field ("kCGImagePropertyColorModelGray")] NSString ColorModelGray { get; } [Field ("kCGImagePropertyColorModelCMYK")] NSString ColorModelCMYK { get; } [Field ("kCGImagePropertyColorModelLab")] NSString ColorModelLab { get; } // EXIF Dictionary Keys [Field ("kCGImagePropertyExifExposureTime")] NSString ExifExposureTime { get; } [Field ("kCGImagePropertyExifFNumber")] NSString ExifFNumber { get; } [Field ("kCGImagePropertyExifExposureProgram")] NSString ExifExposureProgram { get; } [Field ("kCGImagePropertyExifSpectralSensitivity")] NSString ExifSpectralSensitivity { get; } [Field ("kCGImagePropertyExifISOSpeedRatings")] NSString ExifISOSpeedRatings { get; } [Field ("kCGImagePropertyExifOECF")] NSString ExifOECF { get; } [Field ("kCGImagePropertyExifVersion")] NSString ExifVersion { get; } [Field ("kCGImagePropertyExifDateTimeOriginal")] NSString ExifDateTimeOriginal { get; } [Field ("kCGImagePropertyExifDateTimeDigitized")] NSString ExifDateTimeDigitized { get; } [Field ("kCGImagePropertyExifComponentsConfiguration")] NSString ExifComponentsConfiguration { get; } [Field ("kCGImagePropertyExifCompressedBitsPerPixel")] NSString ExifCompressedBitsPerPixel { get; } [Field ("kCGImagePropertyExifShutterSpeedValue")] NSString ExifShutterSpeedValue { get; } [Field ("kCGImagePropertyExifApertureValue")] NSString ExifApertureValue { get; } [Field ("kCGImagePropertyExifBrightnessValue")] NSString ExifBrightnessValue { get; } [Field ("kCGImagePropertyExifExposureBiasValue")] NSString ExifExposureBiasValue { get; } [Field ("kCGImagePropertyExifMaxApertureValue")] NSString ExifMaxApertureValue { get; } [Field ("kCGImagePropertyExifSubjectDistance")] NSString ExifSubjectDistance { get; } [Field ("kCGImagePropertyExifMeteringMode")] NSString ExifMeteringMode { get; } [Field ("kCGImagePropertyExifLightSource")] NSString ExifLightSource { get; } [Field ("kCGImagePropertyExifFlash")] NSString ExifFlash { get; } [Field ("kCGImagePropertyExifFocalLength")] NSString ExifFocalLength { get; } [Field ("kCGImagePropertyExifSubjectArea")] NSString ExifSubjectArea { get; } [Field ("kCGImagePropertyExifMakerNote")] NSString ExifMakerNote { get; } [Field ("kCGImagePropertyExifUserComment")] NSString ExifUserComment { get; } [Field ("kCGImagePropertyExifSubsecTime")] NSString ExifSubsecTime { get; } [Field ("kCGImagePropertyExifSubsecTimeOrginal")] NSString ExifSubsecTimeOrginal { get; } [Field ("kCGImagePropertyExifSubsecTimeDigitized")] NSString ExifSubsecTimeDigitized { get; } [Field ("kCGImagePropertyExifFlashPixVersion")] NSString ExifFlashPixVersion { get; } [Field ("kCGImagePropertyExifColorSpace")] NSString ExifColorSpace { get; } [Field ("kCGImagePropertyExifPixelXDimension")] NSString ExifPixelXDimension { get; } [Field ("kCGImagePropertyExifPixelYDimension")] NSString ExifPixelYDimension { get; } [Field ("kCGImagePropertyExifRelatedSoundFile")] NSString ExifRelatedSoundFile { get; } [Field ("kCGImagePropertyExifFlashEnergy")] NSString ExifFlashEnergy { get; } [Field ("kCGImagePropertyExifSpatialFrequencyResponse")] NSString ExifSpatialFrequencyResponse { get; } [Field ("kCGImagePropertyExifFocalPlaneXResolution")] NSString ExifFocalPlaneXResolution { get; } [Field ("kCGImagePropertyExifFocalPlaneYResolution")] NSString ExifFocalPlaneYResolution { get; } [Field ("kCGImagePropertyExifFocalPlaneResolutionUnit")] NSString ExifFocalPlaneResolutionUnit { get; } [Field ("kCGImagePropertyExifSubjectLocation")] NSString ExifSubjectLocation { get; } [Field ("kCGImagePropertyExifExposureIndex")] NSString ExifExposureIndex { get; } [Field ("kCGImagePropertyExifSensingMethod")] NSString ExifSensingMethod { get; } [Field ("kCGImagePropertyExifFileSource")] NSString ExifFileSource { get; } [Field ("kCGImagePropertyExifSceneType")] NSString ExifSceneType { get; } [Field ("kCGImagePropertyExifCFAPattern")] NSString ExifCFAPattern { get; } [Field ("kCGImagePropertyExifCustomRendered")] NSString ExifCustomRendered { get; } [Field ("kCGImagePropertyExifExposureMode")] NSString ExifExposureMode { get; } [Field ("kCGImagePropertyExifWhiteBalance")] NSString ExifWhiteBalance { get; } [Field ("kCGImagePropertyExifDigitalZoomRatio")] NSString ExifDigitalZoomRatio { get; } [Field ("kCGImagePropertyExifFocalLenIn35mmFilm")] NSString ExifFocalLenIn35mmFilm { get; } [Field ("kCGImagePropertyExifSceneCaptureType")] NSString ExifSceneCaptureType { get; } [Field ("kCGImagePropertyExifGainControl")] NSString ExifGainControl { get; } [Field ("kCGImagePropertyExifContrast")] NSString ExifContrast { get; } [Field ("kCGImagePropertyExifSaturation")] NSString ExifSaturation { get; } [Field ("kCGImagePropertyExifSharpness")] NSString ExifSharpness { get; } [Field ("kCGImagePropertyExifDeviceSettingDescription")] NSString ExifDeviceSettingDescription { get; } [Field ("kCGImagePropertyExifSubjectDistRange")] NSString ExifSubjectDistRange { get; } [Field ("kCGImagePropertyExifImageUniqueID")] NSString ExifImageUniqueID { get; } [Field ("kCGImagePropertyExifGamma")] NSString ExifGamma { get; } [Since(4,3)][Field ("kCGImagePropertyExifCameraOwnerName")] NSString ExifCameraOwnerName { get; } [Since(4,3)][Field ("kCGImagePropertyExifBodySerialNumber")] NSString ExifBodySerialNumber { get; } [Since(4,3)][Field ("kCGImagePropertyExifLensSpecification")] NSString ExifLensSpecification { get; } [Since(4,3)][Field ("kCGImagePropertyExifLensMake")] NSString ExifLensMake { get; } [Since(4,3)][Field ("kCGImagePropertyExifLensModel")] NSString ExifLensModel { get; } [Since(4,3)][Field ("kCGImagePropertyExifLensSerialNumber")] NSString ExifLensSerialNumber { get; } // EXIF Auxiliary Dictionary Keys [Field ("kCGImagePropertyExifAuxLensInfo")] NSString ExifAuxLensInfo { get; } [Field ("kCGImagePropertyExifAuxLensModel")] NSString ExifAuxLensModel { get; } [Field ("kCGImagePropertyExifAuxSerialNumber")] NSString ExifAuxSerialNumber { get; } [Field ("kCGImagePropertyExifAuxLensID")] NSString ExifAuxLensID { get; } [Field ("kCGImagePropertyExifAuxLensSerialNumber")] NSString ExifAuxLensSerialNumber { get; } [Field ("kCGImagePropertyExifAuxImageNumber")] NSString ExifAuxImageNumber { get; } [Field ("kCGImagePropertyExifAuxFlashCompensation")] NSString ExifAuxFlashCompensation { get; } [Field ("kCGImagePropertyExifAuxOwnerName")] NSString ExifAuxOwnerName { get; } [Field ("kCGImagePropertyExifAuxFirmware")] NSString ExifAuxFirmware { get; } // GIF Dictionary Keys [Field ("kCGImagePropertyGIFLoopCount")] NSString GIFLoopCount { get; } [Field ("kCGImagePropertyGIFDelayTime")] NSString GIFDelayTime { get; } [Field ("kCGImagePropertyGIFImageColorMap")] NSString GIFImageColorMap { get; } [Field ("kCGImagePropertyGIFHasGlobalColorMap")] NSString GIFHasGlobalColorMap { get; } [Field ("kCGImagePropertyGIFUnclampedDelayTime")] NSString GIFUnclampedDelayTime { get; } // GPS Dictionary Keys [Field ("kCGImagePropertyGPSVersion")] NSString GPSVersion { get; } [Field ("kCGImagePropertyGPSLatitudeRef")] NSString GPSLatitudeRef { get; } [Field ("kCGImagePropertyGPSLatitude")] NSString GPSLatitude { get; } [Field ("kCGImagePropertyGPSLongitudeRef")] NSString GPSLongitudeRef { get; } [Field ("kCGImagePropertyGPSLongitude")] NSString GPSLongitude { get; } [Field ("kCGImagePropertyGPSAltitudeRef")] NSString GPSAltitudeRef { get; } [Field ("kCGImagePropertyGPSAltitude")] NSString GPSAltitude { get; } [Field ("kCGImagePropertyGPSTimeStamp")] NSString GPSTimeStamp { get; } [Field ("kCGImagePropertyGPSSatellites")] NSString GPSSatellites { get; } [Field ("kCGImagePropertyGPSStatus")] NSString GPSStatus { get; } [Field ("kCGImagePropertyGPSMeasureMode")] NSString GPSMeasureMode { get; } [Field ("kCGImagePropertyGPSDOP")] NSString GPSDOP { get; } [Field ("kCGImagePropertyGPSSpeedRef")] NSString GPSSpeedRef { get; } [Field ("kCGImagePropertyGPSSpeed")] NSString GPSSpeed { get; } [Field ("kCGImagePropertyGPSTrackRef")] NSString GPSTrackRef { get; } [Field ("kCGImagePropertyGPSTrack")] NSString GPSTrack { get; } [Field ("kCGImagePropertyGPSImgDirectionRef")] NSString GPSImgDirectionRef { get; } [Field ("kCGImagePropertyGPSImgDirection")] NSString GPSImgDirection { get; } [Field ("kCGImagePropertyGPSMapDatum")] NSString GPSMapDatum { get; } [Field ("kCGImagePropertyGPSDestLatitudeRef")] NSString GPSDestLatitudeRef { get; } [Field ("kCGImagePropertyGPSDestLatitude")] NSString GPSDestLatitude { get; } [Field ("kCGImagePropertyGPSDestLongitudeRef")] NSString GPSDestLongitudeRef { get; } [Field ("kCGImagePropertyGPSDestLongitude")] NSString GPSDestLongitude { get; } [Field ("kCGImagePropertyGPSDestBearingRef")] NSString GPSDestBearingRef { get; } [Field ("kCGImagePropertyGPSDestBearing")] NSString GPSDestBearing { get; } [Field ("kCGImagePropertyGPSDestDistanceRef")] NSString GPSDestDistanceRef { get; } [Field ("kCGImagePropertyGPSDestDistance")] NSString GPSDestDistance { get; } [Field ("kCGImagePropertyGPSAreaInformation")] NSString GPSAreaInformation { get; } [Field ("kCGImagePropertyGPSDateStamp")] NSString GPSDateStamp { get; } [Field ("kCGImagePropertyGPSDifferental")] NSString GPSDifferental { get; } // IPTC Dictionary Keys [Field ("kCGImagePropertyIPTCObjectTypeReference")] NSString IPTCObjectTypeReference { get; } [Field ("kCGImagePropertyIPTCObjectAttributeReference")] NSString IPTCObjectAttributeReference { get; } [Field ("kCGImagePropertyIPTCObjectName")] NSString IPTCObjectName { get; } [Field ("kCGImagePropertyIPTCEditStatus")] NSString IPTCEditStatus { get; } [Field ("kCGImagePropertyIPTCEditorialUpdate")] NSString IPTCEditorialUpdate { get; } [Field ("kCGImagePropertyIPTCUrgency")] NSString IPTCUrgency { get; } [Field ("kCGImagePropertyIPTCSubjectReference")] NSString IPTCSubjectReference { get; } [Field ("kCGImagePropertyIPTCCategory")] NSString IPTCCategory { get; } [Field ("kCGImagePropertyIPTCSupplementalCategory")] NSString IPTCSupplementalCategory { get; } [Field ("kCGImagePropertyIPTCFixtureIdentifier")] NSString IPTCFixtureIdentifier { get; } [Field ("kCGImagePropertyIPTCKeywords")] NSString IPTCKeywords { get; } [Field ("kCGImagePropertyIPTCContentLocationCode")] NSString IPTCContentLocationCode { get; } [Field ("kCGImagePropertyIPTCContentLocationName")] NSString IPTCContentLocationName { get; } [Field ("kCGImagePropertyIPTCReleaseDate")] NSString IPTCReleaseDate { get; } [Field ("kCGImagePropertyIPTCReleaseTime")] NSString IPTCReleaseTime { get; } [Field ("kCGImagePropertyIPTCExpirationDate")] NSString IPTCExpirationDate { get; } [Field ("kCGImagePropertyIPTCExpirationTime")] NSString IPTCExpirationTime { get; } [Field ("kCGImagePropertyIPTCSpecialInstructions")] NSString IPTCSpecialInstructions { get; } [Field ("kCGImagePropertyIPTCActionAdvised")] NSString IPTCActionAdvised { get; } [Field ("kCGImagePropertyIPTCReferenceService")] NSString IPTCReferenceService { get; } [Field ("kCGImagePropertyIPTCReferenceDate")] NSString IPTCReferenceDate { get; } [Field ("kCGImagePropertyIPTCReferenceNumber")] NSString IPTCReferenceNumber { get; } [Field ("kCGImagePropertyIPTCDateCreated")] NSString IPTCDateCreated { get; } [Field ("kCGImagePropertyIPTCTimeCreated")] NSString IPTCTimeCreated { get; } [Field ("kCGImagePropertyIPTCDigitalCreationDate")] NSString IPTCDigitalCreationDate { get; } [Field ("kCGImagePropertyIPTCDigitalCreationTime")] NSString IPTCDigitalCreationTime { get; } [Field ("kCGImagePropertyIPTCOriginatingProgram")] NSString IPTCOriginatingProgram { get; } [Field ("kCGImagePropertyIPTCProgramVersion")] NSString IPTCProgramVersion { get; } [Field ("kCGImagePropertyIPTCObjectCycle")] NSString IPTCObjectCycle { get; } [Field ("kCGImagePropertyIPTCByline")] NSString IPTCByline { get; } [Field ("kCGImagePropertyIPTCBylineTitle")] NSString IPTCBylineTitle { get; } [Field ("kCGImagePropertyIPTCCity")] NSString IPTCCity { get; } [Field ("kCGImagePropertyIPTCSubLocation")] NSString IPTCSubLocation { get; } [Field ("kCGImagePropertyIPTCProvinceState")] NSString IPTCProvinceState { get; } [Field ("kCGImagePropertyIPTCCountryPrimaryLocationCode")] NSString IPTCCountryPrimaryLocationCode { get; } [Field ("kCGImagePropertyIPTCCountryPrimaryLocationName")] NSString IPTCCountryPrimaryLocationName { get; } [Field ("kCGImagePropertyIPTCOriginalTransmissionReference")] NSString IPTCOriginalTransmissionReference { get; } [Field ("kCGImagePropertyIPTCHeadline")] NSString IPTCHeadline { get; } [Field ("kCGImagePropertyIPTCCredit")] NSString IPTCCredit { get; } [Field ("kCGImagePropertyIPTCSource")] NSString IPTCSource { get; } [Field ("kCGImagePropertyIPTCCopyrightNotice")] NSString IPTCCopyrightNotice { get; } [Field ("kCGImagePropertyIPTCContact")] NSString IPTCContact { get; } [Field ("kCGImagePropertyIPTCCaptionAbstract")] NSString IPTCCaptionAbstract { get; } [Field ("kCGImagePropertyIPTCWriterEditor")] NSString IPTCWriterEditor { get; } [Field ("kCGImagePropertyIPTCImageType")] NSString IPTCImageType { get; } [Field ("kCGImagePropertyIPTCImageOrientation")] NSString IPTCImageOrientation { get; } [Field ("kCGImagePropertyIPTCLanguageIdentifier")] NSString IPTCLanguageIdentifier { get; } [Field ("kCGImagePropertyIPTCStarRating")] NSString IPTCStarRating { get; } [Field ("kCGImagePropertyIPTCCreatorContactInfo")] NSString IPTCCreatorContactInfo { get; } [Field ("kCGImagePropertyIPTCRightsUsageTerms")] NSString IPTCRightsUsageTerms { get; } [Field ("kCGImagePropertyIPTCScene")] NSString IPTCScene { get; } // IPTC Creator Contact Info Dictionary Keys [Field ("kCGImagePropertyIPTCContactInfoCity")] NSString IPTCContactInfoCity { get; } [Field ("kCGImagePropertyIPTCContactInfoCountry")] NSString IPTCContactInfoCountry { get; } [Field ("kCGImagePropertyIPTCContactInfoAddress")] NSString IPTCContactInfoAddress { get; } [Field ("kCGImagePropertyIPTCContactInfoPostalCode")] NSString IPTCContactInfoPostalCode { get; } [Field ("kCGImagePropertyIPTCContactInfoStateProvince")] NSString IPTCContactInfoStateProvince { get; } [Field ("kCGImagePropertyIPTCContactInfoEmails")] NSString IPTCContactInfoEmails { get; } [Field ("kCGImagePropertyIPTCContactInfoPhones")] NSString IPTCContactInfoPhones { get; } [Field ("kCGImagePropertyIPTCContactInfoWebURLs")] NSString IPTCContactInfoWebURLs { get; } // JFIF Dictionary Keys [Field ("kCGImagePropertyJFIFVersion")] NSString JFIFVersion { get; } [Field ("kCGImagePropertyJFIFXDensity")] NSString JFIFXDensity { get; } [Field ("kCGImagePropertyJFIFYDensity")] NSString JFIFYDensity { get; } [Field ("kCGImagePropertyJFIFDensityUnit")] NSString JFIFDensityUnit { get; } [Field ("kCGImagePropertyJFIFIsProgressive")] NSString JFIFIsProgressive { get; } // PNG Dictionary Keys [Field ("kCGImagePropertyPNGGamma")] NSString PNGGamma { get; } [Field ("kCGImagePropertyPNGInterlaceType")] NSString PNGInterlaceType { get; } [Field ("kCGImagePropertyPNGXPixelsPerMeter")] NSString PNGXPixelsPerMeter { get; } [Field ("kCGImagePropertyPNGYPixelsPerMeter")] NSString PNGYPixelsPerMeter { get; } [Field ("kCGImagePropertyPNGsRGBIntent")] NSString PNGsRGBIntent { get; } [Field ("kCGImagePropertyPNGChromaticities")] NSString PNGChromaticities { get; } [Since (5,0)][Field ("kCGImagePropertyPNGAuthor")] NSString PNGAuthor { get; } [Since (5,0)][Field ("kCGImagePropertyPNGCopyright")] NSString PNGCopyright { get; } [Since (5,0)][Field ("kCGImagePropertyPNGCreationTime")] NSString PNGCreationTime { get; } [Since (5,0)][Field ("kCGImagePropertyPNGDescription")] NSString PNGDescription { get; } [Since (5,0)][Field ("kCGImagePropertyPNGModificationTime")] NSString PNGModificationTime { get; } [Since (5,0)][Field ("kCGImagePropertyPNGSoftware")] NSString PNGSoftware { get; } [Since (5,0)][Field ("kCGImagePropertyPNGTitle")] NSString PNGTitle { get; } // TIFF Dictionary Keys [Field ("kCGImagePropertyTIFFCompression")] NSString TIFFCompression { get; } [Field ("kCGImagePropertyTIFFPhotometricInterpretation")] NSString TIFFPhotometricInterpretation { get; } [Field ("kCGImagePropertyTIFFDocumentName")] NSString TIFFDocumentName { get; } [Field ("kCGImagePropertyTIFFImageDescription")] NSString TIFFImageDescription { get; } [Field ("kCGImagePropertyTIFFMake")] NSString TIFFMake { get; } [Field ("kCGImagePropertyTIFFModel")] NSString TIFFModel { get; } [Field ("kCGImagePropertyTIFFOrientation")] NSString TIFFOrientation { get; } [Field ("kCGImagePropertyTIFFXResolution")] NSString TIFFXResolution { get; } [Field ("kCGImagePropertyTIFFYResolution")] NSString TIFFYResolution { get; } [Field ("kCGImagePropertyTIFFResolutionUnit")] NSString TIFFResolutionUnit { get; } [Field ("kCGImagePropertyTIFFSoftware")] NSString TIFFSoftware { get; } [Field ("kCGImagePropertyTIFFTransferFunction")] NSString TIFFTransferFunction { get; } [Field ("kCGImagePropertyTIFFDateTime")] NSString TIFFDateTime { get; } [Field ("kCGImagePropertyTIFFArtist")] NSString TIFFArtist { get; } [Field ("kCGImagePropertyTIFFHostComputer")] NSString TIFFHostComputer { get; } [Field ("kCGImagePropertyTIFFWhitePoint")] NSString TIFFWhitePoint { get; } [Field ("kCGImagePropertyTIFFPrimaryChromaticities")] NSString TIFFPrimaryChromaticities { get; } // DNG Dictionary Keys [Field ("kCGImagePropertyDNGVersion")] NSString DNGVersion { get; } [Field ("kCGImagePropertyDNGBackwardVersion")] NSString DNGBackwardVersion { get; } [Field ("kCGImagePropertyDNGUniqueCameraModel")] NSString DNGUniqueCameraModel { get; } [Field ("kCGImagePropertyDNGLocalizedCameraModel")] NSString DNGLocalizedCameraModel { get; } [Field ("kCGImagePropertyDNGCameraSerialNumber")] NSString DNGCameraSerialNumber { get; } [Field ("kCGImagePropertyDNGLensInfo")] NSString DNGLensInfo { get; } // 8BIM Dictionary Keys [Field ("kCGImageProperty8BIMLayerNames")] NSString EightBIMLayerNames { get; } // CIFF Dictionary Keys [Field ("kCGImagePropertyCIFFDescription")] NSString CIFFDescription { get; } [Field ("kCGImagePropertyCIFFFirmware")] NSString CIFFFirmware { get; } [Field ("kCGImagePropertyCIFFOwnerName")] NSString CIFFOwnerName { get; } [Field ("kCGImagePropertyCIFFImageName")] NSString CIFFImageName { get; } [Field ("kCGImagePropertyCIFFImageFileName")] NSString CIFFImageFileName { get; } [Field ("kCGImagePropertyCIFFReleaseMethod")] NSString CIFFReleaseMethod { get; } [Field ("kCGImagePropertyCIFFReleaseTiming")] NSString CIFFReleaseTiming { get; } [Field ("kCGImagePropertyCIFFRecordID")] NSString CIFFRecordID { get; } [Field ("kCGImagePropertyCIFFSelfTimingTime")] NSString CIFFSelfTimingTime { get; } [Field ("kCGImagePropertyCIFFCameraSerialNumber")] NSString CIFFCameraSerialNumber { get; } [Field ("kCGImagePropertyCIFFImageSerialNumber")] NSString CIFFImageSerialNumber { get; } [Field ("kCGImagePropertyCIFFContinuousDrive")] NSString CIFFContinuousDrive { get; } [Field ("kCGImagePropertyCIFFFocusMode")] NSString CIFFFocusMode { get; } [Field ("kCGImagePropertyCIFFMeteringMode")] NSString CIFFMeteringMode { get; } [Field ("kCGImagePropertyCIFFShootingMode")] NSString CIFFShootingMode { get; } [Field ("kCGImagePropertyCIFFLensMaxMM")] NSString CIFFLensMaxMM { get; } [Field ("kCGImagePropertyCIFFLensMinMM")] NSString CIFFLensMinMM { get; } [Field ("kCGImagePropertyCIFFLensModel")] NSString CIFFLensModel { get; } [Field ("kCGImagePropertyCIFFWhiteBalanceIndex")] NSString CIFFWhiteBalanceIndex { get; } [Field ("kCGImagePropertyCIFFFlashExposureComp")] NSString CIFFFlashExposureComp { get; } [Field ("kCGImagePropertyCIFFMeasuredEV")] NSString CIFFMeasuredEV { get; } // Nikon Camera Dictionary Keys [Field ("kCGImagePropertyMakerNikonISOSetting")] NSString MakerNikonISOSetting { get; } [Field ("kCGImagePropertyMakerNikonColorMode")] NSString MakerNikonColorMode { get; } [Field ("kCGImagePropertyMakerNikonQuality")] NSString MakerNikonQuality { get; } [Field ("kCGImagePropertyMakerNikonWhiteBalanceMode")] NSString MakerNikonWhiteBalanceMode { get; } [Field ("kCGImagePropertyMakerNikonSharpenMode")] NSString MakerNikonSharpenMode { get; } [Field ("kCGImagePropertyMakerNikonFocusMode")] NSString MakerNikonFocusMode { get; } [Field ("kCGImagePropertyMakerNikonFlashSetting")] NSString MakerNikonFlashSetting { get; } [Field ("kCGImagePropertyMakerNikonISOSelection")] NSString MakerNikonISOSelection { get; } [Field ("kCGImagePropertyMakerNikonFlashExposureComp")] NSString MakerNikonFlashExposureComp { get; } [Field ("kCGImagePropertyMakerNikonImageAdjustment")] NSString MakerNikonImageAdjustment { get; } [Field ("kCGImagePropertyMakerNikonLensAdapter")] NSString MakerNikonLensAdapter { get; } [Field ("kCGImagePropertyMakerNikonLensType")] NSString MakerNikonLensType { get; } [Field ("kCGImagePropertyMakerNikonLensInfo")] NSString MakerNikonLensInfo { get; } [Field ("kCGImagePropertyMakerNikonFocusDistance")] NSString MakerNikonFocusDistance { get; } [Field ("kCGImagePropertyMakerNikonDigitalZoom")] NSString MakerNikonDigitalZoom { get; } [Field ("kCGImagePropertyMakerNikonShootingMode")] NSString MakerNikonShootingMode { get; } [Field ("kCGImagePropertyMakerNikonShutterCount")] NSString MakerNikonShutterCount { get; } [Field ("kCGImagePropertyMakerNikonCameraSerialNumber")] NSString MakerNikonCameraSerialNumber { get; } // Canon Camera Dictionary Keys [Field ("kCGImagePropertyMakerCanonOwnerName")] NSString MakerCanonOwnerName { get; } [Field ("kCGImagePropertyMakerCanonCameraSerialNumber")] NSString MakerCanonCameraSerialNumber { get; } [Field ("kCGImagePropertyMakerCanonImageSerialNumber")] NSString MakerCanonImageSerialNumber { get; } [Field ("kCGImagePropertyMakerCanonFlashExposureComp")] NSString MakerCanonFlashExposureComp { get; } [Field ("kCGImagePropertyMakerCanonContinuousDrive")] NSString MakerCanonContinuousDrive { get; } [Field ("kCGImagePropertyMakerCanonLensModel")] NSString MakerCanonLensModel { get; } [Field ("kCGImagePropertyMakerCanonFirmware")] NSString MakerCanonFirmware { get; } [Field ("kCGImagePropertyMakerCanonAspectRatioInfo")] NSString MakerCanonAspectRatioInfo { get; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Test; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Newtonsoft.Json.Linq; using Xunit; namespace ResourceGroups.Tests { public class LiveDeploymentTests : TestBase { const string DummyTemplateUri = "https://testtemplates.blob.core.windows.net/templates/dummytemplate.js"; const string GoodWebsiteTemplateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-webapp-managed-mysql/azuredeploy.json"; const string BadTemplateUri = "https://testtemplates.blob.core.windows.net/templates/bad-website-1.js"; const string GoodResourceId = "/subscriptions/45076d1d-a3e0-418b-8187-e1422a8cf5f4/resourceGroups/net-sdk-scenario-test-rg/providers/Microsoft.Resources/TemplateSpecs/storage-account-spec/versions/v1"; const string LocationWestEurope = "West Europe"; const string LocationSouthCentralUS = "South Central US"; public ResourceManagementClient GetResourceManagementClient(MockContext context, RecordedDelegatingHandler handler) { handler.IsPassThrough = true; return this.GetResourceManagementClientWithHandler(context, handler); } // TODO: Fix [Fact (Skip = "TODO: Re-record test")] public void CreateDummyDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = DummyTemplateUri }, Parameters = dictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); JObject json = JObject.Parse(handler.Request); Assert.NotNull(client.Deployments.Get(groupName, deploymentName)); } } [Fact()] public void CreateDeploymentWithStringTemplateAndParameters() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json")), Parameters = File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account-parameters.json")), Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var deployment = client.Deployments.Get(groupName, deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); } } [Fact] public void CreateDeploymentAndValidateProperties() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); string administratorLoginPassword = TestUtilities.GenerateGuid().ToString(); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse( @"{'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'administratorLogin': {'value': 'resourceAdmin'}, 'administratorLoginPassword': {'value': '" + administratorLoginPassword + "'}}"), Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); Assert.NotNull(deploymentCreateResult.Id); Assert.Equal(deploymentName, deploymentCreateResult.Name); TestUtilities.Wait(1000); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null); var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Tags); Assert.True(deploymentListResult.First().Tags.ContainsKey("tagKey1")); } } [Fact] public void CreateDeploymentWithResourceId() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId }, Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var deploymentCreateResult = client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); Assert.NotNull(deploymentCreateResult.Id); Assert.Equal(deploymentName, deploymentCreateResult.Name); TestUtilities.Wait(1000); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, null); var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodResourceId, deploymentGetResult.Properties.TemplateLink.Id); Assert.Equal(GoodResourceId, deploymentListResult.First().Properties.TemplateLink.Id); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Tags); Assert.True(deploymentListResult.First().Tags.ContainsKey("tagKey1")); } } [Fact] public void ValidateGoodDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); string administratorLoginPassword = TestUtilities.GenerateGuid().ToString(); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse( @"{'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'administratorLogin': {'value': 'resourceAdmin'}, 'administratorLoginPassword': {'value': '" + administratorLoginPassword + "'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(2, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty); } } [Fact] public void ValidateGoodDeploymentWithId() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId, }, Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); } } //TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void ValidateGoodDeploymentWithInlineTemplate() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); string administratorLoginPassword = TestUtilities.GenerateGuid().ToString(); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = File.ReadAllText(Path.Combine("ScenarioTests", "good-website.json")), Parameters = JObject.Parse( @"{'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'administratorLogin': {'value': 'resourceAdmin'}, 'administratorLoginPassword': {'value': '" + administratorLoginPassword + "'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); //Action var validationResult = client.Deployments.Validate(groupName, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); Assert.Equal(1, validationResult.Properties.Providers.Count); Assert.Equal("Microsoft.Web", validationResult.Properties.Providers[0].NamespaceProperty); } } [Fact] public void ValidateBadDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = BadTemplateUri, }, Parameters = JObject.Parse(@"{ 'siteName': {'value': 'mctest0101'},'hostingPlanName': {'value': 'mctest0101'},'siteMode': {'value': 'Limited'},'computeMode': {'value': 'Shared'},'siteLocation': {'value': 'North Europe'},'sku': {'value': 'Free'},'workerSize': {'value': '0'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); var result = client.Deployments.Validate(groupName, deploymentName, parameters); Assert.NotNull(result); Assert.Equal("InvalidTemplate", result.Error.Code); } } [Fact] public void CreateDeploymentCheckSuccessOperations() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csres"); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Id = GoodResourceId, }, Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); //Wait for deployment to complete TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); Assert.NotNull(operations.First().Id); Assert.NotNull(operations.First().OperationId); Assert.NotNull(operations.First().Properties); Assert.Null(operations.First().Properties.StatusMessage); } } // TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void CreateDummyDeploymentProducesOperations() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; var dictionary = new Dictionary<string, object> { {"string", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"securestring", new Dictionary<string, object>() { {"value", "myvalue"}, }}, {"int", new Dictionary<string, object>() { {"value", 42}, }}, {"bool", new Dictionary<string, object>() { {"value", true}, }} }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = DummyTemplateUri }, Parameters = dictionary, Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); Assert.NotNull(operations.First().Id); Assert.NotNull(operations.First().OperationId); Assert.NotNull(operations.First().Properties); } } // TODO: Fix [Fact(Skip = "TODO: Re-record test")] public void ListDeploymentsWorksWithFilter() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string resourceName = TestUtilities.GenerateName("csmr"); string administratorLoginPassword = TestUtilities.GenerateGuid().ToString(); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse( @"{'repoURL': {'value': 'https://github.com/devigned/az-roadshow-oss.git'}, 'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'administratorLogin': {'value': 'resourceAdmin'}, 'administratorLoginPassword': {'value': '" + administratorLoginPassword + "'}, 'databaseSkucapacity': {'value': 2}, 'databaseSkuName': {'value': 'GP_Gen5_2'}, 'databaseSkuSizeMB': {'value': 51200}, 'databaseSkuTier': {'value': 'GeneralPurpose'}, 'mysqlVersion': {'value': '5.6'}, 'databaseSkuFamily': {'value': 'Gen5'}}"), Mode = DeploymentMode.Incremental, } }; string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationWestEurope }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); var deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Running")); if (null == deploymentListResult|| deploymentListResult.Count() == 0) { deploymentListResult = client.Deployments.ListByResourceGroup(groupName, new ODataQuery<DeploymentExtendedFilter>(d => d.ProvisioningState == "Accepted")); } var deploymentGetResult = client.Deployments.Get(groupName, deploymentName); Assert.NotEmpty(deploymentListResult); Assert.Equal(deploymentName, deploymentGetResult.Name); Assert.Equal(deploymentName, deploymentListResult.First().Name); Assert.Equal(GoodWebsiteTemplateUri, deploymentGetResult.Properties.TemplateLink.Uri); Assert.Equal(GoodWebsiteTemplateUri, deploymentListResult.First().Properties.TemplateLink.Uri); Assert.NotNull(deploymentGetResult.Properties.ProvisioningState); Assert.NotNull(deploymentListResult.First().Properties.ProvisioningState); Assert.NotNull(deploymentGetResult.Properties.CorrelationId); Assert.NotNull(deploymentListResult.First().Properties.CorrelationId); Assert.Contains("mctest0101", deploymentGetResult.Properties.Parameters.ToString()); Assert.Contains("mctest0101", deploymentListResult.First().Properties.Parameters.ToString()); } } [Fact] public void CreateLargeWebDeploymentTemplateWorks() { var handler = new RecordedDelegatingHandler(); using (MockContext context = MockContext.Start(this.GetType())) { string resourceName = TestUtilities.GenerateName("csmr"); string groupName = TestUtilities.GenerateName("csmrg"); string deploymentName = TestUtilities.GenerateName("csmd"); string administratorLoginPassword = TestUtilities.GenerateGuid().ToString(); var client = GetResourceManagementClient(context, handler); var parameters = new Deployment { Properties = new DeploymentProperties() { TemplateLink = new TemplateLink { Uri = GoodWebsiteTemplateUri, }, Parameters = JObject.Parse( @"{'siteName': {'value': '" + resourceName + "'}, 'location': {'value': 'westus'}, 'administratorLogin': {'value': 'resourceAdmin'}, 'administratorLoginPassword': {'value': '" + administratorLoginPassword + "'}, 'databaseSkucapacity': {'value': 2}, 'databaseSkuName': {'value': 'GP_Gen5_2'}, 'databaseSkuSizeMB': {'value': 51200}, 'databaseSkuTier': {'value': 'GeneralPurpose'}, 'mysqlVersion': {'value': '5.6'}, 'databaseSkuFamily': {'value': 'Gen5'}}"), Mode = DeploymentMode.Incremental, } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = LiveDeploymentTests.LocationSouthCentralUS }); client.Deployments.CreateOrUpdate(groupName, deploymentName, parameters); // Wait until deployment completes TestUtilities.Wait(30000); var operations = client.DeploymentOperations.List(groupName, deploymentName, null); Assert.True(operations.Any()); } } [Fact] public void SubscriptionLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test"; string deploymentName = TestUtilities.GenerateName("csmd"); string resourceName = TestUtilities.GenerateName("csmr"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"), Mode = DeploymentMode.Incremental, }, Location = "WestUS", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); //Validate var validationResult = client.Deployments.ValidateAtSubscriptionScope(deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtSubscriptionScope(deploymentName, parameters); var deployment = client.Deployments.GetAtSubscriptionScope(deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); } } [Fact] public void ManagementGroupLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupId = "tag-mg-sdk"; string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new ScopedDeployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'tagsa051021'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtManagementGroupScope(groupId, deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtManagementGroupScope(groupId, deploymentName, parameters); var deployment = client.Deployments.GetAtManagementGroupScope(groupId, deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); } } [Fact] public void TenantLevelDeployment() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new ScopedDeployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))), Parameters = JObject.Parse("{'managementGroupId': {'value': 'net-sdk-testmg'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US 2", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtTenantScope(deploymentName, parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtTenantScope(deploymentName, parameters); var deployment = client.Deployments.GetAtTenantScope(deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtTenantScope(deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtTenant() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "tenant_level_template.json"))), Parameters = JObject.Parse("{'managementGroupId': {'value': 'net-sdk-testmg'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US 2", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: "", deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: "", deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: "", deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtManagementGroup() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupId = "tag-mg-sdk"; string deploymentName = TestUtilities.GenerateName("csharpsdktest"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "management_group_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'tagsa'}}"), Mode = DeploymentMode.Incremental, }, Location = "East US", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; var managementGroupScope = $"/providers/Microsoft.Management/managementGroups/{groupId}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: managementGroupScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: managementGroupScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: managementGroupScope, deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtSubscription() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test"; string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "subscription_level_template.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'armbuilddemo1803'}}"), Mode = DeploymentMode.Incremental, }, Location = "WestUS", Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); var subscriptionScope = $"/subscriptions/{client.SubscriptionId}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: subscriptionScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: subscriptionScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: subscriptionScope, deploymentName: deploymentName); Assert.Equal(4, deploymentOperations.Count()); } } [Fact] public void DeploymentWithScope_AtResourceGroup() { var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.Created }; using (MockContext context = MockContext.Start(this.GetType())) { var client = GetResourceManagementClient(context, handler); string groupName = "SDK-test-01"; string deploymentName = TestUtilities.GenerateName("csmd"); var parameters = new Deployment { Properties = new DeploymentProperties() { Template = JObject.Parse(File.ReadAllText(Path.Combine("ScenarioTests", "simple-storage-account.json"))), Parameters = JObject.Parse("{'storageAccountName': {'value': 'sdkTestStorageAccount1'}}"), Mode = DeploymentMode.Incremental, }, Tags = new Dictionary<string, string> { { "tagKey1", "tagValue1" } } }; client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = "WestUS" }); var resourceGroupScope = $"/subscriptions/{client.SubscriptionId}/resourceGroups/{groupName}"; //Validate var validationResult = client.Deployments.ValidateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters); //Assert Assert.Null(validationResult.Error); Assert.NotNull(validationResult.Properties); Assert.NotNull(validationResult.Properties.Providers); //Put deployment var deploymentResult = client.Deployments.CreateOrUpdateAtScope(scope: resourceGroupScope, deploymentName: deploymentName, parameters: parameters); var deployment = client.Deployments.GetAtScope(scope: resourceGroupScope, deploymentName: deploymentName); Assert.Equal("Succeeded", deployment.Properties.ProvisioningState); Assert.NotNull(deployment.Tags); Assert.True(deployment.Tags.ContainsKey("tagKey1")); var deploymentOperations = client.DeploymentOperations.ListAtScope(scope: resourceGroupScope, deploymentName: deploymentName); Assert.Equal(2, deploymentOperations.Count()); } } } }
namespace android.net { [global::MonoJavaBridge.JavaClass()] public partial class UrlQuerySanitizer : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static UrlQuerySanitizer() { InitJNI(); } protected UrlQuerySanitizer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class IllegalCharacterValueSanitizer : java.lang.Object, ValueSanitizer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static IllegalCharacterValueSanitizer() { InitJNI(); } protected IllegalCharacterValueSanitizer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _sanitize5347; public virtual global::java.lang.String sanitize(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer._sanitize5347, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer.staticClass, global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer._sanitize5347, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _IllegalCharacterValueSanitizer5348; public IllegalCharacterValueSanitizer(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer.staticClass, global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer._IllegalCharacterValueSanitizer5348, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } public static int SPACE_OK { get { return 1; } } public static int OTHER_WHITESPACE_OK { get { return 2; } } public static int NON_7_BIT_ASCII_OK { get { return 4; } } public static int DQUOTE_OK { get { return 8; } } public static int SQUOTE_OK { get { return 16; } } public static int LT_OK { get { return 32; } } public static int GT_OK { get { return 64; } } public static int AMP_OK { get { return 128; } } public static int PCT_OK { get { return 256; } } public static int NUL_OK { get { return 512; } } public static int SCRIPT_URL_OK { get { return 1024; } } public static int ALL_OK { get { return 2047; } } public static int ALL_WHITESPACE_OK { get { return 3; } } public static int ALL_ILLEGAL { get { return 0; } } public static int ALL_BUT_NUL_LEGAL { get { return 1535; } } public static int ALL_BUT_WHITESPACE_LEGAL { get { return 1532; } } public static int URL_LEGAL { get { return 404; } } public static int URL_AND_SPACE_LEGAL { get { return 405; } } public static int AMP_LEGAL { get { return 128; } } public static int AMP_AND_SPACE_LEGAL { get { return 129; } } public static int SPACE_LEGAL { get { return 1; } } public static int ALL_BUT_NUL_AND_ANGLE_BRACKETS_LEGAL { get { return 1439; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/UrlQuerySanitizer$IllegalCharacterValueSanitizer")); global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer._sanitize5347 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer.staticClass, "sanitize", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer._IllegalCharacterValueSanitizer5348 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.IllegalCharacterValueSanitizer.staticClass, "<init>", "(I)V"); } } [global::MonoJavaBridge.JavaClass()] public partial class ParameterValuePair : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ParameterValuePair() { InitJNI(); } protected ParameterValuePair(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _ParameterValuePair5349; public ParameterValuePair(android.net.UrlQuerySanitizer arg0, java.lang.String arg1, java.lang.String arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.UrlQuerySanitizer.ParameterValuePair.staticClass, global::android.net.UrlQuerySanitizer.ParameterValuePair._ParameterValuePair5349, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _mParameter5350; public global::java.lang.String mParameter { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _mValue5351; public global::java.lang.String mValue { get { return default(global::java.lang.String); } set { } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.UrlQuerySanitizer.ParameterValuePair.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/UrlQuerySanitizer$ParameterValuePair")); global::android.net.UrlQuerySanitizer.ParameterValuePair._ParameterValuePair5349 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.ParameterValuePair.staticClass, "<init>", "(Landroid/net/UrlQuerySanitizer;Ljava/lang/String;Ljava/lang/String;)V"); } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.net.UrlQuerySanitizer.ValueSanitizer_))] public interface ValueSanitizer : global::MonoJavaBridge.IJavaObject { global::java.lang.String sanitize(java.lang.String arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.net.UrlQuerySanitizer.ValueSanitizer))] public sealed partial class ValueSanitizer_ : java.lang.Object, ValueSanitizer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ValueSanitizer_() { InitJNI(); } internal ValueSanitizer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _sanitize5352; global::java.lang.String android.net.UrlQuerySanitizer.ValueSanitizer.sanitize(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.ValueSanitizer_._sanitize5352, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.ValueSanitizer_.staticClass, global::android.net.UrlQuerySanitizer.ValueSanitizer_._sanitize5352, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.UrlQuerySanitizer.ValueSanitizer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/UrlQuerySanitizer$ValueSanitizer")); global::android.net.UrlQuerySanitizer.ValueSanitizer_._sanitize5352 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.ValueSanitizer_.staticClass, "sanitize", "(Ljava/lang/String;)Ljava/lang/String;"); } } internal static global::MonoJavaBridge.MethodId _clear5353; protected virtual void clear() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._clear5353); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._clear5353); } internal static global::MonoJavaBridge.MethodId _getValue5354; public virtual global::java.lang.String getValue(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getValue5354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getValue5354, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _unescape5355; public virtual global::java.lang.String unescape(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._unescape5355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._unescape5355, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isHexDigit5356; protected virtual bool isHexDigit(char arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._isHexDigit5356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._isHexDigit5356, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getUnregisteredParameterValueSanitizer5357; public virtual global::android.net.UrlQuerySanitizer.ValueSanitizer getUnregisteredParameterValueSanitizer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getUnregisteredParameterValueSanitizer5357)) as android.net.UrlQuerySanitizer.ValueSanitizer; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getUnregisteredParameterValueSanitizer5357)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _setUnregisteredParameterValueSanitizer5358; public virtual void setUnregisteredParameterValueSanitizer(android.net.UrlQuerySanitizer.ValueSanitizer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._setUnregisteredParameterValueSanitizer5358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._setUnregisteredParameterValueSanitizer5358, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getAllIllegal5359; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAllIllegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAllIllegal5359)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getAllButNulLegal5360; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAllButNulLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAllButNulLegal5360)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getAllButWhitespaceLegal5361; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAllButWhitespaceLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAllButWhitespaceLegal5361)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getUrlLegal5362; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getUrlLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getUrlLegal5362)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getUrlAndSpaceLegal5363; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getUrlAndSpaceLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getUrlAndSpaceLegal5363)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getAmpLegal5364; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAmpLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAmpLegal5364)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getAmpAndSpaceLegal5365; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAmpAndSpaceLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAmpAndSpaceLegal5365)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getSpaceLegal5366; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getSpaceLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getSpaceLegal5366)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getAllButNulAndAngleBracketsLegal5367; public static global::android.net.UrlQuerySanitizer.ValueSanitizer getAllButNulAndAngleBracketsLegal() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallStaticObjectMethod(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAllButNulAndAngleBracketsLegal5367)) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _parseUrl5368; public virtual void parseUrl(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._parseUrl5368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._parseUrl5368, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _parseQuery5369; public virtual void parseQuery(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._parseQuery5369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._parseQuery5369, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getParameterSet5370; public virtual global::java.util.Set getParameterSet() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getParameterSet5370)) as java.util.Set; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.Set>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getParameterSet5370)) as java.util.Set; } internal static global::MonoJavaBridge.MethodId _getParameterList5371; public virtual global::java.util.List getParameterList() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getParameterList5371)) as java.util.List; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.util.List>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getParameterList5371)) as java.util.List; } internal static global::MonoJavaBridge.MethodId _hasParameter5372; public virtual bool hasParameter(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._hasParameter5372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._hasParameter5372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _registerParameter5373; public virtual void registerParameter(java.lang.String arg0, android.net.UrlQuerySanitizer.ValueSanitizer arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._registerParameter5373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._registerParameter5373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _registerParameters5374; public virtual void registerParameters(java.lang.String[] arg0, android.net.UrlQuerySanitizer.ValueSanitizer arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._registerParameters5374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._registerParameters5374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setAllowUnregisteredParamaters5375; public virtual void setAllowUnregisteredParamaters(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._setAllowUnregisteredParamaters5375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._setAllowUnregisteredParamaters5375, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getAllowUnregisteredParamaters5376; public virtual bool getAllowUnregisteredParamaters() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getAllowUnregisteredParamaters5376); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getAllowUnregisteredParamaters5376); } internal static global::MonoJavaBridge.MethodId _setPreferFirstRepeatedParameter5377; public virtual void setPreferFirstRepeatedParameter(bool arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._setPreferFirstRepeatedParameter5377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._setPreferFirstRepeatedParameter5377, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getPreferFirstRepeatedParameter5378; public virtual bool getPreferFirstRepeatedParameter() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getPreferFirstRepeatedParameter5378); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getPreferFirstRepeatedParameter5378); } internal static global::MonoJavaBridge.MethodId _parseEntry5379; protected virtual void parseEntry(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._parseEntry5379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._parseEntry5379, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _addSanitizedEntry5380; protected virtual void addSanitizedEntry(java.lang.String arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._addSanitizedEntry5380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._addSanitizedEntry5380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getValueSanitizer5381; public virtual global::android.net.UrlQuerySanitizer.ValueSanitizer getValueSanitizer(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getValueSanitizer5381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.UrlQuerySanitizer.ValueSanitizer; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getValueSanitizer5381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _getEffectiveValueSanitizer5382; public virtual global::android.net.UrlQuerySanitizer.ValueSanitizer getEffectiveValueSanitizer(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._getEffectiveValueSanitizer5382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.UrlQuerySanitizer.ValueSanitizer; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.net.UrlQuerySanitizer.ValueSanitizer>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._getEffectiveValueSanitizer5382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.net.UrlQuerySanitizer.ValueSanitizer; } internal static global::MonoJavaBridge.MethodId _decodeHexDigit5383; protected virtual int decodeHexDigit(char arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer._decodeHexDigit5383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._decodeHexDigit5383, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _UrlQuerySanitizer5384; public UrlQuerySanitizer() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._UrlQuerySanitizer5384); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _UrlQuerySanitizer5385; public UrlQuerySanitizer(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.net.UrlQuerySanitizer.staticClass, global::android.net.UrlQuerySanitizer._UrlQuerySanitizer5385, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.net.UrlQuerySanitizer.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/net/UrlQuerySanitizer")); global::android.net.UrlQuerySanitizer._clear5353 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "clear", "()V"); global::android.net.UrlQuerySanitizer._getValue5354 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getValue", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.UrlQuerySanitizer._unescape5355 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "unescape", "(Ljava/lang/String;)Ljava/lang/String;"); global::android.net.UrlQuerySanitizer._isHexDigit5356 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "isHexDigit", "(C)Z"); global::android.net.UrlQuerySanitizer._getUnregisteredParameterValueSanitizer5357 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getUnregisteredParameterValueSanitizer", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._setUnregisteredParameterValueSanitizer5358 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "setUnregisteredParameterValueSanitizer", "(Landroid/net/UrlQuerySanitizer$ValueSanitizer;)V"); global::android.net.UrlQuerySanitizer._getAllIllegal5359 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAllIllegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getAllButNulLegal5360 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAllButNulLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getAllButWhitespaceLegal5361 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAllButWhitespaceLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getUrlLegal5362 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getUrlLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getUrlAndSpaceLegal5363 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getUrlAndSpaceLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getAmpLegal5364 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAmpLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getAmpAndSpaceLegal5365 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAmpAndSpaceLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getSpaceLegal5366 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getSpaceLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getAllButNulAndAngleBracketsLegal5367 = @__env.GetStaticMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAllButNulAndAngleBracketsLegal", "()Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._parseUrl5368 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "parseUrl", "(Ljava/lang/String;)V"); global::android.net.UrlQuerySanitizer._parseQuery5369 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "parseQuery", "(Ljava/lang/String;)V"); global::android.net.UrlQuerySanitizer._getParameterSet5370 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getParameterSet", "()Ljava/util/Set;"); global::android.net.UrlQuerySanitizer._getParameterList5371 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getParameterList", "()Ljava/util/List;"); global::android.net.UrlQuerySanitizer._hasParameter5372 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "hasParameter", "(Ljava/lang/String;)Z"); global::android.net.UrlQuerySanitizer._registerParameter5373 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "registerParameter", "(Ljava/lang/String;Landroid/net/UrlQuerySanitizer$ValueSanitizer;)V"); global::android.net.UrlQuerySanitizer._registerParameters5374 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "registerParameters", "([Ljava/lang/String;Landroid/net/UrlQuerySanitizer$ValueSanitizer;)V"); global::android.net.UrlQuerySanitizer._setAllowUnregisteredParamaters5375 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "setAllowUnregisteredParamaters", "(Z)V"); global::android.net.UrlQuerySanitizer._getAllowUnregisteredParamaters5376 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getAllowUnregisteredParamaters", "()Z"); global::android.net.UrlQuerySanitizer._setPreferFirstRepeatedParameter5377 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "setPreferFirstRepeatedParameter", "(Z)V"); global::android.net.UrlQuerySanitizer._getPreferFirstRepeatedParameter5378 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getPreferFirstRepeatedParameter", "()Z"); global::android.net.UrlQuerySanitizer._parseEntry5379 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "parseEntry", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.net.UrlQuerySanitizer._addSanitizedEntry5380 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "addSanitizedEntry", "(Ljava/lang/String;Ljava/lang/String;)V"); global::android.net.UrlQuerySanitizer._getValueSanitizer5381 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getValueSanitizer", "(Ljava/lang/String;)Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._getEffectiveValueSanitizer5382 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "getEffectiveValueSanitizer", "(Ljava/lang/String;)Landroid/net/UrlQuerySanitizer$ValueSanitizer;"); global::android.net.UrlQuerySanitizer._decodeHexDigit5383 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "decodeHexDigit", "(C)I"); global::android.net.UrlQuerySanitizer._UrlQuerySanitizer5384 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "<init>", "()V"); global::android.net.UrlQuerySanitizer._UrlQuerySanitizer5385 = @__env.GetMethodIDNoThrow(global::android.net.UrlQuerySanitizer.staticClass, "<init>", "(Ljava/lang/String;)V"); } } }
namespace android.media { [global::MonoJavaBridge.JavaClass()] public partial class AudioTrack : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected AudioTrack(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_))] public partial interface OnPlaybackPositionUpdateListener : global::MonoJavaBridge.IJavaObject { void onMarkerReached(android.media.AudioTrack arg0); void onPeriodicNotification(android.media.AudioTrack arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.media.AudioTrack.OnPlaybackPositionUpdateListener))] internal sealed partial class OnPlaybackPositionUpdateListener_ : java.lang.Object, OnPlaybackPositionUpdateListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnPlaybackPositionUpdateListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.media.AudioTrack.OnPlaybackPositionUpdateListener.onMarkerReached(android.media.AudioTrack arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, "onMarkerReached", "(Landroid/media/AudioTrack;)V", ref global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; void android.media.AudioTrack.OnPlaybackPositionUpdateListener.onPeriodicNotification(android.media.AudioTrack arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass, "onPeriodicNotification", "(Landroid/media/AudioTrack;)V", ref global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnPlaybackPositionUpdateListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.media.AudioTrack.OnPlaybackPositionUpdateListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioTrack$OnPlaybackPositionUpdateListener")); } } private static global::MonoJavaBridge.MethodId _m0; protected override void finalize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "finalize", "()V", ref global::android.media.AudioTrack._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual int write(byte[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "write", "([BII)I", ref global::android.media.AudioTrack._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m2; public virtual int write(short[] arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "write", "([SII)I", ref global::android.media.AudioTrack._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void stop() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "stop", "()V", ref global::android.media.AudioTrack._m3); } public new int State { get { return getState(); } set { setState(value); } } private static global::MonoJavaBridge.MethodId _m4; public virtual int getState() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getState", "()I", ref global::android.media.AudioTrack._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual void flush() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "flush", "()V", ref global::android.media.AudioTrack._m5); } private static global::MonoJavaBridge.MethodId _m6; protected virtual void setState(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "setState", "(I)V", ref global::android.media.AudioTrack._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m7; public virtual void release() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "release", "()V", ref global::android.media.AudioTrack._m7); } private static global::MonoJavaBridge.MethodId _m8; public virtual void play() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "play", "()V", ref global::android.media.AudioTrack._m8); } public new int SampleRate { get { return getSampleRate(); } } private static global::MonoJavaBridge.MethodId _m9; public virtual int getSampleRate() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getSampleRate", "()I", ref global::android.media.AudioTrack._m9); } public new int AudioFormat { get { return getAudioFormat(); } } private static global::MonoJavaBridge.MethodId _m10; public virtual int getAudioFormat() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getAudioFormat", "()I", ref global::android.media.AudioTrack._m10); } public new int ChannelConfiguration { get { return getChannelConfiguration(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual int getChannelConfiguration() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getChannelConfiguration", "()I", ref global::android.media.AudioTrack._m11); } public new int ChannelCount { get { return getChannelCount(); } } private static global::MonoJavaBridge.MethodId _m12; public virtual int getChannelCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getChannelCount", "()I", ref global::android.media.AudioTrack._m12); } public new int NotificationMarkerPosition { get { return getNotificationMarkerPosition(); } set { setNotificationMarkerPosition(value); } } private static global::MonoJavaBridge.MethodId _m13; public virtual int getNotificationMarkerPosition() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getNotificationMarkerPosition", "()I", ref global::android.media.AudioTrack._m13); } public new int PositionNotificationPeriod { get { return getPositionNotificationPeriod(); } set { setPositionNotificationPeriod(value); } } private static global::MonoJavaBridge.MethodId _m14; public virtual int getPositionNotificationPeriod() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getPositionNotificationPeriod", "()I", ref global::android.media.AudioTrack._m14); } private static global::MonoJavaBridge.MethodId _m15; public static int getMinBufferSize(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.AudioTrack._m15.native == global::System.IntPtr.Zero) global::android.media.AudioTrack._m15 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMinBufferSize", "(III)I"); return @__env.CallStaticIntMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m16; public virtual int setNotificationMarkerPosition(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setNotificationMarkerPosition", "(I)I", ref global::android.media.AudioTrack._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual int setPositionNotificationPeriod(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setPositionNotificationPeriod", "(I)I", ref global::android.media.AudioTrack._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static float MinVolume { get { return getMinVolume(); } } private static global::MonoJavaBridge.MethodId _m18; public static float getMinVolume() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.AudioTrack._m18.native == global::System.IntPtr.Zero) global::android.media.AudioTrack._m18 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMinVolume", "()F"); return @__env.CallStaticFloatMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._m18); } public static float MaxVolume { get { return getMaxVolume(); } } private static global::MonoJavaBridge.MethodId _m19; public static float getMaxVolume() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.AudioTrack._m19.native == global::System.IntPtr.Zero) global::android.media.AudioTrack._m19 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getMaxVolume", "()F"); return @__env.CallStaticFloatMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._m19); } public new int PlaybackRate { get { return getPlaybackRate(); } set { setPlaybackRate(value); } } private static global::MonoJavaBridge.MethodId _m20; public virtual int getPlaybackRate() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getPlaybackRate", "()I", ref global::android.media.AudioTrack._m20); } public new int StreamType { get { return getStreamType(); } } private static global::MonoJavaBridge.MethodId _m21; public virtual int getStreamType() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getStreamType", "()I", ref global::android.media.AudioTrack._m21); } public new int PlayState { get { return getPlayState(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual int getPlayState() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getPlayState", "()I", ref global::android.media.AudioTrack._m22); } protected new int NativeFrameCount { get { return getNativeFrameCount(); } } private static global::MonoJavaBridge.MethodId _m23; protected virtual int getNativeFrameCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getNativeFrameCount", "()I", ref global::android.media.AudioTrack._m23); } public new int PlaybackHeadPosition { get { return getPlaybackHeadPosition(); } set { setPlaybackHeadPosition(value); } } private static global::MonoJavaBridge.MethodId _m24; public virtual int getPlaybackHeadPosition() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "getPlaybackHeadPosition", "()I", ref global::android.media.AudioTrack._m24); } private static global::MonoJavaBridge.MethodId _m25; public static int getNativeOutputSampleRate(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.AudioTrack._m25.native == global::System.IntPtr.Zero) global::android.media.AudioTrack._m25 = @__env.GetStaticMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "getNativeOutputSampleRate", "(I)I"); return @__env.CallStaticIntMethod(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; public virtual void setPlaybackPositionUpdateListener(android.media.AudioTrack.OnPlaybackPositionUpdateListener arg0, android.os.Handler arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "setPlaybackPositionUpdateListener", "(Landroid/media/AudioTrack$OnPlaybackPositionUpdateListener;Landroid/os/Handler;)V", ref global::android.media.AudioTrack._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::android.media.AudioTrack.OnPlaybackPositionUpdateListener PlaybackPositionUpdateListener { set { setPlaybackPositionUpdateListener(value); } } private static global::MonoJavaBridge.MethodId _m27; public virtual void setPlaybackPositionUpdateListener(android.media.AudioTrack.OnPlaybackPositionUpdateListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "setPlaybackPositionUpdateListener", "(Landroid/media/AudioTrack$OnPlaybackPositionUpdateListener;)V", ref global::android.media.AudioTrack._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m28; public virtual int setStereoVolume(float arg0, float arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setStereoVolume", "(FF)I", ref global::android.media.AudioTrack._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m29; public virtual int setPlaybackRate(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setPlaybackRate", "(I)I", ref global::android.media.AudioTrack._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public virtual int setPlaybackHeadPosition(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setPlaybackHeadPosition", "(I)I", ref global::android.media.AudioTrack._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual int setLoopPoints(int arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "setLoopPoints", "(III)I", ref global::android.media.AudioTrack._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m32; public virtual void pause() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.media.AudioTrack.staticClass, "pause", "()V", ref global::android.media.AudioTrack._m32); } private static global::MonoJavaBridge.MethodId _m33; public virtual int reloadStaticData() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.media.AudioTrack.staticClass, "reloadStaticData", "()I", ref global::android.media.AudioTrack._m33); } private static global::MonoJavaBridge.MethodId _m34; public AudioTrack(int arg0, int arg1, int arg2, int arg3, int arg4, int arg5) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.media.AudioTrack._m34.native == global::System.IntPtr.Zero) global::android.media.AudioTrack._m34 = @__env.GetMethodIDNoThrow(global::android.media.AudioTrack.staticClass, "<init>", "(IIIIII)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.media.AudioTrack.staticClass, global::android.media.AudioTrack._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); Init(@__env, handle); } public static int PLAYSTATE_STOPPED { get { return 1; } } public static int PLAYSTATE_PAUSED { get { return 2; } } public static int PLAYSTATE_PLAYING { get { return 3; } } public static int MODE_STATIC { get { return 0; } } public static int MODE_STREAM { get { return 1; } } public static int STATE_UNINITIALIZED { get { return 0; } } public static int STATE_INITIALIZED { get { return 1; } } public static int STATE_NO_STATIC_DATA { get { return 2; } } public static int SUCCESS { get { return 0; } } public static int ERROR { get { return -1; } } public static int ERROR_BAD_VALUE { get { return -2; } } public static int ERROR_INVALID_OPERATION { get { return -3; } } static AudioTrack() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.media.AudioTrack.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/media/AudioTrack")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using JCG = J2N.Collections.Generic; namespace YAF.Lucene.Net.Search.Spans { /* * 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 AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext; using IBits = YAF.Lucene.Net.Util.IBits; using IndexReader = YAF.Lucene.Net.Index.IndexReader; using Term = YAF.Lucene.Net.Index.Term; using TermContext = YAF.Lucene.Net.Index.TermContext; using ToStringUtils = YAF.Lucene.Net.Util.ToStringUtils; /// <summary> /// Matches the union of its clauses. </summary> public class SpanOrQuery : SpanQuery #if FEATURE_CLONEABLE , System.ICloneable #endif { private readonly IList<SpanQuery> clauses; private string field; /// <summary> /// Construct a <see cref="SpanOrQuery"/> merging the provided <paramref name="clauses"/>. </summary> public SpanOrQuery(params SpanQuery[] clauses) : this((IList<SpanQuery>)clauses) { } // LUCENENET specific overload. // LUCENENET TODO: API - This constructor was added to eliminate casting with PayloadSpanUtil. Make public? // It would be more useful if the type was an IEnumerable<SpanQuery>, but // need to rework the allocation below. It would also be better to change AddClause() to Add() to make // the C# collection initializer function. internal SpanOrQuery(IList<SpanQuery> clauses) { // copy clauses array into an ArrayList this.clauses = new JCG.List<SpanQuery>(clauses.Count); for (int i = 0; i < clauses.Count; i++) { AddClause(clauses[i]); } } /// <summary> /// Adds a <paramref name="clause"/> to this query </summary> public void AddClause(SpanQuery clause) { if (field == null) { field = clause.Field; } else if (clause.Field != null && !clause.Field.Equals(field, StringComparison.Ordinal)) { throw new System.ArgumentException("Clauses must have same field."); } this.clauses.Add(clause); } /// <summary> /// Return the clauses whose spans are matched. </summary> public virtual SpanQuery[] GetClauses() { return clauses.ToArray(); } public override string Field => field; public override void ExtractTerms(ISet<Term> terms) { foreach (SpanQuery clause in clauses) { clause.ExtractTerms(terms); } } public override object Clone() { int sz = clauses.Count; SpanQuery[] newClauses = new SpanQuery[sz]; for (int i = 0; i < sz; i++) { newClauses[i] = (SpanQuery)clauses[i].Clone(); } SpanOrQuery soq = new SpanOrQuery(newClauses); soq.Boost = Boost; return soq; } public override Query Rewrite(IndexReader reader) { SpanOrQuery clone = null; for (int i = 0; i < clauses.Count; i++) { SpanQuery c = clauses[i]; SpanQuery query = (SpanQuery)c.Rewrite(reader); if (query != c) // clause rewrote: must clone { if (clone == null) { clone = (SpanOrQuery)this.Clone(); } clone.clauses[i] = query; } } if (clone != null) { return clone; // some clauses rewrote } else { return this; // no clauses rewrote } } public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); buffer.Append("spanOr(["); bool first = true; foreach (SpanQuery clause in clauses) { if (!first) buffer.Append(", "); buffer.Append(clause.ToString(field)); first = false; } buffer.Append("])"); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } public override bool Equals(object o) { if (this == o) { return true; } if (o == null || this.GetType() != o.GetType()) { return false; } SpanOrQuery that = (SpanOrQuery)o; if (!clauses.Equals(that.clauses)) { return false; } return Boost == that.Boost; } public override int GetHashCode() { //If this doesn't work, hash all elemnts together instead. This version was used to reduce time complexity int h = clauses.GetHashCode(); h ^= (h << 10) | ((int)(((uint)h) >> 23)); h ^= J2N.BitConversion.SingleToRawInt32Bits(Boost); return h; } private class SpanQueue : Util.PriorityQueue<Spans> { private readonly SpanOrQuery outerInstance; public SpanQueue(SpanOrQuery outerInstance, int size) : base(size) { this.outerInstance = outerInstance; } protected internal override bool LessThan(Spans spans1, Spans spans2) { if (spans1.Doc == spans2.Doc) { if (spans1.Start == spans2.Start) { return spans1.End < spans2.End; } else { return spans1.Start < spans2.Start; } } else { return spans1.Doc < spans2.Doc; } } } public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { if (clauses.Count == 1) // optimize 1-clause case { return (clauses[0]).GetSpans(context, acceptDocs, termContexts); } return new SpansAnonymousInnerClassHelper(this, context, acceptDocs, termContexts); } private class SpansAnonymousInnerClassHelper : Spans { private readonly SpanOrQuery outerInstance; private AtomicReaderContext context; private IBits acceptDocs; private IDictionary<Term, TermContext> termContexts; public SpansAnonymousInnerClassHelper(SpanOrQuery outerInstance, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts) { this.outerInstance = outerInstance; this.context = context; this.acceptDocs = acceptDocs; this.termContexts = termContexts; queue = null; } private SpanQueue queue; private long cost; private bool InitSpanQueue(int target) { queue = new SpanQueue(outerInstance, outerInstance.clauses.Count); foreach (var clause in outerInstance.clauses) { Spans spans = clause.GetSpans(context, acceptDocs, termContexts); cost += spans.GetCost(); if (((target == -1) && spans.Next()) || ((target != -1) && spans.SkipTo(target))) { queue.Add(spans); } } return queue.Count != 0; } public override bool Next() { if (queue == null) { return InitSpanQueue(-1); } if (queue.Count == 0) // all done { return false; } if (Top.Next()) // move to next { queue.UpdateTop(); return true; } queue.Pop(); // exhausted a clause return queue.Count != 0; } private Spans Top { get { return queue.Top; } } public override bool SkipTo(int target) { if (queue == null) { return InitSpanQueue(target); } bool skipCalled = false; while (queue.Count != 0 && Top.Doc < target) { if (Top.SkipTo(target)) { queue.UpdateTop(); } else { queue.Pop(); } skipCalled = true; } if (skipCalled) { return queue.Count != 0; } return Next(); } public override int Doc { get { return Top.Doc; } } public override int Start { get { return Top.Start; } } public override int End { get { return Top.End; } } public override ICollection<byte[]> GetPayload() { List<byte[]> result = null; Spans theTop = Top; if (theTop != null && theTop.IsPayloadAvailable) { result = new List<byte[]>(theTop.GetPayload()); } return result; } public override bool IsPayloadAvailable { get { Spans top = Top; return top != null && top.IsPayloadAvailable; } } public override string ToString() { return "spans(" + outerInstance + ")@" + ((queue == null) ? "START" : (queue.Count > 0 ? (Doc + ":" + Start + "-" + End) : "END")); } public override long GetCost() { return cost; } } } }
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 frmStockTakeCSV { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockTakeCSV() : base() { Load += frmStockTakeCSV_Load; KeyPress += frmStockTakeCSV_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.PictureBox picBC; private System.Windows.Forms.CheckBox withEventsField_chkPic; public System.Windows.Forms.CheckBox chkPic { get { return withEventsField_chkPic; } set { if (withEventsField_chkPic != null) { withEventsField_chkPic.CheckStateChanged -= chkPic_CheckStateChanged; } withEventsField_chkPic = value; if (withEventsField_chkPic != null) { withEventsField_chkPic.CheckStateChanged += chkPic_CheckStateChanged; } } } private System.Windows.Forms.Button withEventsField_cmdDiff; public System.Windows.Forms.Button cmdDiff { get { return withEventsField_cmdDiff; } set { if (withEventsField_cmdDiff != null) { withEventsField_cmdDiff.Click -= cmdDiff_Click; } withEventsField_cmdDiff = value; if (withEventsField_cmdDiff != null) { withEventsField_cmdDiff.Click += cmdDiff_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } public System.Windows.Forms.Panel picButtons; private System.Windows.Forms.Button withEventsField_cmdsearch; public System.Windows.Forms.Button cmdsearch { get { return withEventsField_cmdsearch; } set { if (withEventsField_cmdsearch != null) { withEventsField_cmdsearch.Click -= cmdsearch_Click; } withEventsField_cmdsearch = value; if (withEventsField_cmdsearch != null) { withEventsField_cmdsearch.Click += cmdsearch_Click; } } } public System.Windows.Forms.TextBox txtqty; public System.Windows.Forms.TextBox txtdesc; public System.Windows.Forms.TextBox txtcode; public System.Windows.Forms.DataGrid DataGrid1; public System.Windows.Forms.PictureBox imgBC; public System.Windows.Forms.Label Label3; public System.Windows.Forms.Label Label2; 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(frmStockTakeCSV)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.picBC = new System.Windows.Forms.PictureBox(); this.chkPic = new System.Windows.Forms.CheckBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdDiff = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this.cmdsearch = new System.Windows.Forms.Button(); this.txtqty = new System.Windows.Forms.TextBox(); this.txtdesc = new System.Windows.Forms.TextBox(); this.txtcode = new System.Windows.Forms.TextBox(); this.DataGrid1 = new System.Windows.Forms.DataGrid(); this.imgBC = new System.Windows.Forms.PictureBox(); this.Label3 = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; ((System.ComponentModel.ISupportInitialize)this.DataGrid1).BeginInit(); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Text = "StockTake"; this.ClientSize = new System.Drawing.Size(570, 390); this.Location = new System.Drawing.Point(3, 29); this.Icon = (System.Drawing.Icon)resources.GetObject("frmStockTakeCSV.Icon"); 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.ControlBox = true; 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 = "frmStockTakeCSV"; this.picBC.Size = new System.Drawing.Size(265, 300); this.picBC.Location = new System.Drawing.Point(576, 472); this.picBC.TabIndex = 11; this.picBC.Visible = false; this.picBC.Dock = System.Windows.Forms.DockStyle.None; this.picBC.BackColor = System.Drawing.SystemColors.Control; this.picBC.CausesValidation = true; this.picBC.Enabled = true; this.picBC.ForeColor = System.Drawing.SystemColors.ControlText; this.picBC.Cursor = System.Windows.Forms.Cursors.Default; this.picBC.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picBC.TabStop = true; this.picBC.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.picBC.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picBC.Name = "picBC"; this.chkPic.Text = "Show Pictures"; this.chkPic.Size = new System.Drawing.Size(89, 17); this.chkPic.Location = new System.Drawing.Point(472, 360); this.chkPic.TabIndex = 10; this.chkPic.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft; this.chkPic.FlatStyle = System.Windows.Forms.FlatStyle.Standard; this.chkPic.BackColor = System.Drawing.SystemColors.Control; this.chkPic.CausesValidation = true; this.chkPic.Enabled = true; this.chkPic.ForeColor = System.Drawing.SystemColors.ControlText; this.chkPic.Cursor = System.Windows.Forms.Cursors.Default; this.chkPic.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkPic.Appearance = System.Windows.Forms.Appearance.Normal; this.chkPic.TabStop = true; this.chkPic.CheckState = System.Windows.Forms.CheckState.Unchecked; this.chkPic.Visible = true; this.chkPic.Name = "chkPic"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(570, 38); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 7; 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.cmdDiff.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdDiff.Text = "Show Difference"; this.cmdDiff.Size = new System.Drawing.Size(97, 29); this.cmdDiff.Location = new System.Drawing.Point(360, 2); this.cmdDiff.TabIndex = 12; this.cmdDiff.TabStop = false; this.cmdDiff.BackColor = System.Drawing.SystemColors.Control; this.cmdDiff.CausesValidation = true; this.cmdDiff.Enabled = true; this.cmdDiff.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDiff.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDiff.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDiff.Name = "cmdDiff"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "Save and E&xit"; this.cmdClose.Size = new System.Drawing.Size(89, 29); this.cmdClose.Location = new System.Drawing.Point(472, 2); this.cmdClose.TabIndex = 8; this.cmdClose.TabStop = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this.cmdsearch.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdsearch.Text = "&Search"; this.AcceptButton = this.cmdsearch; this.cmdsearch.Size = new System.Drawing.Size(89, 33); this.cmdsearch.Location = new System.Drawing.Point(8, 352); this.cmdsearch.TabIndex = 3; this.cmdsearch.BackColor = System.Drawing.SystemColors.Control; this.cmdsearch.CausesValidation = true; this.cmdsearch.Enabled = true; this.cmdsearch.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdsearch.Cursor = System.Windows.Forms.Cursors.Default; this.cmdsearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdsearch.TabStop = true; this.cmdsearch.Name = "cmdsearch"; this.txtqty.AutoSize = false; this.txtqty.Size = new System.Drawing.Size(89, 25); this.txtqty.Location = new System.Drawing.Point(472, 48); this.txtqty.TabIndex = 2; this.txtqty.AcceptsReturn = true; this.txtqty.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtqty.BackColor = System.Drawing.SystemColors.Window; this.txtqty.CausesValidation = true; this.txtqty.Enabled = true; this.txtqty.ForeColor = System.Drawing.SystemColors.WindowText; this.txtqty.HideSelection = true; this.txtqty.ReadOnly = false; this.txtqty.MaxLength = 0; this.txtqty.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtqty.Multiline = false; this.txtqty.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtqty.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtqty.TabStop = true; this.txtqty.Visible = true; this.txtqty.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtqty.Name = "txtqty"; this.txtdesc.AutoSize = false; this.txtdesc.Enabled = false; this.txtdesc.Size = new System.Drawing.Size(153, 25); this.txtdesc.Location = new System.Drawing.Point(272, 48); this.txtdesc.TabIndex = 1; this.txtdesc.AcceptsReturn = true; this.txtdesc.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtdesc.BackColor = System.Drawing.SystemColors.Window; this.txtdesc.CausesValidation = true; this.txtdesc.ForeColor = System.Drawing.SystemColors.WindowText; this.txtdesc.HideSelection = true; this.txtdesc.ReadOnly = false; this.txtdesc.MaxLength = 0; this.txtdesc.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtdesc.Multiline = false; this.txtdesc.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtdesc.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtdesc.TabStop = true; this.txtdesc.Visible = true; this.txtdesc.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtdesc.Name = "txtdesc"; this.txtcode.AutoSize = false; this.txtcode.Size = new System.Drawing.Size(89, 25); this.txtcode.Location = new System.Drawing.Point(88, 48); this.txtcode.TabIndex = 0; this.txtcode.AcceptsReturn = true; this.txtcode.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtcode.BackColor = System.Drawing.SystemColors.Window; this.txtcode.CausesValidation = true; this.txtcode.Enabled = true; this.txtcode.ForeColor = System.Drawing.SystemColors.WindowText; this.txtcode.HideSelection = true; this.txtcode.ReadOnly = false; this.txtcode.MaxLength = 0; this.txtcode.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtcode.Multiline = false; this.txtcode.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtcode.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtcode.TabStop = true; this.txtcode.Visible = true; this.txtcode.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtcode.Name = "txtcode"; //DataGrid1.OcxState = CType(resources.GetObject("DataGrid1.OcxState"), System.Windows.Forms.AxHost.State) this.DataGrid1.Size = new System.Drawing.Size(553, 257); this.DataGrid1.Location = new System.Drawing.Point(8, 88); this.DataGrid1.TabIndex = 9; this.DataGrid1.Name = "DataGrid1"; this.imgBC.Size = new System.Drawing.Size(265, 300); this.imgBC.Location = new System.Drawing.Point(568, 48); this.imgBC.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.imgBC.Visible = false; this.imgBC.Enabled = true; this.imgBC.Cursor = System.Windows.Forms.Cursors.Default; this.imgBC.BorderStyle = System.Windows.Forms.BorderStyle.None; this.imgBC.Name = "imgBC"; this.Label3.Text = "Qty"; this.Label3.Size = new System.Drawing.Size(33, 17); this.Label3.Location = new System.Drawing.Point(432, 56); this.Label3.TabIndex = 6; 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 = "Description"; this.Label2.Size = new System.Drawing.Size(81, 25); this.Label2.Location = new System.Drawing.Point(184, 56); this.Label2.TabIndex = 5; 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.Label1.Text = "Barcode"; this.Label1.Size = new System.Drawing.Size(81, 25); this.Label1.Location = new System.Drawing.Point(8, 56); this.Label1.TabIndex = 4; 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(picBC); this.Controls.Add(chkPic); this.Controls.Add(picButtons); this.Controls.Add(cmdsearch); this.Controls.Add(txtqty); this.Controls.Add(txtdesc); this.Controls.Add(txtcode); this.Controls.Add(DataGrid1); this.Controls.Add(imgBC); this.Controls.Add(Label3); this.Controls.Add(Label2); this.Controls.Add(Label1); this.picButtons.Controls.Add(cmdDiff); this.picButtons.Controls.Add(cmdClose); ((System.ComponentModel.ISupportInitialize)this.DataGrid1).EndInit(); this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the RemClasificado class. /// </summary> [Serializable] public partial class RemClasificadoCollection : ReadOnlyList<RemClasificado, RemClasificadoCollection> { public RemClasificadoCollection() {} } /// <summary> /// This is Read-only wrapper class for the REM_Clasificados view. /// </summary> [Serializable] public partial class RemClasificado : ReadOnlyRecord<RemClasificado>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("REM_Clasificados", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema); colvarApellido.ColumnName = "apellido"; colvarApellido.DataType = DbType.String; colvarApellido.MaxLength = 100; colvarApellido.AutoIncrement = false; colvarApellido.IsNullable = false; colvarApellido.IsPrimaryKey = false; colvarApellido.IsForeignKey = false; colvarApellido.IsReadOnly = false; schema.Columns.Add(colvarApellido); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 100; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarNumeroDocumento = new TableSchema.TableColumn(schema); colvarNumeroDocumento.ColumnName = "numeroDocumento"; colvarNumeroDocumento.DataType = DbType.Int32; colvarNumeroDocumento.MaxLength = 0; colvarNumeroDocumento.AutoIncrement = false; colvarNumeroDocumento.IsNullable = false; colvarNumeroDocumento.IsPrimaryKey = false; colvarNumeroDocumento.IsForeignKey = false; colvarNumeroDocumento.IsReadOnly = false; schema.Columns.Add(colvarNumeroDocumento); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "Sexo"; colvarSexo.DataType = DbType.String; colvarSexo.MaxLength = 50; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = false; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema); colvarFechaNacimiento.ColumnName = "fechaNacimiento"; colvarFechaNacimiento.DataType = DbType.DateTime; colvarFechaNacimiento.MaxLength = 0; colvarFechaNacimiento.AutoIncrement = false; colvarFechaNacimiento.IsNullable = false; colvarFechaNacimiento.IsPrimaryKey = false; colvarFechaNacimiento.IsForeignKey = false; colvarFechaNacimiento.IsReadOnly = false; schema.Columns.Add(colvarFechaNacimiento); TableSchema.TableColumn colvarFechaControl = new TableSchema.TableColumn(schema); colvarFechaControl.ColumnName = "fechaControl"; colvarFechaControl.DataType = DbType.DateTime; colvarFechaControl.MaxLength = 0; colvarFechaControl.AutoIncrement = false; colvarFechaControl.IsNullable = false; colvarFechaControl.IsPrimaryKey = false; colvarFechaControl.IsForeignKey = false; colvarFechaControl.IsReadOnly = false; schema.Columns.Add(colvarFechaControl); TableSchema.TableColumn colvarCalle = new TableSchema.TableColumn(schema); colvarCalle.ColumnName = "calle"; colvarCalle.DataType = DbType.String; colvarCalle.MaxLength = 50; colvarCalle.AutoIncrement = false; colvarCalle.IsNullable = false; colvarCalle.IsPrimaryKey = false; colvarCalle.IsForeignKey = false; colvarCalle.IsReadOnly = false; schema.Columns.Add(colvarCalle); TableSchema.TableColumn colvarNumero = new TableSchema.TableColumn(schema); colvarNumero.ColumnName = "numero"; colvarNumero.DataType = DbType.Int32; colvarNumero.MaxLength = 0; colvarNumero.AutoIncrement = false; colvarNumero.IsNullable = false; colvarNumero.IsPrimaryKey = false; colvarNumero.IsForeignKey = false; colvarNumero.IsReadOnly = false; schema.Columns.Add(colvarNumero); TableSchema.TableColumn colvarManzana = new TableSchema.TableColumn(schema); colvarManzana.ColumnName = "manzana"; colvarManzana.DataType = DbType.String; colvarManzana.MaxLength = 50; colvarManzana.AutoIncrement = false; colvarManzana.IsNullable = false; colvarManzana.IsPrimaryKey = false; colvarManzana.IsForeignKey = false; colvarManzana.IsReadOnly = false; schema.Columns.Add(colvarManzana); TableSchema.TableColumn colvarPiso = new TableSchema.TableColumn(schema); colvarPiso.ColumnName = "piso"; colvarPiso.DataType = DbType.String; colvarPiso.MaxLength = 10; colvarPiso.AutoIncrement = false; colvarPiso.IsNullable = false; colvarPiso.IsPrimaryKey = false; colvarPiso.IsForeignKey = false; colvarPiso.IsReadOnly = false; schema.Columns.Add(colvarPiso); TableSchema.TableColumn colvarDepartamento = new TableSchema.TableColumn(schema); colvarDepartamento.ColumnName = "departamento"; colvarDepartamento.DataType = DbType.String; colvarDepartamento.MaxLength = 10; colvarDepartamento.AutoIncrement = false; colvarDepartamento.IsNullable = false; colvarDepartamento.IsPrimaryKey = false; colvarDepartamento.IsForeignKey = false; colvarDepartamento.IsReadOnly = false; schema.Columns.Add(colvarDepartamento); TableSchema.TableColumn colvarIdBarrio = new TableSchema.TableColumn(schema); colvarIdBarrio.ColumnName = "idBarrio"; colvarIdBarrio.DataType = DbType.Int32; colvarIdBarrio.MaxLength = 0; colvarIdBarrio.AutoIncrement = false; colvarIdBarrio.IsNullable = false; colvarIdBarrio.IsPrimaryKey = false; colvarIdBarrio.IsForeignKey = false; colvarIdBarrio.IsReadOnly = false; schema.Columns.Add(colvarIdBarrio); TableSchema.TableColumn colvarIdLocalidad = new TableSchema.TableColumn(schema); colvarIdLocalidad.ColumnName = "idLocalidad"; colvarIdLocalidad.DataType = DbType.Int32; colvarIdLocalidad.MaxLength = 0; colvarIdLocalidad.AutoIncrement = false; colvarIdLocalidad.IsNullable = false; colvarIdLocalidad.IsPrimaryKey = false; colvarIdLocalidad.IsForeignKey = false; colvarIdLocalidad.IsReadOnly = false; schema.Columns.Add(colvarIdLocalidad); TableSchema.TableColumn colvarIdProvinciaDomicilio = new TableSchema.TableColumn(schema); colvarIdProvinciaDomicilio.ColumnName = "idProvinciaDomicilio"; colvarIdProvinciaDomicilio.DataType = DbType.Int32; colvarIdProvinciaDomicilio.MaxLength = 0; colvarIdProvinciaDomicilio.AutoIncrement = false; colvarIdProvinciaDomicilio.IsNullable = false; colvarIdProvinciaDomicilio.IsPrimaryKey = false; colvarIdProvinciaDomicilio.IsForeignKey = false; colvarIdProvinciaDomicilio.IsReadOnly = false; schema.Columns.Add(colvarIdProvinciaDomicilio); TableSchema.TableColumn colvarInformacionContacto = new TableSchema.TableColumn(schema); colvarInformacionContacto.ColumnName = "informacionContacto"; colvarInformacionContacto.DataType = DbType.String; colvarInformacionContacto.MaxLength = 800; colvarInformacionContacto.AutoIncrement = false; colvarInformacionContacto.IsNullable = false; colvarInformacionContacto.IsPrimaryKey = false; colvarInformacionContacto.IsForeignKey = false; colvarInformacionContacto.IsReadOnly = false; schema.Columns.Add(colvarInformacionContacto); TableSchema.TableColumn colvarModifiedOn = new TableSchema.TableColumn(schema); colvarModifiedOn.ColumnName = "ModifiedOn"; colvarModifiedOn.DataType = DbType.DateTime; colvarModifiedOn.MaxLength = 0; colvarModifiedOn.AutoIncrement = false; colvarModifiedOn.IsNullable = false; colvarModifiedOn.IsPrimaryKey = false; colvarModifiedOn.IsForeignKey = false; colvarModifiedOn.IsReadOnly = false; schema.Columns.Add(colvarModifiedOn); TableSchema.TableColumn colvarIdObraSocial = new TableSchema.TableColumn(schema); colvarIdObraSocial.ColumnName = "idObraSocial"; colvarIdObraSocial.DataType = DbType.Int32; colvarIdObraSocial.MaxLength = 0; colvarIdObraSocial.AutoIncrement = false; colvarIdObraSocial.IsNullable = false; colvarIdObraSocial.IsPrimaryKey = false; colvarIdObraSocial.IsForeignKey = false; colvarIdObraSocial.IsReadOnly = false; schema.Columns.Add(colvarIdObraSocial); TableSchema.TableColumn colvarAntecedente = new TableSchema.TableColumn(schema); colvarAntecedente.ColumnName = "Antecedente"; colvarAntecedente.DataType = DbType.String; colvarAntecedente.MaxLength = 50; colvarAntecedente.AutoIncrement = false; colvarAntecedente.IsNullable = false; colvarAntecedente.IsPrimaryKey = false; colvarAntecedente.IsForeignKey = false; colvarAntecedente.IsReadOnly = false; schema.Columns.Add(colvarAntecedente); TableSchema.TableColumn colvarImc = new TableSchema.TableColumn(schema); colvarImc.ColumnName = "Imc"; colvarImc.DataType = DbType.Decimal; colvarImc.MaxLength = 0; colvarImc.AutoIncrement = false; colvarImc.IsNullable = false; colvarImc.IsPrimaryKey = false; colvarImc.IsForeignKey = false; colvarImc.IsReadOnly = false; schema.Columns.Add(colvarImc); TableSchema.TableColumn colvarRiesgoCardiovascular = new TableSchema.TableColumn(schema); colvarRiesgoCardiovascular.ColumnName = "riesgoCardiovascular"; colvarRiesgoCardiovascular.DataType = DbType.Int32; colvarRiesgoCardiovascular.MaxLength = 0; colvarRiesgoCardiovascular.AutoIncrement = false; colvarRiesgoCardiovascular.IsNullable = false; colvarRiesgoCardiovascular.IsPrimaryKey = false; colvarRiesgoCardiovascular.IsForeignKey = false; colvarRiesgoCardiovascular.IsReadOnly = false; schema.Columns.Add(colvarRiesgoCardiovascular); TableSchema.TableColumn colvarTAS = new TableSchema.TableColumn(schema); colvarTAS.ColumnName = "tAS"; colvarTAS.DataType = DbType.Int32; colvarTAS.MaxLength = 0; colvarTAS.AutoIncrement = false; colvarTAS.IsNullable = false; colvarTAS.IsPrimaryKey = false; colvarTAS.IsForeignKey = false; colvarTAS.IsReadOnly = false; schema.Columns.Add(colvarTAS); TableSchema.TableColumn colvarTAD = new TableSchema.TableColumn(schema); colvarTAD.ColumnName = "tAD"; colvarTAD.DataType = DbType.Int32; colvarTAD.MaxLength = 0; colvarTAD.AutoIncrement = false; colvarTAD.IsNullable = false; colvarTAD.IsPrimaryKey = false; colvarTAD.IsForeignKey = false; colvarTAD.IsReadOnly = false; schema.Columns.Add(colvarTAD); TableSchema.TableColumn colvarColesterolTotal = new TableSchema.TableColumn(schema); colvarColesterolTotal.ColumnName = "colesterolTotal"; colvarColesterolTotal.DataType = DbType.Decimal; colvarColesterolTotal.MaxLength = 0; colvarColesterolTotal.AutoIncrement = false; colvarColesterolTotal.IsNullable = false; colvarColesterolTotal.IsPrimaryKey = false; colvarColesterolTotal.IsForeignKey = false; colvarColesterolTotal.IsReadOnly = false; schema.Columns.Add(colvarColesterolTotal); TableSchema.TableColumn colvarUnidadColTotal = new TableSchema.TableColumn(schema); colvarUnidadColTotal.ColumnName = "unidadColTotal"; colvarUnidadColTotal.DataType = DbType.AnsiString; colvarUnidadColTotal.MaxLength = 10; colvarUnidadColTotal.AutoIncrement = false; colvarUnidadColTotal.IsNullable = false; colvarUnidadColTotal.IsPrimaryKey = false; colvarUnidadColTotal.IsForeignKey = false; colvarUnidadColTotal.IsReadOnly = false; schema.Columns.Add(colvarUnidadColTotal); TableSchema.TableColumn colvarHdl = new TableSchema.TableColumn(schema); colvarHdl.ColumnName = "HDL"; colvarHdl.DataType = DbType.Decimal; colvarHdl.MaxLength = 0; colvarHdl.AutoIncrement = false; colvarHdl.IsNullable = false; colvarHdl.IsPrimaryKey = false; colvarHdl.IsForeignKey = false; colvarHdl.IsReadOnly = false; schema.Columns.Add(colvarHdl); TableSchema.TableColumn colvarUnidadHDL = new TableSchema.TableColumn(schema); colvarUnidadHDL.ColumnName = "unidadHDL"; colvarUnidadHDL.DataType = DbType.AnsiString; colvarUnidadHDL.MaxLength = 10; colvarUnidadHDL.AutoIncrement = false; colvarUnidadHDL.IsNullable = false; colvarUnidadHDL.IsPrimaryKey = false; colvarUnidadHDL.IsForeignKey = false; colvarUnidadHDL.IsReadOnly = false; schema.Columns.Add(colvarUnidadHDL); TableSchema.TableColumn colvarLdl = new TableSchema.TableColumn(schema); colvarLdl.ColumnName = "LDL"; colvarLdl.DataType = DbType.Decimal; colvarLdl.MaxLength = 0; colvarLdl.AutoIncrement = false; colvarLdl.IsNullable = false; colvarLdl.IsPrimaryKey = false; colvarLdl.IsForeignKey = false; colvarLdl.IsReadOnly = false; schema.Columns.Add(colvarLdl); TableSchema.TableColumn colvarUnidadLDL = new TableSchema.TableColumn(schema); colvarUnidadLDL.ColumnName = "unidadLDL"; colvarUnidadLDL.DataType = DbType.AnsiString; colvarUnidadLDL.MaxLength = 10; colvarUnidadLDL.AutoIncrement = false; colvarUnidadLDL.IsNullable = false; colvarUnidadLDL.IsPrimaryKey = false; colvarUnidadLDL.IsForeignKey = false; colvarUnidadLDL.IsReadOnly = false; schema.Columns.Add(colvarUnidadLDL); TableSchema.TableColumn colvarTgl = new TableSchema.TableColumn(schema); colvarTgl.ColumnName = "TGL"; colvarTgl.DataType = DbType.Decimal; colvarTgl.MaxLength = 0; colvarTgl.AutoIncrement = false; colvarTgl.IsNullable = false; colvarTgl.IsPrimaryKey = false; colvarTgl.IsForeignKey = false; colvarTgl.IsReadOnly = false; schema.Columns.Add(colvarTgl); TableSchema.TableColumn colvarUnidadTGL = new TableSchema.TableColumn(schema); colvarUnidadTGL.ColumnName = "unidadTGL"; colvarUnidadTGL.DataType = DbType.AnsiString; colvarUnidadTGL.MaxLength = 10; colvarUnidadTGL.AutoIncrement = false; colvarUnidadTGL.IsNullable = false; colvarUnidadTGL.IsPrimaryKey = false; colvarUnidadTGL.IsForeignKey = false; colvarUnidadTGL.IsReadOnly = false; schema.Columns.Add(colvarUnidadTGL); TableSchema.TableColumn colvarGlucemia = new TableSchema.TableColumn(schema); colvarGlucemia.ColumnName = "glucemia"; colvarGlucemia.DataType = DbType.Decimal; colvarGlucemia.MaxLength = 0; colvarGlucemia.AutoIncrement = false; colvarGlucemia.IsNullable = false; colvarGlucemia.IsPrimaryKey = false; colvarGlucemia.IsForeignKey = false; colvarGlucemia.IsReadOnly = false; schema.Columns.Add(colvarGlucemia); TableSchema.TableColumn colvarUnidadGlucemia = new TableSchema.TableColumn(schema); colvarUnidadGlucemia.ColumnName = "unidadGlucemia"; colvarUnidadGlucemia.DataType = DbType.AnsiString; colvarUnidadGlucemia.MaxLength = 10; colvarUnidadGlucemia.AutoIncrement = false; colvarUnidadGlucemia.IsNullable = false; colvarUnidadGlucemia.IsPrimaryKey = false; colvarUnidadGlucemia.IsForeignKey = false; colvarUnidadGlucemia.IsReadOnly = false; schema.Columns.Add(colvarUnidadGlucemia); TableSchema.TableColumn colvarHbAc1 = new TableSchema.TableColumn(schema); colvarHbAc1.ColumnName = "HbAc1"; colvarHbAc1.DataType = DbType.Decimal; colvarHbAc1.MaxLength = 0; colvarHbAc1.AutoIncrement = false; colvarHbAc1.IsNullable = false; colvarHbAc1.IsPrimaryKey = false; colvarHbAc1.IsForeignKey = false; colvarHbAc1.IsReadOnly = false; schema.Columns.Add(colvarHbAc1); TableSchema.TableColumn colvarDosis = new TableSchema.TableColumn(schema); colvarDosis.ColumnName = "dosis"; colvarDosis.DataType = DbType.Double; colvarDosis.MaxLength = 0; colvarDosis.AutoIncrement = false; colvarDosis.IsNullable = false; colvarDosis.IsPrimaryKey = false; colvarDosis.IsForeignKey = false; colvarDosis.IsReadOnly = false; schema.Columns.Add(colvarDosis); TableSchema.TableColumn colvarMedicamentos = new TableSchema.TableColumn(schema); colvarMedicamentos.ColumnName = "Medicamentos"; colvarMedicamentos.DataType = DbType.String; colvarMedicamentos.MaxLength = 255; colvarMedicamentos.AutoIncrement = false; colvarMedicamentos.IsNullable = true; colvarMedicamentos.IsPrimaryKey = false; colvarMedicamentos.IsForeignKey = false; colvarMedicamentos.IsReadOnly = false; schema.Columns.Add(colvarMedicamentos); TableSchema.TableColumn colvarNombreInsulina = new TableSchema.TableColumn(schema); colvarNombreInsulina.ColumnName = "nombreInsulina"; colvarNombreInsulina.DataType = DbType.String; colvarNombreInsulina.MaxLength = 50; colvarNombreInsulina.AutoIncrement = false; colvarNombreInsulina.IsNullable = false; colvarNombreInsulina.IsPrimaryKey = false; colvarNombreInsulina.IsForeignKey = false; colvarNombreInsulina.IsReadOnly = false; schema.Columns.Add(colvarNombreInsulina); TableSchema.TableColumn colvarOtrasDrogas1 = new TableSchema.TableColumn(schema); colvarOtrasDrogas1.ColumnName = "otrasDrogas1"; colvarOtrasDrogas1.DataType = DbType.AnsiString; colvarOtrasDrogas1.MaxLength = 200; colvarOtrasDrogas1.AutoIncrement = false; colvarOtrasDrogas1.IsNullable = false; colvarOtrasDrogas1.IsPrimaryKey = false; colvarOtrasDrogas1.IsForeignKey = false; colvarOtrasDrogas1.IsReadOnly = false; schema.Columns.Add(colvarOtrasDrogas1); TableSchema.TableColumn colvarDosisODrogas1 = new TableSchema.TableColumn(schema); colvarDosisODrogas1.ColumnName = "dosisODrogas1"; colvarDosisODrogas1.DataType = DbType.Decimal; colvarDosisODrogas1.MaxLength = 0; colvarDosisODrogas1.AutoIncrement = false; colvarDosisODrogas1.IsNullable = false; colvarDosisODrogas1.IsPrimaryKey = false; colvarDosisODrogas1.IsForeignKey = false; colvarDosisODrogas1.IsReadOnly = false; schema.Columns.Add(colvarDosisODrogas1); TableSchema.TableColumn colvarOtrasDrogras2 = new TableSchema.TableColumn(schema); colvarOtrasDrogras2.ColumnName = "otrasDrogras2"; colvarOtrasDrogras2.DataType = DbType.AnsiString; colvarOtrasDrogras2.MaxLength = 200; colvarOtrasDrogras2.AutoIncrement = false; colvarOtrasDrogras2.IsNullable = false; colvarOtrasDrogras2.IsPrimaryKey = false; colvarOtrasDrogras2.IsForeignKey = false; colvarOtrasDrogras2.IsReadOnly = false; schema.Columns.Add(colvarOtrasDrogras2); TableSchema.TableColumn colvarDosisODrogas2 = new TableSchema.TableColumn(schema); colvarDosisODrogas2.ColumnName = "dosisODrogas2"; colvarDosisODrogas2.DataType = DbType.Decimal; colvarDosisODrogas2.MaxLength = 0; colvarDosisODrogas2.AutoIncrement = false; colvarDosisODrogas2.IsNullable = false; colvarDosisODrogas2.IsPrimaryKey = false; colvarDosisODrogas2.IsForeignKey = false; colvarDosisODrogas2.IsReadOnly = false; schema.Columns.Add(colvarDosisODrogas2); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("REM_Clasificados",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public RemClasificado() { SetSQLProps(); SetDefaults(); MarkNew(); } public RemClasificado(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public RemClasificado(object keyID) { SetSQLProps(); LoadByKey(keyID); } public RemClasificado(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("Apellido")] [Bindable(true)] public string Apellido { get { return GetColumnValue<string>("apellido"); } set { SetColumnValue("apellido", value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>("nombre"); } set { SetColumnValue("nombre", value); } } [XmlAttribute("NumeroDocumento")] [Bindable(true)] public int NumeroDocumento { get { return GetColumnValue<int>("numeroDocumento"); } set { SetColumnValue("numeroDocumento", value); } } [XmlAttribute("Sexo")] [Bindable(true)] public string Sexo { get { return GetColumnValue<string>("Sexo"); } set { SetColumnValue("Sexo", value); } } [XmlAttribute("FechaNacimiento")] [Bindable(true)] public DateTime FechaNacimiento { get { return GetColumnValue<DateTime>("fechaNacimiento"); } set { SetColumnValue("fechaNacimiento", value); } } [XmlAttribute("FechaControl")] [Bindable(true)] public DateTime FechaControl { get { return GetColumnValue<DateTime>("fechaControl"); } set { SetColumnValue("fechaControl", value); } } [XmlAttribute("Calle")] [Bindable(true)] public string Calle { get { return GetColumnValue<string>("calle"); } set { SetColumnValue("calle", value); } } [XmlAttribute("Numero")] [Bindable(true)] public int Numero { get { return GetColumnValue<int>("numero"); } set { SetColumnValue("numero", value); } } [XmlAttribute("Manzana")] [Bindable(true)] public string Manzana { get { return GetColumnValue<string>("manzana"); } set { SetColumnValue("manzana", value); } } [XmlAttribute("Piso")] [Bindable(true)] public string Piso { get { return GetColumnValue<string>("piso"); } set { SetColumnValue("piso", value); } } [XmlAttribute("Departamento")] [Bindable(true)] public string Departamento { get { return GetColumnValue<string>("departamento"); } set { SetColumnValue("departamento", value); } } [XmlAttribute("IdBarrio")] [Bindable(true)] public int IdBarrio { get { return GetColumnValue<int>("idBarrio"); } set { SetColumnValue("idBarrio", value); } } [XmlAttribute("IdLocalidad")] [Bindable(true)] public int IdLocalidad { get { return GetColumnValue<int>("idLocalidad"); } set { SetColumnValue("idLocalidad", value); } } [XmlAttribute("IdProvinciaDomicilio")] [Bindable(true)] public int IdProvinciaDomicilio { get { return GetColumnValue<int>("idProvinciaDomicilio"); } set { SetColumnValue("idProvinciaDomicilio", value); } } [XmlAttribute("InformacionContacto")] [Bindable(true)] public string InformacionContacto { get { return GetColumnValue<string>("informacionContacto"); } set { SetColumnValue("informacionContacto", value); } } [XmlAttribute("ModifiedOn")] [Bindable(true)] public DateTime ModifiedOn { get { return GetColumnValue<DateTime>("ModifiedOn"); } set { SetColumnValue("ModifiedOn", value); } } [XmlAttribute("IdObraSocial")] [Bindable(true)] public int IdObraSocial { get { return GetColumnValue<int>("idObraSocial"); } set { SetColumnValue("idObraSocial", value); } } [XmlAttribute("Antecedente")] [Bindable(true)] public string Antecedente { get { return GetColumnValue<string>("Antecedente"); } set { SetColumnValue("Antecedente", value); } } [XmlAttribute("Imc")] [Bindable(true)] public decimal Imc { get { return GetColumnValue<decimal>("Imc"); } set { SetColumnValue("Imc", value); } } [XmlAttribute("RiesgoCardiovascular")] [Bindable(true)] public int RiesgoCardiovascular { get { return GetColumnValue<int>("riesgoCardiovascular"); } set { SetColumnValue("riesgoCardiovascular", value); } } [XmlAttribute("TAS")] [Bindable(true)] public int TAS { get { return GetColumnValue<int>("tAS"); } set { SetColumnValue("tAS", value); } } [XmlAttribute("TAD")] [Bindable(true)] public int TAD { get { return GetColumnValue<int>("tAD"); } set { SetColumnValue("tAD", value); } } [XmlAttribute("ColesterolTotal")] [Bindable(true)] public decimal ColesterolTotal { get { return GetColumnValue<decimal>("colesterolTotal"); } set { SetColumnValue("colesterolTotal", value); } } [XmlAttribute("UnidadColTotal")] [Bindable(true)] public string UnidadColTotal { get { return GetColumnValue<string>("unidadColTotal"); } set { SetColumnValue("unidadColTotal", value); } } [XmlAttribute("Hdl")] [Bindable(true)] public decimal Hdl { get { return GetColumnValue<decimal>("HDL"); } set { SetColumnValue("HDL", value); } } [XmlAttribute("UnidadHDL")] [Bindable(true)] public string UnidadHDL { get { return GetColumnValue<string>("unidadHDL"); } set { SetColumnValue("unidadHDL", value); } } [XmlAttribute("Ldl")] [Bindable(true)] public decimal Ldl { get { return GetColumnValue<decimal>("LDL"); } set { SetColumnValue("LDL", value); } } [XmlAttribute("UnidadLDL")] [Bindable(true)] public string UnidadLDL { get { return GetColumnValue<string>("unidadLDL"); } set { SetColumnValue("unidadLDL", value); } } [XmlAttribute("Tgl")] [Bindable(true)] public decimal Tgl { get { return GetColumnValue<decimal>("TGL"); } set { SetColumnValue("TGL", value); } } [XmlAttribute("UnidadTGL")] [Bindable(true)] public string UnidadTGL { get { return GetColumnValue<string>("unidadTGL"); } set { SetColumnValue("unidadTGL", value); } } [XmlAttribute("Glucemia")] [Bindable(true)] public decimal Glucemia { get { return GetColumnValue<decimal>("glucemia"); } set { SetColumnValue("glucemia", value); } } [XmlAttribute("UnidadGlucemia")] [Bindable(true)] public string UnidadGlucemia { get { return GetColumnValue<string>("unidadGlucemia"); } set { SetColumnValue("unidadGlucemia", value); } } [XmlAttribute("HbAc1")] [Bindable(true)] public decimal HbAc1 { get { return GetColumnValue<decimal>("HbAc1"); } set { SetColumnValue("HbAc1", value); } } [XmlAttribute("Dosis")] [Bindable(true)] public double Dosis { get { return GetColumnValue<double>("dosis"); } set { SetColumnValue("dosis", value); } } [XmlAttribute("Medicamentos")] [Bindable(true)] public string Medicamentos { get { return GetColumnValue<string>("Medicamentos"); } set { SetColumnValue("Medicamentos", value); } } [XmlAttribute("NombreInsulina")] [Bindable(true)] public string NombreInsulina { get { return GetColumnValue<string>("nombreInsulina"); } set { SetColumnValue("nombreInsulina", value); } } [XmlAttribute("OtrasDrogas1")] [Bindable(true)] public string OtrasDrogas1 { get { return GetColumnValue<string>("otrasDrogas1"); } set { SetColumnValue("otrasDrogas1", value); } } [XmlAttribute("DosisODrogas1")] [Bindable(true)] public decimal DosisODrogas1 { get { return GetColumnValue<decimal>("dosisODrogas1"); } set { SetColumnValue("dosisODrogas1", value); } } [XmlAttribute("OtrasDrogras2")] [Bindable(true)] public string OtrasDrogras2 { get { return GetColumnValue<string>("otrasDrogras2"); } set { SetColumnValue("otrasDrogras2", value); } } [XmlAttribute("DosisODrogas2")] [Bindable(true)] public decimal DosisODrogas2 { get { return GetColumnValue<decimal>("dosisODrogas2"); } set { SetColumnValue("dosisODrogas2", value); } } #endregion #region Columns Struct public struct Columns { public static string Apellido = @"apellido"; public static string Nombre = @"nombre"; public static string NumeroDocumento = @"numeroDocumento"; public static string Sexo = @"Sexo"; public static string FechaNacimiento = @"fechaNacimiento"; public static string FechaControl = @"fechaControl"; public static string Calle = @"calle"; public static string Numero = @"numero"; public static string Manzana = @"manzana"; public static string Piso = @"piso"; public static string Departamento = @"departamento"; public static string IdBarrio = @"idBarrio"; public static string IdLocalidad = @"idLocalidad"; public static string IdProvinciaDomicilio = @"idProvinciaDomicilio"; public static string InformacionContacto = @"informacionContacto"; public static string ModifiedOn = @"ModifiedOn"; public static string IdObraSocial = @"idObraSocial"; public static string Antecedente = @"Antecedente"; public static string Imc = @"Imc"; public static string RiesgoCardiovascular = @"riesgoCardiovascular"; public static string TAS = @"tAS"; public static string TAD = @"tAD"; public static string ColesterolTotal = @"colesterolTotal"; public static string UnidadColTotal = @"unidadColTotal"; public static string Hdl = @"HDL"; public static string UnidadHDL = @"unidadHDL"; public static string Ldl = @"LDL"; public static string UnidadLDL = @"unidadLDL"; public static string Tgl = @"TGL"; public static string UnidadTGL = @"unidadTGL"; public static string Glucemia = @"glucemia"; public static string UnidadGlucemia = @"unidadGlucemia"; public static string HbAc1 = @"HbAc1"; public static string Dosis = @"dosis"; public static string Medicamentos = @"Medicamentos"; public static string NombreInsulina = @"nombreInsulina"; public static string OtrasDrogas1 = @"otrasDrogas1"; public static string DosisODrogas1 = @"dosisODrogas1"; public static string OtrasDrogras2 = @"otrasDrogras2"; public static string DosisODrogas2 = @"dosisODrogas2"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
using System; using Server.Items; namespace Server.Engines.Craft { public class DefBowFletching : CraftSystem { public override SkillName MainSkill { get { return SkillName.Fletching; } } public override int GumpTitleNumber { get { return 1044006; } // <CENTER>BOWCRAFT AND FLETCHING MENU</CENTER> } private static CraftSystem m_CraftSystem; public static CraftSystem CraftSystem { get { if ( m_CraftSystem == null ) m_CraftSystem = new DefBowFletching(); return m_CraftSystem; } } public override double GetChanceAtMin( CraftItem item ) { return 0.5; // 50% } private DefBowFletching() : base( 1, 1, 1.25 )// base( 1, 2, 1.7 ) { } public override int CanCraft( Mobile from, BaseTool tool, Type itemType ) { if( tool == null || tool.Deleted || tool.UsesRemaining < 0 ) return 1044038; // You have worn out your tool! else if ( !BaseTool.CheckAccessible( tool, from ) ) return 1044263; // The tool must be on your person to use. return 0; } public override void PlayCraftEffect( Mobile from ) { // no animation //if ( from.Body.Type == BodyType.Human && !from.Mounted ) // from.Animate( 33, 5, 1, true, false, 0 ); from.PlaySound( 0x55 ); } public override int PlayEndingEffect( Mobile from, bool failed, bool lostMaterial, bool toolBroken, int quality, bool makersMark, CraftItem item ) { if ( toolBroken ) from.SendLocalizedMessage( 1044038 ); // You have worn out your tool if ( failed ) { if ( lostMaterial ) return 1044043; // You failed to create the item, and some of your materials are lost. else return 1044157; // You failed to create the item, but no materials were lost. } else { if ( quality == 0 ) return 502785; // You were barely able to make this item. It's quality is below average. else if ( makersMark && quality == 2 ) return 1044156; // You create an exceptional quality item and affix your maker's mark. else if ( quality == 2 ) return 1044155; // You create an exceptional quality item. else return 1044154; // You create the item. } } public override CraftECA ECA{ get{ return CraftECA.FiftyPercentChanceMinusTenPercent; } } public override void InitCraftList() { int index = -1; // Materials AddCraft( typeof( Kindling ), 1044457, 1023553, 0.0, 00.0, typeof( Log ), 1044041, 1, 1044351 ); index = AddCraft( typeof( Shaft ), 1044457, 1027124, 0.0, 40.0, typeof( Log ), 1044041, 1, 1044351 ); SetUseAllRes( index, true ); // Ammunition index = AddCraft( typeof( Arrow ), 1044565, 1023903, 0.0, 40.0, typeof( Shaft ), 1044560, 1, 1044561 ); AddRes( index, typeof( Feather ), 1044562, 1, 1044563 ); SetUseAllRes( index, true ); index = AddCraft( typeof( Bolt ), 1044565, 1027163, 0.0, 40.0, typeof( Shaft ), 1044560, 1, 1044561 ); AddRes( index, typeof( Feather ), 1044562, 1, 1044563 ); SetUseAllRes( index, true ); if( Core.SE ) { index = AddCraft( typeof( FukiyaDarts ), 1044565, 1030246, 50.0, 90.0, typeof( Log ), 1044041, 1, 1044351 ); SetUseAllRes( index, true ); SetNeededExpansion( index, Expansion.SE ); } // Weapons AddCraft( typeof( Bow ), 1044566, 1025042, 30.0, 70.0, typeof( Log ), 1044041, 7, 1044351 ); AddCraft( typeof( Crossbow ), 1044566, 1023919, 60.0, 100.0, typeof( Log ), 1044041, 7, 1044351 ); AddCraft( typeof( HeavyCrossbow ), 1044566, 1025117, 80.0, 120.0, typeof( Log ), 1044041, 10, 1044351 ); if ( Core.AOS ) { AddCraft( typeof( CompositeBow ), 1044566, 1029922, 70.0, 110.0, typeof( Log ), 1044041, 7, 1044351 ); AddCraft( typeof( RepeatingCrossbow ), 1044566, 1029923, 90.0, 130.0, typeof( Log ), 1044041, 10, 1044351 ); } if( Core.SE ) { index = AddCraft( typeof( Yumi ), 1044566, 1030224, 90.0, 130.0, typeof( Log ), 1044041, 10, 1044351 ); SetNeededExpansion( index, Expansion.SE ); } if (Core.ML) { index = AddCraft(typeof(BlightGrippedLongbow), 1044566, 1072907, 75.0, 125.0, typeof(Log), 1044041, 20, 1044351); AddRes(index, typeof(LardOfParoxysmus), 1032681, 1, 1053098); AddRes(index, typeof(Blight), 1032675, 10, 1053098); AddRes(index, typeof(Corruption), 1032676, 10, 1053098); AddRareRecipe(index, 200); ForceNonExceptional(index); SetNeededExpansion(index, Expansion.ML); /* TODO index = AddCraft( typeof( FaerieFire ), 1044566, 1072908, 75.0, 125.0, typeof( Log ), 1044041, 20, 1044351 ); AddRes( index, typeof( LardOfParoxysmus ), 1032681, 1, 1053098 ); AddRes( index, typeof( Putrefication ), 1032678, 10, 1053098 ); AddRes( index, typeof( Taint ), 1032679, 10, 1053098 ); AddRareRecipe( index, 201 ); ForceNonExceptional( index ); SetNeededExpansion( index, Expansion.ML ); */ index = AddCraft(typeof(SilvanisFeywoodBow), 1044566, 1072955, 75.0, 125.0, typeof(Log), 1044041, 20, 1044351); AddRes(index, typeof(LardOfParoxysmus), 1032681, 1, 1053098); AddRes(index, typeof(Scourge), 1032677, 10, 1053098); AddRes(index, typeof(Muculent), 1032680, 10, 1053098); AddRareRecipe(index, 202); ForceNonExceptional(index); SetNeededExpansion(index, Expansion.ML); /* TODO index = AddCraft( typeof( MischiefMaker ), 1044566, 1072910, 75.0, 125.0, typeof( Log ), 1044041, 15, 1044351 ); AddRes( index, typeof( DreadHornMane ), 1032682, 1, 1053098 ); AddRes( index, typeof( Corruption ), 1032676, 10, 1053098 ); AddRes( index, typeof( Putrefication ), 1032678, 10, 1053098 ); AddRareRecipe( index, 203 ); ForceNonExceptional( index ); SetNeededExpansion( index, Expansion.ML ); */ index = AddCraft(typeof(TheNightReaper), 1044566, 1072912, 75.0, 125.0, typeof(Log), 1044041, 10, 1044351); AddRes(index, typeof(DreadHornMane), 1032682, 1, 1053098); AddRes(index, typeof(Blight), 1032675, 10, 1053098); AddRes(index, typeof(Scourge), 1032677, 10, 1053098); AddRareRecipe(index, 204); ForceNonExceptional(index); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(BarbedLongbow), 1044566, 1073505, 75.0, 125.0, typeof(Log), 1044041, 20, 1044351); AddRes(index, typeof(FireRuby), 1026254, 1, 1053098); AddRecipe(index, 205); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(SlayerLongbow), 1044566, 1073506, 75.0, 125.0, typeof(Log), 1044041, 20, 1044351); AddRes(index, typeof(BrilliantAmber), 1026256, 1, 1053098); AddRecipe(index, 206); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(FrozenLongbow), 1044566, 1073507, 75.0, 125.0, typeof(Log), 1044041, 20, 1044351); AddRes(index, typeof(Turquoise), 1026250, 1, 1053098); AddRecipe(index, 207); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(LongbowOfMight), 1044566, 1073508, 75.0, 125.0, typeof(Log), 1044041, 10, 1044351); AddRes(index, typeof(BlueDiamond), 1026255, 1, 1053098); AddRecipe(index, 208); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(RangersShortbow), 1044566, 1073509, 75.0, 125.0, typeof(Log), 1044041, 15, 1044351); AddRes(index, typeof(PerfectEmerald), 1026251, 1, 1053098); AddRecipe(index, 209); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(LightweightShortbow), 1044566, 1073510, 75.0, 125.0, typeof(Log), 1044041, 15, 1044351); AddRes(index, typeof(WhitePearl), 1026253, 1, 1053098); AddRecipe(index, 210); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(MysticalShortbow), 1044566, 1073511, 75.0, 125.0, typeof(Log), 1044041, 15, 1044351); AddRes(index, typeof(EcruCitrine), 1026252, 1, 1053098); AddRecipe(index, 211); SetNeededExpansion(index, Expansion.ML); index = AddCraft(typeof(AssassinsShortbow), 1044566, 1073512, 75.0, 125.0, typeof(Log), 1044041, 15, 1044351); AddRes(index, typeof(DarkSapphire), 1026249, 1, 1053098); AddRecipe(index, 212); SetNeededExpansion(index, Expansion.ML); } MarkOption = true; Repair = Core.AOS; SetSubRes(typeof(Log), 1072643); // Add every material you want the player to be able to choose from // This will override the overridable material TODO: Verify the required skill amount AddSubRes(typeof(Log), 1072643, 00.0, 1044041, 1072652); AddSubRes(typeof(OakLog), 1072644, 65.0, 1044041, 1072652); AddSubRes(typeof(AshLog), 1072645, 80.0, 1044041, 1072652); AddSubRes(typeof(YewLog), 1072646, 95.0, 1044041, 1072652); AddSubRes(typeof(HeartwoodLog), 1072647, 100.0, 1044041, 1072652); AddSubRes(typeof(BloodwoodLog), 1072648, 100.0, 1044041, 1072652); AddSubRes(typeof(FrostwoodLog), 1072649, 100.0, 1044041, 1072652); } } }
// 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 Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked001.checked001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked001.checked001; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { checked { x = (int)d.GetMaxInt() + 1; } } catch (System.OverflowException) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked002.checked002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked002.checked002; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt { get { return int.MaxValue; } set { } } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { checked { x = (int)d.GetMaxInt++; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked003.checked003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked003.checked003; public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = int.MaxValue; byte x = 0; try { checked { //this will not throw, because we don't pass the fact that we are in a checked context x = (byte)d; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked004.checked004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked004.checked004; public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = int.MaxValue; int x = 0; try { checked { //This will not work by our current design because we will introduce an implicit conversion to byte x = d + 1; } } catch (System.OverflowException) { if (x == 0) { return 0; } else { return 1; } } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked005.checked005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked005.checked005; public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { int rez = 0, tests = 0; bool exception = false; //signals if the exception is thrown dynamic d = null; dynamic d2 = null; // ++ on byte in checked context tests++; exception = false; d = byte.MaxValue; try { checked { d++; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -- on char in checked context tests++; exception = false; d = char.MinValue; try { char rchar = checked(d--); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on ushort in checked context tests++; exception = false; d = ushort.MaxValue; try { checked { ushort rez2 = (ushort)-d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // + on sbyte and int tests++; exception = false; d = sbyte.MaxValue; d2 = int.MaxValue; try { checked { int rez2 = d + d2; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on uint and ushort tests++; exception = false; d = uint.MaxValue; d2 = ushort.MinValue; try { checked { uint rez3 = d2 - d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -= on ushort and ushort tests++; exception = false; d = ushort.MaxValue; d2 = ushort.MinValue; try { checked { d2 -= d; exception = true; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // * on char and long tests++; exception = false; d = char.MaxValue; d2 = long.MinValue; try { checked { long rez3 = d2 * d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // / on char and long tests++; exception = false; d = int.MinValue; d2 = -1; try { long rez4 = checked(d / d2); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from int to byte tests++; exception = false; d = int.MaxValue; try { checked { byte b = (byte)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = false; d = float.MaxValue; try { checked { char b = (char)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = false; d = double.MaxValue; try { checked { ushort b = (ushort)d; } } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked006.checked006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked006.checked006; public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { int rez = 0, tests = 0; bool exception = true; //signals if the exception is thrown dynamic d = null; dynamic d2 = null; // ++ on byte in unchecked context tests++; exception = true; d = byte.MaxValue; try { unchecked { d++; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -- on char in unchecked context tests++; exception = true; d = char.MinValue; try { char rchar = unchecked(d--); } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on ushort in unchecked context tests++; exception = true; d = ushort.MaxValue; try { unchecked { ushort rez2 = (ushort)-d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // + on sbyte and int tests++; exception = true; d = sbyte.MaxValue; d2 = int.MaxValue; try { unchecked { int rez2 = d + d2; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // - on uint and ushort tests++; exception = true; d = uint.MaxValue; d2 = ushort.MinValue; try { unchecked { uint rez3 = d2 - d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // -= on uint and ushort tests++; exception = true; d = ushort.MaxValue; d2 = ushort.MinValue; try { unchecked { d2 -= d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // * on char and long tests++; exception = true; d = char.MaxValue; d2 = long.MinValue; try { unchecked { long rez3 = d2 * d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // / on char and long -> it is implemented such that this will throw even in an unchecked context. tests++; exception = false; d = int.MinValue; d2 = -1; try { long rez4 = unchecked(d / d2); } catch (System.OverflowException) { exception = true; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from int to byte tests++; exception = true; d = int.MaxValue; try { unchecked { byte b = (byte)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = true; d = float.MaxValue; try { unchecked { char b = (char)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } // explicit numeric conversion from float to char tests++; exception = true; d = double.MaxValue; try { unchecked { ushort b = (ushort)d; } } catch (System.OverflowException) { exception = false; } finally { if (exception) rez++; else System.Console.WriteLine("Test {0} failed", tests); } return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked008.checked008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.checked008.checked008; // <Title>Tests checked block</Title> // <Description> Compiler not passing checked flag in complex operators // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(16,17\).*CS0649</Expects> //<Expects Status=warning>\(17,11\).*CS0414</Expects> //<Expects Status=warning>\(18,20\).*CS0414</Expects> //<Expects Status=success></Expects> // <Code> using System; public class Test { public byte X; private sbyte _X1 = sbyte.MinValue; private ushort _Y = ushort.MinValue; protected short Y1 = short.MaxValue; internal uint Z = 0; protected internal ulong Q = ulong.MaxValue; protected long C = long.MinValue; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int ret = 0; dynamic a = new Test(); try { var v0 = checked(a.X1 -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("byte"); // expected } try { var v1 = checked(a.X1 -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("sbyte"); // expected } try { var v2 = checked(a.Y -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("ushort"); // expected } try { var v2 = checked(a.Y1 += 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("short"); // expected } try { var v3 = checked(a.Z -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("uint"); // expected } try { var v4 = checked(a.Q += 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("ulong max"); // expected } try { var v5 = checked(a.C -= 1); ret++; } catch (System.OverflowException) { System.Console.WriteLine("long min"); // expected } System.Console.WriteLine(ret); return ret == 0 ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do001.do001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do001.do001; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while ((bool)d); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do002.do002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do002.do002; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while (d); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do003.do003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.do003.do003; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool MyMethod() { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; do { x++; if (x > 2) return 0; } while (d.MyMethod()); return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if001.if001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if001.if001; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if002.if002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if002.if002; // <Title>Tests if statements</Title> // <Description> // Remove the comments when the exception is known // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if003.if003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if003.if003; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if004.if004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if004.if004; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if005.if005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if005.if005; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } public static bool operator true(myIf f) { return false; } public static bool operator false(myIf f) { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if006.if006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if006.if006; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public bool MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d.MyMethod()) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if007.if007 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if007.if007; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if (d.MyMethod()) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if008.if008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if008.if008; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { Test.Status = 1; return !this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { public static int Status = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d || (bool)d.MyMethod()) { if (Test.Status == 0) //We should have short-circuited the second call return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if009.if009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if009.if009; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public object MyMethod() { Test.Status = 1; return !this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { public static int Status = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); if ((bool)d | (bool)d.MyMethod()) { if (Test.Status == 1) //We should have short-circuited the second call return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if010.if010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.if010.if010; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); bool boo = true; if ((bool)d && (bool)boo) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch001.switch001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch001.switch001; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = "foo"; switch ((string)d) { case "foo": return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch002.switch002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.switch002.switch002; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 1; switch ((int?)d) { case 1: return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary001.ternary001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary001.ternary001; // <Title>Tests ternary operator statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return (bool)d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary002.ternary002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary002.ternary002; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary003.ternary003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary003.ternary003; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } public static bool operator true(myIf f) { return false; } public static bool operator false(myIf f) { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary004.ternary004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary004.ternary004; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public bool MyMethod() { return this.value; } public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); return d.MyMethod() ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary005.ternary005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.ternary005.ternary005; // <Title>Tests if statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static explicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); bool boo = true; return ((bool)d && (bool)boo) ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked001.unchecked001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked001.unchecked001; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { unchecked { x = (int)d.GetMaxInt() + 1; } } catch (System.OverflowException) { return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked002.unchecked002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked002.unchecked002; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myClass { public int GetMaxInt() { return int.MaxValue; } } public class Test { [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/513 public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myClass(); int x = 0; try { unchecked { x = (int)d.GetMaxInt() * 3; } } catch (System.OverflowException) { return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked003.unchecked003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unchecked003.unchecked003; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { unchecked { dynamic c_byte = (byte?)(-123); var rez = c_byte == (byte?)-123; return rez ? 0 : 1; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unsfe001.unsfe001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.unsfe001.unsfe001; // <Title>If def</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Foo { public void Set() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { { dynamic d = new Foo(); d.Set(); } if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while001.while001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while001.while001; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool value = true; public static implicit operator bool (myIf f) { return f.value; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while002.while002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while002.while002; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public static bool operator true(myIf f) { return true; } public static bool operator false(myIf f) { return false; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while003.while003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.while003.while003; // <Title>Tests do statements</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class myIf { public bool MyMethod() { return true; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new myIf(); int x = 0; while (d.MyMethod()) { x++; if (x > 2) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield001.yield001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield001.yield001; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<int> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if (item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield002.yield002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield002.yield002; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<dynamic> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield003.yield003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield003.yield003; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<dynamic> Foo() { object d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield004.yield004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.statements.yield004.yield004; // <Title>Tests checked block</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass { public IEnumerable<object> Foo() { dynamic d = 1; yield return d; } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass d = new MyClass(); foreach (var item in d.Foo()) { if ((int)item != 1) return 1; } return 0; } } // </Code> }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Build.Framework; using System.Collections.Generic; using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem; using Xunit; namespace Microsoft.Build.UnitTests { /// <summary> /// A class containing an extension to BuildEventArgs /// </summary> internal static class BuildEventArgsExtension { /// <summary> /// Extension method to help our tests without adding shipping code. /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="args">The 'this' object</param> /// <param name="other">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(this BuildEventArgs args, BuildEventArgs other) { if (Object.ReferenceEquals(args, other)) { return true; } if (Object.ReferenceEquals(other, null) || Object.ReferenceEquals(args, null)) { return false; } if (args.GetType() != other.GetType()) { return false; } if (args.Timestamp.Ticks != other.Timestamp.Ticks) { return false; } if (args.BuildEventContext != other.BuildEventContext) { return false; } if (!String.Equals(args.HelpKeyword, other.HelpKeyword, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.IsNullOrEmpty(args.Message)) { // Just in case we're matching chk against ret or vice versa, make sure the message still registers as the same string fixedArgsMessage = args.Message.Replace("\r\nThis is an unhandled exception from a task -- PLEASE OPEN A BUG AGAINST THE TASK OWNER.", String.Empty); string fixedOtherMessage = other.Message.Replace("\r\nThis is an unhandled exception from a task -- PLEASE OPEN A BUG AGAINST THE TASK OWNER.", String.Empty); if (!String.Equals(fixedArgsMessage, fixedOtherMessage, StringComparison.OrdinalIgnoreCase)) { return false; } } if (!String.Equals(args.SenderName, other.SenderName, StringComparison.OrdinalIgnoreCase)) { return false; } if (args.ThreadId != other.ThreadId) { return false; } return true; } /// <summary> /// Extension method to help our tests without adding shipping code. /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="args">The 'this' object</param> /// <param name="other">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(this BuildFinishedEventArgs args, BuildFinishedEventArgs other) { if (args.Succeeded != other.Succeeded) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compares the value fields in the class to the passed in object and check to see if they are the same. /// </summary> /// <param name="obj">Object to compare to this instance</param> /// <returns>True if the value fields are identical, false if otherwise</returns> public static bool IsEquivalent(this BuildMessageEventArgs args, BuildMessageEventArgs other) { if (args.Importance != other.Importance) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(this BuildErrorEventArgs args, BuildErrorEventArgs other) { if (args.ColumnNumber != other.ColumnNumber) { return false; } if (args.EndColumnNumber != other.EndColumnNumber) { return false; } if (args.LineNumber != other.LineNumber) { return false; } if (args.EndLineNumber != other.EndLineNumber) { return false; } if (!String.Equals(args.File, other.File, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.Code, other.Code, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.Subcategory, other.Subcategory, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(this BuildWarningEventArgs args, BuildWarningEventArgs other) { if (args.ColumnNumber != other.ColumnNumber) { return false; } if (args.EndColumnNumber != other.EndColumnNumber) { return false; } if (args.LineNumber != other.LineNumber) { return false; } if (args.EndLineNumber != other.EndLineNumber) { return false; } if (!String.Equals(args.File, other.File, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.Code, other.Code, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.Subcategory, other.Subcategory, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(ProjectStartedEventArgs args, ProjectStartedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetNames, other.TargetNames, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(ExternalProjectStartedEventArgs args, ExternalProjectStartedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetNames, other.TargetNames, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(ProjectFinishedEventArgs args, ProjectFinishedEventArgs other) { if (args.Succeeded != other.Succeeded) { return false; } if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(ExternalProjectFinishedEventArgs args, ExternalProjectFinishedEventArgs other) { if (args.Succeeded != other.Succeeded) { return false; } if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(TargetStartedEventArgs args, TargetStartedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetFile, other.TargetFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetName, other.TargetName, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.ParentTarget, other.ParentTarget, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(TargetFinishedEventArgs args, TargetFinishedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetFile, other.TargetFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TargetName, other.TargetName, StringComparison.OrdinalIgnoreCase)) { return false; } if (!Object.ReferenceEquals(args.TargetOutputs, other.TargetOutputs)) { // See if one is null, if so they are not equal if (args.TargetOutputs == null || other.TargetOutputs == null) { return false; } List<string> argItemIncludes = new List<string>(); foreach (TaskItem item in args.TargetOutputs) { argItemIncludes.Add(item.ToString()); } List<string> otherItemIncludes = new List<string>(); foreach (TaskItem item in other.TargetOutputs) { otherItemIncludes.Add(item.ToString()); } argItemIncludes.Sort(); otherItemIncludes.Sort(); if (argItemIncludes.Count != otherItemIncludes.Count) { return false; } // Since the lists are sorted each include must match for (int i = 0; i < argItemIncludes.Count; i++) { if (!argItemIncludes[i].Equals(otherItemIncludes[i], StringComparison.OrdinalIgnoreCase)) { return false; } } } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(TaskStartedEventArgs args, TaskStartedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TaskFile, other.TaskFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TaskName, other.TaskName, StringComparison.OrdinalIgnoreCase)) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } /// <summary> /// Compare this build event context with another object to determine /// equality. This means the values inside the object are identical. /// </summary> /// <param name="obj">Object to compare to this object</param> /// <returns>True if the object values are identical, false if they are not identical</returns> public static bool IsEquivalent(TaskFinishedEventArgs args, TaskFinishedEventArgs other) { if (!String.Equals(args.ProjectFile, other.ProjectFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TaskFile, other.TaskFile, StringComparison.OrdinalIgnoreCase)) { return false; } if (!String.Equals(args.TaskName, other.TaskName, StringComparison.OrdinalIgnoreCase)) { return false; } if (args.Succeeded != other.Succeeded) { return false; } return ((BuildEventArgs)args).IsEquivalent(other); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Compiler; using System.CodeDom.Compiler; // needed for CompilerError using System.Diagnostics.Contracts; namespace Microsoft.Contracts.Foxtrot { internal sealed class RepresentationFor : Attribute { internal string runtimeName; internal bool required; internal RepresentationFor(string s) { this.runtimeName = s; this.required = true; } internal RepresentationFor(string s, bool required) { this.runtimeName = s; this.required = required; } } /// <summary> /// Contains CCI nodes for common types and members in the contract library. /// </summary> /// <remarks> /// This class could be static if it referenced the Contracts assembly statically as a project reference. /// </remarks> public class ContractNodes { /// <summary>Namespace that the contract types are defined in.</summary> public static readonly Identifier ContractNamespace = Identifier.For("System.Diagnostics.Contracts"); public static readonly Identifier ContractClassName = Identifier.For("Contract"); public static readonly Identifier ContractInternalNamespace = Identifier.For("System.Runtime.CompilerServices"); //public static readonly Identifier ContractInternalNamespace = Identifier.For("System.Diagnostics.Contracts.Internal"); public static readonly Identifier RaiseContractFailedEventName = Identifier.For("RaiseContractFailedEvent"); public static readonly Identifier TriggerFailureName = Identifier.For("TriggerFailure"); public static readonly Identifier ReportFailureName = Identifier.For("ReportFailure"); public static readonly Identifier RequiresName = Identifier.For("Requires"); public static readonly Identifier RequiresAlwaysName = Identifier.For("RequiresAlways"); public static readonly Identifier EnsuresName = Identifier.For("Ensures"); public static readonly Identifier EnsuresOnThrowName = Identifier.For("EnsuresOnThrow"); public static readonly Identifier InvariantName = Identifier.For("Invariant"); public static readonly Identifier ResultName = Identifier.For("Result"); public static readonly Identifier OldName = Identifier.For("OldValue"); public static readonly Identifier ValueAtReturnName = Identifier.For("ValueAtReturn"); public static readonly Identifier ForallName = Identifier.For("ForAll"); public static readonly Identifier ExistsName = Identifier.For("Exists"); public static readonly Identifier ValidatorAttributeName = Identifier.For("ContractArgumentValidatorAttribute"); public static readonly Identifier AbbreviatorAttributeName = Identifier.For("ContractAbbreviatorAttribute"); public static readonly Identifier ContractOptionAttributeName = Identifier.For("ContractOptionAttribute"); public static readonly Identifier RuntimeIgnoredAttributeName = Identifier.For("ContractRuntimeIgnoredAttribute"); public static readonly Identifier ModelAttributeName = Identifier.For("ContractModelAttribute"); public static readonly Identifier ContractClassAttributeName = Identifier.For("ContractClassAttribute"); public static readonly Identifier ContractClassForAttributeName = Identifier.For("ContractClassForAttribute"); public static readonly Identifier SpecPublicAttributeName = Identifier.For(SpecPublicAttributeStringName); /// <summary> /// Event that is raised when an error is found. /// </summary> public event Action<CompilerError> ErrorFound; /// <summary> /// Need this just so other classes that have a reference to this instance can call it. /// For some reason it can be called only from within this class?? /// </summary> /// <param name="e">The error to pass to ErrorFound</param> public void CallErrorFound(CompilerError e) { ErrorFound(e); } // Fields that represent methods, attributes, and types in the contract library [RepresentationFor("System.Diagnostics.Contracts.PureAttribute")] public readonly Class /*?*/ PureAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractInvariantMethodAttribute")] public readonly Class /*?*/ InvariantMethodAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractClassAttribute")] internal readonly Class /*?*/ ContractClassAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractClassForAttribute")] internal readonly Class /*?*/ ContractClassForAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractVerificationAttribute")] public readonly Class /*?*/ VerifyAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractPublicPropertyNameAttribute")] internal readonly Class /*?*/ SpecPublicAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractReferenceAssemblyAttribute", false)] public readonly Class /*?*/ ReferenceAssemblyAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractRuntimeIgnoredAttribute")] public readonly Class /*?*/ IgnoreAtRuntimeAttribute; [RepresentationFor("System.Diagnostics.Contracts.ContractClass")] public readonly Class /*?*/ ContractClass; [RepresentationFor("System.Diagnostics.Contracts.Internal.ContractHelper", false)] public readonly Class /*?*/ ContractHelperClass; [RepresentationFor("System.Diagnostics.Contracts.ContractFailureKind")] public readonly EnumNode /*?*/ ContractFailureKind; [RepresentationFor("Contract.Assert(bool)")] public readonly Method /*?*/ AssertMethod; [RepresentationFor("Contract.Assert(bool, string)")] public readonly Method /*?*/ AssertWithMsgMethod; [RepresentationFor("Contract.Assume(bool b)")] public readonly Method /*?*/ AssumeMethod; [RepresentationFor("Contract.Assume(bool b, string)")] public readonly Method /*?*/ AssumeWithMsgMethod; [RepresentationFor("Contract.Requires(bool)")] public readonly Method /*?*/ RequiresMethod; [RepresentationFor("Contract.Requires(bool,string)")] public readonly Method /*?*/ RequiresWithMsgMethod; [RepresentationFor("Contract.Requires<TException>(bool)", false)] public readonly Method /*?*/ RequiresExceptionMethod; [RepresentationFor("Contract.Requires<TException>(bool,string)", false)] public readonly Method /*?*/ RequiresExceptionWithMsgMethod; [RepresentationFor("Contract.Ensures(bool)")] public readonly Method /*?*/ EnsuresMethod; [RepresentationFor("Contract.Ensures(bool,string)")] public readonly Method /*?*/ EnsuresWithMsgMethod; [RepresentationFor("Contract.EnsuresOnThrow<T>(bool)")] public readonly Method /*?*/ EnsuresOnThrowTemplate; [RepresentationFor("Contract.EnsuresOnThrow<T>(bool,string)")] public readonly Method /*?*/ EnsuresOnThrowWithMsgTemplate; [RepresentationFor("Contract.Invariant(bool)")] public readonly Method /*?*/ InvariantMethod; [RepresentationFor("Contract.Invariant(bool,msg)")] public readonly Method /*?*/ InvariantWithMsgMethod; [RepresentationFor("Contract.Result<T>()")] private readonly Method /*?*/ ResultTemplate; [RepresentationFor("Contract.ValueAtReturn<T>(out T t)")] private readonly Method /*?*/ ParameterTemplate; [RepresentationFor("Contract.OldValue<T>(T t)")] private readonly Method /*?*/ OldTemplate; [RepresentationFor("Contract.ForAll(int lo, int hi, Predicate<int> P)", false)] private readonly Method /*?*/ ForAllTemplate; [RepresentationFor("Contract.ForAll<T>(IEnumerable<T> collection, Predicate<int> P)", false)] private readonly Method /*?*/ ForAllGenericTemplate; [RepresentationFor("Contract.Exists(int lo, int hi, Predicate<int> P)", false)] private readonly Method /*?*/ ExistsTemplate; [RepresentationFor("Contract.Exists<T>(IEnumerable<T> collection, Predicate<int> P)", false)] private readonly Method /*?*/ ExistsGenericTemplate; [RepresentationFor("Contract.EndContractBlock()")] public readonly Method /*?*/ EndContract; [RepresentationFor("ContractHelper.RaiseContractFailedEvent(ContractFailureKind failureKind, String userProvidedMessage, String condition, Exception originalException)", false)] public readonly Method /*?*/ RaiseFailedEventMethod; [RepresentationFor( "ContractHelper.ShowFailure(ContractFailureKind failureKind, String displayMessage, String userProvidedMessage, String condition, Exception originalException)", false)] public readonly Method /*?*/ TriggerFailureMethod; /// <summary> /// If <paramref name="assembly"/> is null then this looks for the contract class in mscorlib. /// If it isn't null then it searches in <paramref name="assembly"/> for the contract class. /// Returns null if the contract class is not found. /// </summary> public static ContractNodes GetContractNodes(AssemblyNode assembly, Action<CompilerError> errorHandler) { ContractNodes contractNodes = new ContractNodes(assembly, errorHandler); if (contractNodes.ContractClass == null) { return null; } return contractNodes; } private void CallWarningFound(Module assembly, string message) { if (ErrorFound == null) { throw new InvalidOperationException(message); } var error = new CompilerError(assembly.Location, 0, 0, "", message); error.IsWarning = true; ErrorFound(error); } private void CallErrorFound(Module assembly, string message) { if (ErrorFound == null) { throw new InvalidOperationException(message); } ErrorFound(new System.CodeDom.Compiler.CompilerError(assembly.Location, 0, 0, "", message)); } public const string SpecPublicAttributeStringName = "ContractPublicPropertyNameAttribute"; /// <summary> /// Creates a new instance of this class that contains the CCI nodes for contract class. /// </summary> /// <param name="errorHandler">Delegate receiving errors. If null, errors are thrown as exceptions.</param> /// private ContractNodes(AssemblyNode assembly, Action<System.CodeDom.Compiler.CompilerError> errorHandler) { if (errorHandler != null) this.ErrorFound += errorHandler; AssemblyNode assemblyContainingContractClass = null; // Get the contract class and all of its members assemblyContainingContractClass = assembly; ContractClass = assembly.GetType(ContractNamespace, Identifier.For("Contract")) as Class; if (ContractClass == null) { // This is not a candidate, no warning as we try to find the right place where contracts live return; } ContractHelperClass = assembly.GetType(ContractInternalNamespace, Identifier.For("ContractHelper")) as Class; if (ContractHelperClass == null || !ContractHelperClass.IsPublic) { // look in alternate location var alternateNs = Identifier.For("System.Diagnostics.Contracts.Internal"); ContractHelperClass = assembly.GetType(alternateNs, Identifier.For("ContractHelper")) as Class; } // Get ContractFailureKind ContractFailureKind = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractFailureKind")) as EnumNode; // Look for each member of the contract class var requiresMethods = ContractClass.GetMethods(Identifier.For("Requires"), SystemTypes.Boolean); for (int i = 0; i < requiresMethods.Count; i++) { var method = requiresMethods[i]; if (method.TemplateParameters != null && method.TemplateParameters.Count == 1) { // Requires<E> RequiresExceptionMethod = method; } else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0) { RequiresMethod = method; } } // early test to see if the ContractClass we found has a Requires(bool) method. If it doesn't, we // silently think that this is not the right place. // We use this because contract reference assemblies have a Contract class, but it is not the right one, as it holds // just the 3 argument versions of all the contract methods. if (RequiresMethod == null) { ContractClass = null; return; } var requiresMethodsWithMsg = ContractClass.GetMethods(Identifier.For("Requires"), SystemTypes.Boolean, SystemTypes.String); for (int i = 0; i < requiresMethodsWithMsg.Count; i++) { var method = requiresMethodsWithMsg[i]; if (method.TemplateParameters != null && method.TemplateParameters.Count == 1) { // Requires<E> RequiresExceptionWithMsgMethod = method; } else if (method.TemplateParameters == null || method.TemplateParameters.Count == 0) { RequiresWithMsgMethod = method; } } EnsuresMethod = ContractClass.GetMethod(Identifier.For("Ensures"), SystemTypes.Boolean); EnsuresWithMsgMethod = ContractClass.GetMethod(Identifier.For("Ensures"), SystemTypes.Boolean, SystemTypes.String); EnsuresOnThrowTemplate = ContractClass.GetMethod(Identifier.For("EnsuresOnThrow"), SystemTypes.Boolean); EnsuresOnThrowWithMsgTemplate = ContractClass.GetMethod(Identifier.For("EnsuresOnThrow"), SystemTypes.Boolean, SystemTypes.String); InvariantMethod = ContractClass.GetMethod(Identifier.For("Invariant"), SystemTypes.Boolean); InvariantWithMsgMethod = ContractClass.GetMethod(Identifier.For("Invariant"), SystemTypes.Boolean, SystemTypes.String); AssertMethod = ContractClass.GetMethod(Identifier.For("Assert"), SystemTypes.Boolean); AssertWithMsgMethod = ContractClass.GetMethod(Identifier.For("Assert"), SystemTypes.Boolean, SystemTypes.String); AssumeMethod = ContractClass.GetMethod(Identifier.For("Assume"), SystemTypes.Boolean); AssumeWithMsgMethod = ContractClass.GetMethod(Identifier.For("Assume"), SystemTypes.Boolean, SystemTypes.String); ResultTemplate = ContractClass.GetMethod(ResultName); TypeNode GenericPredicate = SystemTypes.SystemAssembly.GetType( Identifier.For("System"), Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1")); if (GenericPredicate != null) { ForAllGenericTemplate = ContractClass.GetMethod(ForallName, SystemTypes.GenericIEnumerable, GenericPredicate); ExistsGenericTemplate = ContractClass.GetMethod(ExistsName, SystemTypes.GenericIEnumerable, GenericPredicate); if (ForAllGenericTemplate == null) { // The problem might be that we are in the pre 4.0 scenario and using an out-of-band contract for mscorlib // in which case the contract library is defined in that out-of-band contract assembly. // If so, then ForAll and Exists are defined in terms of the System.Predicate defined in the out-of-band assembly. var tempGenericPredicate = assemblyContainingContractClass.GetType( Identifier.For("System"), Identifier.For("Predicate" + TargetPlatform.GenericTypeNamesMangleChar + "1")); if (tempGenericPredicate != null) { GenericPredicate = tempGenericPredicate; TypeNode genericIEnum = assemblyContainingContractClass.GetType(Identifier.For("System.Collections.Generic"), Identifier.For("IEnumerable" + TargetPlatform.GenericTypeNamesMangleChar + "1")); ForAllGenericTemplate = ContractClass.GetMethod(Identifier.For("ForAll"), genericIEnum, GenericPredicate); ExistsGenericTemplate = ContractClass.GetMethod(Identifier.For("Exists"), genericIEnum, GenericPredicate); } } TypeNode PredicateOfInt = GenericPredicate.GetTemplateInstance(ContractClass, SystemTypes.Int32); if (PredicateOfInt != null) { ForAllTemplate = ContractClass.GetMethod(Identifier.For("ForAll"), SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt); ExistsTemplate = ContractClass.GetMethod(Identifier.For("Exists"), SystemTypes.Int32, SystemTypes.Int32, PredicateOfInt); } } foreach (Member member in ContractClass.GetMembersNamed(ValueAtReturnName)) { Method method = member as Method; if (method != null && method.Parameters.Count == 1) { Reference reference = method.Parameters[0].Type as Reference; if (reference != null && reference.ElementType.IsTemplateParameter) { ParameterTemplate = method; break; } } } foreach (Member member in ContractClass.GetMembersNamed(OldName)) { Method method = member as Method; if (method != null && method.Parameters.Count == 1 && method.Parameters[0].Type.IsTemplateParameter) { OldTemplate = method; break; } } EndContract = ContractClass.GetMethod(Identifier.For("EndContractBlock")); if (this.ContractFailureKind != null) { if (ContractHelperClass != null) { RaiseFailedEventMethod = ContractHelperClass.GetMethod(ContractNodes.RaiseContractFailedEventName, this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.Exception); TriggerFailureMethod = ContractHelperClass.GetMethod(ContractNodes.TriggerFailureName, this.ContractFailureKind, SystemTypes.String, SystemTypes.String, SystemTypes.String, SystemTypes.Exception); } } // Get the attributes PureAttribute = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("PureAttribute")) as Class; InvariantMethodAttribute = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractInvariantMethodAttribute")) as Class; ContractClassAttribute = assemblyContainingContractClass.GetType(ContractNamespace, ContractClassAttributeName) as Class; ContractClassForAttribute = assemblyContainingContractClass.GetType(ContractNamespace, ContractClassForAttributeName) as Class; VerifyAttribute = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractVerificationAttribute")) as Class; SpecPublicAttribute = assemblyContainingContractClass.GetType(ContractNamespace, SpecPublicAttributeName) as Class; ReferenceAssemblyAttribute = assemblyContainingContractClass.GetType(ContractNamespace, Identifier.For("ContractReferenceAssemblyAttribute")) as Class; IgnoreAtRuntimeAttribute = assemblyContainingContractClass.GetType(ContractNamespace, RuntimeIgnoredAttributeName) as Class; // Check that every field in this class has been set foreach (System.Reflection.FieldInfo field in typeof (ContractNodes).GetFields()) { if (field.GetValue(this) == null) { string sig = null; bool required = false; object[] cas = field.GetCustomAttributes(typeof (RepresentationFor), false); for (int i = 0, n = cas.Length; i < n; i++) { // should be exactly one RepresentationFor rf = cas[i] as RepresentationFor; if (rf != null) { sig = rf.runtimeName; required = rf.required; break; } } if (!required) continue; string msg = "Could not find contract node for '" + field.Name + "'"; if (sig != null) msg = "Could not find the method/type '" + sig + "'"; if (ContractClass != null && ContractClass.DeclaringModule != null) { msg += " in assembly '" + ContractClass.DeclaringModule.Location + "'"; } Module dm = ContractClass.DeclaringModule; ClearFields(); CallErrorFound(dm, msg); return; } } // Check that ContractFailureKind is okay if (this.ContractFailureKind.GetField(Identifier.For("Assert")) == null || this.ContractFailureKind.GetField(Identifier.For("Assume")) == null || this.ContractFailureKind.GetField(Identifier.For("Invariant")) == null || this.ContractFailureKind.GetField(Identifier.For("Postcondition")) == null || this.ContractFailureKind.GetField(Identifier.For("Precondition")) == null ) { Module dm = ContractClass.DeclaringModule; ClearFields(); CallErrorFound(dm, "The enum ContractFailureKind must have the values 'Assert', 'Assume', 'Invariant', 'Postcondition', and 'Precondition'."); } } /// <summary> /// For those fields in this class that represent things (methods, types, etc.) from the contract library, /// this method (re)sets them to null. It uses Reflection. /// </summary> private void ClearFields() { foreach (System.Reflection.FieldInfo field in typeof (ContractNodes).GetFields()) { object[] cas = field.GetCustomAttributes(typeof (RepresentationFor), false); if (cas != null && cas.Length == 1) { field.SetValue(this, null); } } } [Pure] public bool IsContractOrValidatorOrAbbreviatorCall(Statement s) { Contract.Ensures(!Contract.Result<bool>() || s != null); Method m = HelperMethods.IsMethodCall(s); if (m == null) return false; return IsContractOrValidatorOrAbbreviatorMethod(m); } /// <summary> /// Analyzes a statement to see if it is a call to one of the contract methods, /// such as Contract.Requires. /// </summary> /// <param name="s">Any statement.</param> /// <returns>System.Contracts.Contract.xxx where xxx is Requires, Ensures, etc. or null</returns> public Method IsContractCall(Statement s) { Method m = HelperMethods.IsMethodCall(s); if (m == null) return null; if (this.IsContractMethod(m)) { return m; } return null; } public static bool IsValidatorCall(Statement s) { Method m = HelperMethods.IsMethodCall(s); if (m == null) return false; if (IsValidatorMethod(m)) { return true; } return false; } public static bool IsAlreadyRewritten(Module module) { foreach (var attr in module.Attributes) { if (attr == null) continue; if (attr.Type.FullName == "System.Diagnostics.Contracts.RuntimeContractsAttribute") return true; } return false; } public bool IsContractOrValidatorOrAbbreviatorMethod(Method m) { return IsValidatorMethod(m) || IsContractMethod(m) || IsAbbreviatorMethod(m); } public static bool IsAbbreviatorMethod(Method m) { if (m == null) return false; while (m.Template != null) { m = m.Template; } return (m.Attributes.HasAttribute(AbbreviatorAttributeName)); } public static bool IsValidatorMethod(Method m) { if (m == null) return false; while (m.Template != null) { m = m.Template; } return (m.Attributes.HasAttribute(ValidatorAttributeName)); } public bool IsContractMethod(Method m) { if (m == null) return false; return this.IsPlainPrecondition(m) || this.IsPostcondition(m) || this.IsExceptionalPostcondition(m) || this.IsEndContract(m); } public bool IsEndContract(Method m) { return m == this.EndContract; } public bool IsPlainPrecondition(Method m) { TypeNode typeArg; return IsContractMethod(RequiresName, m, out typeArg) || // Beta1 backward compat IsContractMethod(RequiresAlwaysName, m, out typeArg); } public bool IsRequiresWithException(Method m, out TypeNode texception) { if (IsContractMethod(RequiresName, m, out texception) && texception != null) return true; // backward compat if (IsContractMethod(RequiresAlwaysName, m, out texception)) { texception = SystemTypes.ArgumentException; return true; } return false; } /// <summary> /// Returns the invariant condition or null if statement is not invariant method call /// </summary> /// <param name="name">Optional string of invariant</param> public Expression IsInvariant(Statement s, out Literal name, out Literal sourceText) { name = null; sourceText = null; if (s == null) return null; ExpressionStatement es = s as ExpressionStatement; if (es == null) return null; MethodCall mc = es.Expression as MethodCall; if (mc == null) return null; MemberBinding mb = mc.Callee as MemberBinding; if (mb == null) return null; Method m = mb.BoundMember as Method; if (m == null) return null; if (this.IsInvariantMethod(m)) { if (mc.Operands.Count > 1) { name = mc.Operands[1] as Literal; } if (mc.Operands.Count > 2) { sourceText = mc.Operands[2] as Literal; } return mc.Operands[0]; } return null; } public bool IsInvariantMethod(Method m) { if (m == null) return false; TypeNode typeArg; return IsContractMethod(InvariantName, m, out typeArg) && typeArg == null; } public bool IsPostcondition(Method m) { TypeNode typeArg; return IsContractMethod(EnsuresName, m, out typeArg) && typeArg == null; } public bool IsExceptionalPostcondition(Method m) { TypeNode excType; return IsContractMethod(EnsuresOnThrowName, m, out excType) && excType != null; } public bool IsContractMethod(Identifier name, Method m, out TypeNode genericArg) { genericArg = null; if (m == null) return false; if (m.Template != null) { if (m.TemplateArguments == null) return false; if (m.TemplateArguments.Count != 1) return false; genericArg = m.TemplateArguments[0]; m = m.Template; } if (m.Name == null) return false; if (m.Name.UniqueIdKey != name.UniqueIdKey) return false; if (m.DeclaringType == this.ContractClass) return true; // Reference assemblies *always* use a three-argument method which is defined in the // reference assembly itself. // REVIEW: Could also check that the assembly m is defined in is marked with // the [ContractReferenceAssembly] attribute if (m.Parameters == null || m.Parameters.Count != 3) return false; if (m.DeclaringType == null || m.DeclaringType.Namespace == null) return false; if (m.DeclaringType.Namespace.Name == null || m.DeclaringType.Namespace.Name != "System.Diagnostics.Contracts") { return false; } if (m.DeclaringType.Name != null && m.DeclaringType.Name.Name == "Contract") return true; return false; } private bool AreAnyPure(MethodList methods) { if (methods == null || methods.Count == 0) return false; for (int i = 0; i < methods.Count; i++) { if (IsPure(methods[i])) return true; } return false; } private static bool HasPureAttribute(AttributeList attributes) { if (attributes == null) return false; for (int i = 0; i < attributes.Count; i++) { if (attributes[i] == null) continue; if (attributes[i].Type == null) continue; if (attributes[i].Type.Name == null) continue; if (attributes[i].Type.Name.Name == "PureAttribute") return true; } return false; } [Pure] public bool IsPure(Method method) { if (method == null) return false; while (method.Template != null) { method = method.Template; } if (method.Contract != null && method.Contract.IsPure) return true; if (method.IsPropertyGetter) return true; if (HasPureAttribute(method.Attributes)) return true; if (!(method is InstanceInitializer) && HasPureAttribute(method.DeclaringType.Attributes)) return true; // Operators are pure by default if (IsOperator(method)) return true; if (method.OverriddenMethod != null && IsPure(method.OverriddenMethod)) return true; if (AreAnyPure(method.ImplementedInterfaceMethods)) return true; if (AreAnyPure(method.ImplicitlyImplementedInterfaceMethods)) return true; if (IsForallMethod(method) || IsGenericForallMethod(method) || IsExistsMethod(method) || IsGenericExistsMethod(method)) return true; if (IsFuncOrPredicate(method)) return true; return false; } private static bool IsOperator(Method method) { return method.IsSpecialName && method.IsStatic && method.Name != null && method.Name.Name != null && method.Name.Name.StartsWith("op_") && method.Parameters != null && (method.Parameters.Count == 1 || method.Parameters.Count == 2) && !HelperMethods.IsVoidType(method.ReturnType); } public bool IsResultMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ResultTemplate) return true; // by name matching return method.MatchesContractByName(ResultName); } public bool IsOldMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == OldTemplate) return true; // by name matching return method.MatchesContractByName(OldName); } public bool IsValueAtReturnMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ParameterTemplate) return true; // by name matching return method.MatchesContractByName(ValueAtReturnName); } public bool IsForallMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ForAllTemplate) return true; // by name matching if (method.TemplateParameters != null && method.TemplateParameters.Count > 0) return false; return method.MatchesContractByName(ForallName); } public bool IsGenericForallMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ForAllGenericTemplate) return true; // by name matching if (method.TemplateParameters == null || method.TemplateParameters.Count != 1) return false; return method.MatchesContractByName(ForallName); } public Method GetForAllTemplate { get { return this.ForAllTemplate; } } public Method GetForAllGenericTemplate { get { return this.ForAllGenericTemplate; } } public bool IsExistsMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ExistsTemplate) return true; // by name matching if (method.TemplateParameters != null && method.TemplateParameters.Count > 0) return false; return method.MatchesContractByName(ExistsName); } public bool IsGenericExistsMethod(Method method) { if (method == null) return false; if (method.Template != null) { method = method.Template; } if (method == ExistsGenericTemplate) return true; // by name matching if (method.TemplateParameters == null || method.TemplateParameters.Count != 1) return false; return method.MatchesContractByName(ExistsName); } public Method GetExistsTemplate { get { return this.ExistsTemplate; } } public Method GetExistsGenericTemplate { get { return this.ExistsGenericTemplate; } } [Pure] public bool IsObjectInvariantMethod(Method method) { if (method == null) return false; if (method.Attributes != null) { foreach (var a in method.Attributes) { if (a == null) continue; if (a.Type == this.InvariantMethodAttribute) return true; // by name matching if (a.Type.MatchesContractByName(this.InvariantMethodAttribute.Name)) return true; } } return false; } [Pure] public static bool IsFuncOrPredicate(Method method) { if (method == null) return false; if (!(method.DeclaringType.IsDelegateType())) return false; var declaringRoot = HelperMethods.Unspecialize(method.DeclaringType); if (declaringRoot.Namespace.Name != "System") return false; if (declaringRoot.Name.Name == "Predicate`1") return true; if (declaringRoot.Name.Name.StartsWith("Func`")) return true; return false; } } }
using System; using System.Collections.Generic; using NServiceKit.ServiceInterface.ServiceModel; namespace NServiceKit.ServiceHost.Tests.AppData { /// <summary>A customers.</summary> public class Customers { } /// <summary>The customers response.</summary> public class CustomersResponse : IHasResponseStatus { /// <summary>Initializes a new instance of the NServiceKit.ServiceHost.Tests.AppData.CustomersResponse class.</summary> public CustomersResponse() { this.ResponseStatus = new ResponseStatus(); this.Customers = new List<Customer>(); } /// <summary>Gets or sets the customers.</summary> /// /// <value>The customers.</value> public List<Customer> Customers { get; set; } /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> public ResponseStatus ResponseStatus { get; set; } } /// <summary>A customer details.</summary> public class CustomerDetails { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get; set; } } /// <summary>A customer details response.</summary> public class CustomerDetailsResponse : IHasResponseStatus { /// <summary>Initializes a new instance of the NServiceKit.ServiceHost.Tests.AppData.CustomerDetailsResponse class.</summary> public CustomerDetailsResponse() { this.ResponseStatus = new ResponseStatus(); this.CustomerOrders = new List<CustomerOrder>(); } /// <summary>Gets or sets the customer.</summary> /// /// <value>The customer.</value> public Customer Customer { get; set; } /// <summary>Gets or sets the customer orders.</summary> /// /// <value>The customer orders.</value> public List<CustomerOrder> CustomerOrders { get; set; } /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> public ResponseStatus ResponseStatus { get; set; } } /// <summary>An orders.</summary> public class Orders { /// <summary>Gets or sets the page.</summary> /// /// <value>The page.</value> public int? Page { get; set; } /// <summary>Gets or sets the identifier of the customer.</summary> /// /// <value>The identifier of the customer.</value> public string CustomerId { get; set; } } /// <summary>The orders response.</summary> public class OrdersResponse : IHasResponseStatus { /// <summary>Initializes a new instance of the NServiceKit.ServiceHost.Tests.AppData.OrdersResponse class.</summary> public OrdersResponse() { this.ResponseStatus = new ResponseStatus(); this.Results = new List<CustomerOrder>(); } /// <summary>Gets or sets the results.</summary> /// /// <value>The results.</value> public List<CustomerOrder> Results { get; set; } /// <summary>Gets or sets the response status.</summary> /// /// <value>The response status.</value> public ResponseStatus ResponseStatus { get; set; } } /// <summary>A category.</summary> public class Category { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the name of the category.</summary> /// /// <value>The name of the category.</value> public string CategoryName { get; set; } /// <summary>Gets or sets the description.</summary> /// /// <value>The description.</value> public string Description { get; set; } } /// <summary>A customer.</summary> public class Customer { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get; set; } /// <summary>Gets or sets the name of the company.</summary> /// /// <value>The name of the company.</value> public string CompanyName { get; set; } /// <summary>Gets or sets the name of the contact.</summary> /// /// <value>The name of the contact.</value> public string ContactName { get; set; } /// <summary>Gets or sets the contact title.</summary> /// /// <value>The contact title.</value> public string ContactTitle { get; set; } /// <summary>Gets or sets the address.</summary> /// /// <value>The address.</value> public string Address { get; set; } /// <summary>Gets or sets the city.</summary> /// /// <value>The city.</value> public string City { get; set; } /// <summary>Gets or sets the region.</summary> /// /// <value>The region.</value> public string Region { get; set; } /// <summary>Gets or sets the postal code.</summary> /// /// <value>The postal code.</value> public string PostalCode { get; set; } /// <summary>Gets or sets the country.</summary> /// /// <value>The country.</value> public string Country { get; set; } /// <summary>Gets or sets the phone.</summary> /// /// <value>The phone.</value> public string Phone { get; set; } /// <summary>Gets or sets the fax.</summary> /// /// <value>The fax.</value> public string Fax { get; set; } /// <summary>Gets the email.</summary> /// /// <value>The email.</value> public string Email { get { return this.ContactName.Replace(" ", ".").ToLower() + "@gmail.com"; } } } /// <summary>A customer demo.</summary> public class CustomerCustomerDemo { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get; set; } /// <summary>Gets or sets the identifier of the customer type.</summary> /// /// <value>The identifier of the customer type.</value> public string CustomerTypeId { get; set; } } /// <summary>A customer demographic.</summary> public class CustomerDemographic { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get; set; } /// <summary>Gets or sets information describing the customer.</summary> /// /// <value>Information describing the customer.</value> public string CustomerDesc { get; set; } } /// <summary>A customer order.</summary> public class CustomerOrder { /// <summary>Initializes a new instance of the NServiceKit.ServiceHost.Tests.AppData.CustomerOrder class.</summary> public CustomerOrder() { this.OrderDetails = new List<OrderDetail>(); } /// <summary>Gets or sets the order.</summary> /// /// <value>The order.</value> public Order Order { get; set; } /// <summary>Gets or sets the order details.</summary> /// /// <value>The order details.</value> public List<OrderDetail> OrderDetails { get; set; } } /// <summary>An employee.</summary> public class Employee { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the person's last name.</summary> /// /// <value>The name of the last.</value> public string LastName { get; set; } /// <summary>Gets or sets the person's first name.</summary> /// /// <value>The name of the first.</value> public string FirstName { get; set; } /// <summary>Gets or sets the title.</summary> /// /// <value>The title.</value> public string Title { get; set; } /// <summary>Gets or sets the title of courtesy.</summary> /// /// <value>The title of courtesy.</value> public string TitleOfCourtesy { get; set; } /// <summary>Gets or sets the birth date.</summary> /// /// <value>The birth date.</value> public DateTime? BirthDate { get; set; } /// <summary>Gets or sets the hire date.</summary> /// /// <value>The hire date.</value> public DateTime? HireDate { get; set; } /// <summary>Gets or sets the address.</summary> /// /// <value>The address.</value> public string Address { get; set; } /// <summary>Gets or sets the city.</summary> /// /// <value>The city.</value> public string City { get; set; } /// <summary>Gets or sets the region.</summary> /// /// <value>The region.</value> public string Region { get; set; } /// <summary>Gets or sets the postal code.</summary> /// /// <value>The postal code.</value> public string PostalCode { get; set; } /// <summary>Gets or sets the country.</summary> /// /// <value>The country.</value> public string Country { get; set; } /// <summary>Gets or sets the home phone.</summary> /// /// <value>The home phone.</value> public string HomePhone { get; set; } /// <summary>Gets or sets the extension.</summary> /// /// <value>The extension.</value> public string Extension { get; set; } /// <summary>Gets or sets the photo.</summary> /// /// <value>The photo.</value> public byte[] Photo { get; set; } /// <summary>Gets or sets the notes.</summary> /// /// <value>The notes.</value> public string Notes { get; set; } /// <summary>Gets or sets the reports to.</summary> /// /// <value>The reports to.</value> public int? ReportsTo { get; set; } /// <summary>Gets or sets the full pathname of the photo file.</summary> /// /// <value>The full pathname of the photo file.</value> public string PhotoPath { get; set; } } /// <summary>An employee territory.</summary> public class EmployeeTerritory { /// <summary>Gets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get { return this.EmployeeId + "/" + this.TerritoryId; } } /// <summary>Gets or sets the identifier of the employee.</summary> /// /// <value>The identifier of the employee.</value> public int EmployeeId { get; set; } /// <summary>Gets or sets the identifier of the territory.</summary> /// /// <value>The identifier of the territory.</value> public string TerritoryId { get; set; } } /// <summary>An order.</summary> public class Order { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the identifier of the customer.</summary> /// /// <value>The identifier of the customer.</value> public string CustomerId { get; set; } /// <summary>Gets or sets the identifier of the employee.</summary> /// /// <value>The identifier of the employee.</value> public int EmployeeId { get; set; } /// <summary>Gets or sets the order date.</summary> /// /// <value>The order date.</value> public DateTime? OrderDate { get; set; } /// <summary>Gets or sets the required date.</summary> /// /// <value>The required date.</value> public DateTime? RequiredDate { get; set; } /// <summary>Gets or sets the shipped date.</summary> /// /// <value>The shipped date.</value> public DateTime? ShippedDate { get; set; } /// <summary>Gets or sets the ship via.</summary> /// /// <value>The ship via.</value> public int? ShipVia { get; set; } /// <summary>Gets or sets the freight.</summary> /// /// <value>The freight.</value> public decimal Freight { get; set; } /// <summary>Gets or sets the name of the ship.</summary> /// /// <value>The name of the ship.</value> public string ShipName { get; set; } /// <summary>Gets or sets the ship address.</summary> /// /// <value>The ship address.</value> public string ShipAddress { get; set; } /// <summary>Gets or sets the ship city.</summary> /// /// <value>The ship city.</value> public string ShipCity { get; set; } /// <summary>Gets or sets the ship region.</summary> /// /// <value>The ship region.</value> public string ShipRegion { get; set; } /// <summary>Gets or sets the ship postal code.</summary> /// /// <value>The ship postal code.</value> public string ShipPostalCode { get; set; } /// <summary>Gets or sets the ship country.</summary> /// /// <value>The ship country.</value> public string ShipCountry { get; set; } } /// <summary>An order detail.</summary> public class OrderDetail { /// <summary>Gets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get { return this.OrderId + "/" + this.ProductId; } } /// <summary>Gets or sets the identifier of the order.</summary> /// /// <value>The identifier of the order.</value> public int OrderId { get; set; } /// <summary>Gets or sets the identifier of the product.</summary> /// /// <value>The identifier of the product.</value> public int ProductId { get; set; } /// <summary>Gets or sets the unit price.</summary> /// /// <value>The unit price.</value> public decimal UnitPrice { get; set; } /// <summary>Gets or sets the quantity.</summary> /// /// <value>The quantity.</value> public short Quantity { get; set; } /// <summary>Gets or sets the discount.</summary> /// /// <value>The discount.</value> public double Discount { get; set; } } /// <summary>A product.</summary> public class Product { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the name of the product.</summary> /// /// <value>The name of the product.</value> public string ProductName { get; set; } /// <summary>Gets or sets the identifier of the supplier.</summary> /// /// <value>The identifier of the supplier.</value> public int SupplierId { get; set; } /// <summary>Gets or sets the identifier of the category.</summary> /// /// <value>The identifier of the category.</value> public int CategoryId { get; set; } /// <summary>Gets or sets the quantity per unit.</summary> /// /// <value>The quantity per unit.</value> public string QuantityPerUnit { get; set; } /// <summary>Gets or sets the unit price.</summary> /// /// <value>The unit price.</value> public decimal UnitPrice { get; set; } /// <summary>Gets or sets the units in stock.</summary> /// /// <value>The units in stock.</value> public short UnitsInStock { get; set; } /// <summary>Gets or sets the units on order.</summary> /// /// <value>The units on order.</value> public short UnitsOnOrder { get; set; } /// <summary>Gets or sets the reorder level.</summary> /// /// <value>The reorder level.</value> public short ReorderLevel { get; set; } /// <summary>Gets or sets a value indicating whether the discontinued.</summary> /// /// <value>true if discontinued, false if not.</value> public bool Discontinued { get; set; } } /// <summary>A region.</summary> public class Region { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets information describing the region.</summary> /// /// <value>Information describing the region.</value> public string RegionDescription { get; set; } } /// <summary>A shipper.</summary> public class Shipper { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the name of the company.</summary> /// /// <value>The name of the company.</value> public string CompanyName { get; set; } /// <summary>Gets or sets the phone.</summary> /// /// <value>The phone.</value> public string Phone { get; set; } } /// <summary>A supplier.</summary> public class Supplier { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public int Id { get; set; } /// <summary>Gets or sets the name of the company.</summary> /// /// <value>The name of the company.</value> public string CompanyName { get; set; } /// <summary>Gets or sets the name of the contact.</summary> /// /// <value>The name of the contact.</value> public string ContactName { get; set; } /// <summary>Gets or sets the contact title.</summary> /// /// <value>The contact title.</value> public string ContactTitle { get; set; } /// <summary>Gets or sets the address.</summary> /// /// <value>The address.</value> public string Address { get; set; } /// <summary>Gets or sets the city.</summary> /// /// <value>The city.</value> public string City { get; set; } /// <summary>Gets or sets the region.</summary> /// /// <value>The region.</value> public string Region { get; set; } /// <summary>Gets or sets the postal code.</summary> /// /// <value>The postal code.</value> public string PostalCode { get; set; } /// <summary>Gets or sets the country.</summary> /// /// <value>The country.</value> public string Country { get; set; } /// <summary>Gets or sets the phone.</summary> /// /// <value>The phone.</value> public string Phone { get; set; } /// <summary>Gets or sets the fax.</summary> /// /// <value>The fax.</value> public string Fax { get; set; } /// <summary>Gets or sets the home page.</summary> /// /// <value>The home page.</value> public string HomePage { get; set; } } /// <summary>A territory.</summary> public class Territory { /// <summary>Gets or sets the identifier.</summary> /// /// <value>The identifier.</value> public string Id { get; set; } /// <summary>Gets or sets information describing the territory.</summary> /// /// <value>Information describing the territory.</value> public string TerritoryDescription { get; set; } /// <summary>Gets or sets the identifier of the region.</summary> /// /// <value>The identifier of the region.</value> public int RegionId { get; set; } } }